我试图在 Android 上解密从 发送的备份,并且在方法 doFinal 中显示iOS
了异常。javax.crypto.BadPaddingException: pad block corrupted
public String decrypt(byte[] cipherText, SecretKey key, byte [] initialVector) throws Exception {
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
IvParameterSpec ivParameterSpec = new IvParameterSpec(initialVector);
cipher.init(Cipher.DECRYPT_MODE, key, ivParameterSpec);
cipherText = cipher.doFinal(cipherText);
return new String(cipherText, "UTF-8");
}
键和初始向量是从 iOS 以 base64 字符串发送的。相关代码:
public static byte[] decodeWebSafe(String s) throws Base64DecoderException {
byte[] bytes = s.getBytes();
return decodeWebSafe(bytes, 0, bytes.length);
}
byte[] iv = Base64.decodeWebSafe(enciv);
byte[] salt = Base64.decodeWebSafe(encsalt);
byte[] data = Base64.decodeWebSafe(encdata);
SecretKey key = Security.getExistingKey(password, salt);
String original = aes.decrypt(data, key, iv);
关于 Security.getExistingKey:
public static SecretKey getExistingKey(String password, byte[] salt) throws Exception{
SecretKey key= null;
KeySpec keySpec = new PBEKeySpec(password.toCharArray(), salt, 10000, 256);
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
byte[] keyBytes=new byte[32];
keyBytes = keyFactory.generateSecret(keySpec).getEncoded();
key= new SecretKeySpec(keyBytes, "AES");
return key;
}
感谢任何解决方案。
PS这是我们在 iOS 中设置加密的方式:
CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, kCCAlgorithmAES128,
kCCOptionPKCS7Padding,
self.encryptionKey.bytes, kCCKeySizeAES128,
self.encryptionIV.bytes, [rawData bytes], dataLength,
/* input */buffer, bufferSize, /* output */&numBytesEncrypted);
密钥和IV推导方法:
(NSData *)keyForPassword:(NSString *)password salt:(NSData *)salt {
NSMutableData *
derivedKey = [NSMutableData dataWithLength:kCCKeySizeAES128];
int result = CCKeyDerivationPBKDF(kCCPBKDF2, // algorithm
password.UTF8String,
password.length,
salt.bytes, // salt
salt.length, // saltLen
kCCPRFHmacAlgSHA1, // PRF
kPBKDFRounds, // rounds
derivedKey.mutableBytes, // derivedKey
derivedKey.length); // derivedKeyLen
}