在此代码中,此行导致异常:
clearText = c.doFinal(Base64.decode(encryptedText, Base64.DEFAULT));
javax.crypto.BadPaddingException: pad block corrupted
我从以下代码获得了代码: http://www.techrepublic.com/blog/software-engineer/attention-android-developers-keep-user-data-safe/
有什么想法吗?
private String decrypt (String encryptedText) {
byte[] clearText = null;
try {
SecretKeySpec ks = new SecretKeySpec(getKey(), "AES");
Cipher c = Cipher.getInstance("AES");
c.init(Cipher.DECRYPT_MODE, ks);
clearText = c.doFinal(Base64.decode(encryptedText, Base64.DEFAULT));
return new String(clearText, "UTF-8");
} catch (Exception e) {
return null;
}
}
详细信息:我在android上加密它
答案 0 :(得分:6)
Java + Android + Encryption + Exception通常意味着一件事,有人再次使用SecureRandom
类作为密钥派生函数。当SecureRandom
"SHA1PRNG"
的实现与Sun在Java SE中的实现不同时,这会失败。特别是如果种子添加到随机数生成器的状态而不是种子被用作PRNG的起点。
基本上,只需使用SecretKey aesKey = new SecretKeySpec(byte[] keyData, "AES")
,或者 - 如果您从密码开始 - 尝试使用PBKDF2生成密钥。
答案 1 :(得分:6)
owlstead的建议很有帮助,但在这种情况下使用
中的代码Android开发人员注意:保护用户数据安全 http://www.techrepublic.com/blog/software-engineer/attention-android-developers-keep-user-data-safe/
我对代码做了一些更改,可能对将来的其他人有所帮助。我完全删除了getkey方法。
private static String seed;
/**
* Encrypts the text.
* @param clearText The text you want to encrypt
* @return Encrypted data if successful, or null if unsucessful
*/
protected String encrypt(String clearText) {
byte[] encryptedText = null;
try {
byte[] keyData = seed.getBytes();
SecretKey ks = new SecretKeySpec(keyData, "AES");
Cipher c = Cipher.getInstance("AES");
c.init(Cipher.ENCRYPT_MODE, ks);
encryptedText = c.doFinal(clearText.getBytes("UTF-8"));
return Base64.encodeToString(encryptedText, Base64.DEFAULT);
} catch (Exception e) {
return null;
}
}
/**
* Decrypts the text
* @param encryptedText The text you want to encrypt
* @return Decrypted data if successful, or null if unsucessful
*/
protected String decrypt (String encryptedText) {
byte[] clearText = null;
try {
byte[] keyData = seed.getBytes();
SecretKey ks = new SecretKeySpec(keyData, "AES");
Cipher c = Cipher.getInstance("AES");
c.init(Cipher.DECRYPT_MODE, ks);
clearText = c.doFinal(Base64.decode(encryptedText, Base64.DEFAULT));
return new String(clearText, "UTF-8");
} catch (Exception e) {
return null;
}
}
答案 2 :(得分:1)
对我来说,问题出在getKey()
确保两次getKey()
的调用返回相同的值。
我使用new SecureRandom(password.getBytes())
生成密钥。它适用于Windows,但在Android上,它为不同的调用返回了不同的值。
答案 3 :(得分:0)
更改为" AES "来自" AES / ECB / PKCS7Padding ";