我有一个类似于this question的加密/解密代码。不同之处在于我只是在解密我之前加密的密钥并将其作为String存储在我的Constants类中。
它工作正常,但今天我发现代码因此错误而死:
javax.crypto.BadPaddingException: pad block corrupted
at com.android.org.bouncycastle.jcajce.provider.symmetric.util.BaseBlockCipher.engineDoFinal(BaseBlockCipher.java:709)
at javax.crypto.Cipher.doFinal(Cipher.java:1111)
仅在使用galaxy nexus Android 4.2.2时才会出现此错误。我已经在其他设备上测试了我的代码,包括平板电脑和2.3到4.0.3的其他Android版本。我没有在其他4.2.2设备中测试过这个,因为我只有这个设备有Android 4.2.2。
有没有人知道如何解决这个问题?
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[] getRawKey(byte[] seed) throws Exception {
KeyGenerator kgen = KeyGenerator.getInstance("AES");
SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
sr.setSeed(seed);
kgen.init(KEY_SIZE, sr);
SecretKey skey = kgen.generateKey();
byte[] raw = skey.getEncoded();
return raw;
}
public static byte[] toByte(String hexString) {
int len = hexString.length() / 2;
byte[] result = new byte[len];
for (int i = 0; i < len; i++) {
result[i] = Integer.valueOf(hexString.substring(2 * i, 2 * i + 2), END_POSITION).byteValue();
}
return result;
}
public static void generateKey() {
try {
byte[] seed = SEED_STRING.getBytes("UTF-8");
byte[] rawKey = getRawKey(seed);
byte[] toDecrypt = toByte(Constants.ENCRYPTED);
mKey = new String(decrypt(rawKey, toDecrypt), "UTF-8");
} catch (Exception e) {
if (BuildConfig.DEBUG) {
Log.e(TAG, "encryption: ", e);
}
}
}
编辑:我刚刚发现当我在问题设备上执行密钥加密时,每次我的应用程序启动时它都会生成一个不同的密钥。与之前测试的其他设备不同,每次只生成相同的密钥。
public static String toHex(byte[] buf) {
if (buf == null)
return "";
StringBuffer result = new StringBuffer(2*buf.length);
for (int i = 0; i < buf.length; i++) {
appendHex(result, buf[i]);
}
return result.toString();
}
private static void appendHex(StringBuffer sb, byte b) {
sb.append(HEX.charAt((b>>4)&0x0f)).append(HEX.charAt(b&0x0f));
}
private final static String HEX = "0123456789ABCDEF";
public static String encrypt(String seed, String cleartext) throws Exception {
byte[] rawKey = getRawKey(seed.getBytes());
byte[] result = encrypt(rawKey, cleartext.getBytes());
return toHex(result);
}
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;
}