我創建了一個Encryption
類來加密/解密我的Android項目中的二進制數據,到這個link。爲什麼我在嘗試加密字符串時遇到BadPaddingException?
package com.my.package;
import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
// TODO Incomplete class
public class Encryption {
private static final byte[] salt = { (byte) 0xA4, (byte) 0x0B, (byte) 0xC8,
(byte) 0x34, (byte) 0xD6, (byte) 0x95, (byte) 0xF3, (byte) 0x13 };
private static int BLOCKS = 128;
private static byte[] encrypt(byte[] raw, byte[] clear) throws Exception {
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
byte[] encrypted = cipher.doFinal(clear);
return encrypted;
}
private static byte[] decrypt(byte[] raw, byte[] encrypted)
throws Exception {
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
byte[] decrypted = cipher.doFinal(encrypted);
return decrypted;
}
private static byte[] getKey() throws Exception {
byte[] keyStart = "this is a key".getBytes();
KeyGenerator kgen = KeyGenerator.getInstance("AES");
SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
sr.setSeed(keyStart);
kgen.init(128, sr); // 192 and 256 bits may not be available
SecretKey skey = kgen.generateKey();
byte[] key = skey.getEncoded();
return key;
}
public static void test() {
String test = "My Name Is Dragon Warrior";
byte[] e = null;
try {
e = encrypt(getKey(), test.getBytes());
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
byte[] d = null;
try {
d = decrypt(getKey(), e);
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
System.out.println(new String(d));
}
}
然後我跑在主要活動代碼:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// ...
Encryption.test();
// ...
}
然後我得到了BadPaddingException
時在test()
執行以下代碼:
try {
d = decrypt(getKey(), e);
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
有趣的是,我創建了一個Android項目以外的Java項目。代碼運行得很好,沒有任何異常。
我的代碼有什麼問題?
我絕對不知道這件事,但我googled出來,找到這個鏈接:http://stackoverflow.com/questions/4874311/badpaddingexception-in-android-encrypt希望它會幫助你。和這個鏈接:http://stackoverflow.com/questions/8387345/badpaddingexception-pad-block-corrupted-in-android – Maulik 2013-03-06 06:18:34
我可以確認代碼在Android(Java 7)之外正確執行。 – 2013-03-06 07:53:26
'BadPaddingException'通常意味着使用錯誤的密鑰來解密數據。如果getKey()在每個調用中返回不同的值,可能會導致這種情況。你有沒有在Android中試過一次測試,你只需調用一次'getKey()'並存儲結果? *沒有很好的理由說明爲什麼結果會有所不同,但這是一個有趣的測試。* – 2013-03-06 07:54:44