【发布时间】:2015-02-24 20:06:36
【问题描述】:
我正在尝试创建 AES 加密/解密方法,但如果不使用 AES/ECB/NoPadding,我似乎无法获得原始输入。现在我正在尝试使用 AES/CBC/PKCS7Padding。我已经确认从文件中读取和写入字节工作正常。使用 PKCS7 填充我从
得到一个 BadPaddingExceptioncipher.doFinal(encrypted)
在解密方法中。没有填充,没有例外 - 但是输出是加扰的。我已经花时间浏览了关于这个完全相同的问题的其他帖子,但我似乎无法找到适合我的问题的解决方案。
如何解读该输出?
protected boolean encrypt(String place, String encrypt) {
try {
// encrypt the text
cipher.init(Cipher.ENCRYPT_MODE, aesKey);
byte[] encrypted = cipher.doFinal(encrypt.getBytes());
Context context = HomeViewActivity.hva.getApplicationContext();
FileOutputStream writer = context.openFileOutput(file_name.get(place.toUpperCase()), Context.MODE_PRIVATE);
writer.write(encrypted);
writer.close();
return true; //successfully wrote encrypted string to file
}catch(Exception e) {
e.printStackTrace();
}
return false;
}
protected String decrypt(String place){
String decrypted = null;
try{
Context context = HomeViewActivity.hva.getApplicationContext();
// decrypt the text
cipher.init(Cipher.DECRYPT_MODE, aesKey);
FileInputStream reader = context.openFileInput(file_name.get(place.toUpperCase()));
byte[] encrypted = new byte[reader.available()];
reader.read(encrypted);
reader.close();
decrypted= new String(cipher.doFinal(encrypted));
}catch(FileNotFoundException e){return null;}
catch(IllegalBlockSizeException |
BadPaddingException |
InvalidKeyException |
NoSuchAlgorithmException |
IOException |
NoSuchPaddingException e){e.printStackTrace();}
return decrypted;
}
编辑 1:使从文件中读取的加密数组具有适当的大小
编辑 2:在构造函数而不是每个方法中初始化密钥和密码
【问题讨论】:
-
为什么不使用与加密相同的算法进行解密?为什么只解密 16 个字节,而不是加密的完整输出?
-
就像我说的,如果我在解密方法中使用填充,我会得到一个异常。该数组也是 16 字节,因为它是使用 128 位密钥加密的
-
澄清:密钥大小和块大小是不同的。 AES 使用 128 位块和 128、192 或 256 位密钥。填充确保文本是块大小的倍数。使用
NoPadding意味着您有责任确保输入的大小正确。无论如何,它需要在加密和解密上保持一致(从发布的代码中不清楚)。而且,就@JBNizet 而言,您应该期望密文(即encrypted)超过1 个块。如果只占用 16 个字节,您可能会截断数据。 -
您似乎正在使用作为字符串传输的密钥。如果字符串是二进制的,您可能会丢失数据。丢失数据意味着不同的密钥。不同的密钥意味着您获得垃圾明文(因为 AES CBC 不受完整性保护)。垃圾明文意味着填充也是随机的,这意味着它将失败并显示
BadPaddingException。 -
再读一遍我看不到对 IV 值的任何处理。 IV 值应该是随机的,并作为密文的前缀,然后删除并重新用于解密。 ECB 不使用 IV 值。
标签: java android encryption aes badpaddingexception