Java AES-128 CBC解密
为了解密密文,我用java编写了这段代码。我有钥匙。对我来说,一切似乎都是正确的,但我有一个问题要解释。Java AES-128 CBC解密,java,cryptography,block-cipher,Java,Cryptography,Block Cipher,为了解密密文,我用java编写了这段代码。我有钥匙。对我来说,一切似乎都是正确的,但我有一个问题要解释。 这是我的密码: import javax.crypto.Cipher; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; public class AES_CBC { public static void main(String[] args) throws Exce
这是我的密码:
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
public class AES_CBC {
public static void main(String[] args) throws Exception {
byte[] keyBytes = new byte[] { 14, (byte) 0x0b, (byte) 0x41,
(byte) 0xb2, (byte) 0x2a, (byte) 0x29, (byte) 0xbe,
(byte) 0xb4, (byte) 0x06, (byte) 0x1b, (byte) 0xda,
(byte) 0x66, (byte) 0xb6, (byte) 0x74, (byte) 0x7e, (byte) 0x14 };
byte[] ivBytes = new byte[] { (byte) 0x4c, (byte) 0xa0, (byte) 0x0f,
(byte) 0xf4, (byte) 0xc8, (byte) 0x98, (byte) 0xd6,
(byte) 0x1e, (byte) 0x1e, (byte) 0xdb, (byte) 0xf1,
(byte) 0x80, (byte) 0x06, (byte) 0x18, (byte) 0xfb, (byte) 0x28 };
SecretKeySpec key = new SecretKeySpec(keyBytes, "AES");
IvParameterSpec ivSpec = new IvParameterSpec(ivBytes);
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
byte[] cipherText = new byte[] { (byte) 0x28, (byte) 0xa2, (byte) 0x26,
(byte) 0xd1, (byte) 0x60, (byte) 0xda, (byte) 0xd0,
(byte) 0x78, (byte) 0x83, (byte) 0xd0, (byte) 0x4e,
(byte) 0x00, (byte) 0x8a, (byte) 0x78, (byte) 0x97,
(byte) 0xee, (byte) 0x2e, (byte) 0x4b, (byte) 0x74,
(byte) 0x65, (byte) 0xd5, (byte) 0x29, (byte) 0x0d,
(byte) 0x0c, (byte) 0x0e, (byte) 0x6c, (byte) 0x68,
(byte) 0x22, (byte) 0x23, (byte) 0x6e, (byte) 0x1d,
(byte) 0xaa, (byte) 0xfb, (byte) 0x94, (byte) 0xff,
(byte) 0xe0, (byte) 0xc5, (byte) 0xda, (byte) 0x05,
(byte) 0xd9, (byte) 0x47, (byte) 0x6b, (byte) 0xe0,
(byte) 0x28, (byte) 0xad, (byte) 0x7c, (byte) 0x1d, (byte) 0x81 };
cipher.init(Cipher.DECRYPT_MODE, key, ivSpec);
byte[] original = cipher.doFinal(cipherText);
String plaintext = new String(original);
System.out.println(plaintext);
}
}
我得到以下错误:
Exception in thread "main" javax.crypto.BadPaddingException: Given final block not properly padded
at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:969)
at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:831)
at com.sun.crypto.provider.AESCipher.engineDoFinal(AESCipher.java:436)
at javax.crypto.Cipher.doFinal(Cipher.java:2097)
at AES_CTR.main(AES_CBC.java:39)
出什么事了?
我知道问题与填充物有关,但我不知道确切的解决方法。我只有一个密文,IV和密钥。您的第一个
密钥字节
是错误的,它应该是0x14而不是14。因此,填充字节被错误地解密,并且该块被视为被错误地填充
有关可能的密码选项,请参阅。Java使用PKCS5P添加名称来引用填充方案,该方案不限于8字节块大小。本质上,该算法是PKCS7填充,名称有点不恰当。@OlegEstekhin好的,但在这种特殊情况下,填充不是
PKCS5
或PKCS7
,而是ISO1026
。你错了。最后一个块以八个0x08字节结束。这是PKCS5/PKCS7填充。ISO10126将以一个0x80和七个0x00结尾。@Oleg我不知道您看到了什么,既没有八个0x08字节,也没有一个0x80和七个0x00。我也在我的电脑上测试了这个,所以你最好控制自己。我把ISO1026和ISO/IEC 7816-4混淆了。ISO10126具有[(长度-1)x(随机字节),长度]填充的焊盘,PKCS5/7具有[length x length]填充的焊盘,因此ISO10126确实可以毫无问题地接受PKCS5/7填充。但此密码文本仍然使用PKCS5/7 padding=)。