问题描述
我试图加密和解密一些简单的文本。但是由于某种原因,我得到一个奇怪的错误: javax.crypto.BadPaddingException
。为什么JCE会生成未正确填充的字节?
I am trying to encrypt and decrypt some simple text. But for some reason I am getting a strange error: javax.crypto.BadPaddingException
. Why would JCE generates bytes that are not properly padded?
我有以下代码:
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import java.security.SecureRandom;
public class SimplestTest {
public static void main(String[] args) throws Exception {
SecureRandom rnd = new SecureRandom();
String text = "Hello, my dear! ... " + System.getProperty("user.home");
byte[] textData = text.getBytes();
IvParameterSpec iv = new IvParameterSpec(rnd.generateSeed(16));
KeyGenerator generator = KeyGenerator.getInstance("AES");
generator.init(128);
SecretKey k = generator.generateKey();
Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding");
c.init(Cipher.ENCRYPT_MODE, k, iv);
c.update(textData);
byte[] data = c.doFinal();
System.out.println("E: " + data.length);
c = Cipher.getInstance("AES/CBC/PKCS5Padding");
c.init(Cipher.DECRYPT_MODE, k, iv);
c.update(data);
System.out.println("R: " + c.doFinal().length);
}
}
但由于某种原因工作。它失败了这个异常:
But for some reason it does not work. It fails with this exception:
E: 16
Exception in thread "main" javax.crypto.BadPaddingException: Given final block not properly padded
at com.sun.crypto.provider.SunJCE_f.b(DashoA13*..)
at com.sun.crypto.provider.SunJCE_f.b(DashoA13*..)
at com.sun.crypto.provider.AESCipher.engineDoFinal(DashoA13*..)
at javax.crypto.Cipher.doFinal(DashoA13*..)
at SimplestTest.main(SimplestTest.java:31)
出了什么问题?数据大小为16字节,但仍然未正确填充?
What's going wrong? The data size is 16 bytes in length but is still "not properly padded" ?
推荐答案
Cipher.update返回一个byte []以及。因此,当您去解密时,您缺少部分加密数据。更新最后一部分如下:
Cipher.update returns a byte[] as well. So you are missing part of the encrypted data when you go to decrypt. Update the last section to read as follows:
Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding");
c.init(Cipher.ENCRYPT_MODE, k, iv);
byte[] someData = c.update(textData);
byte[] moreData = c.doFinal();
System.out.println("E: " + (someData.length + moreData.length));
c = Cipher.getInstance("AES/CBC/PKCS5Padding");
c.init(Cipher.DECRYPT_MODE, k, iv);
byte[] someDecrypted = c.update(someData);
byte[] moreDecrypted = c.doFinal(moreData);
System.out.println("R: " + (someDecrypted.length + moreDecrypted.length));
这篇关于AES / CBC / PKCS5Padding问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!