简体   繁体   English

解密DES / CBC / ZeroBytePadding数据

[英]Decrypting DES/CBC/ZeroBytePadding data

I have a token and a secret that is needed to decrypt the token. 我有一个令牌和一个解密令牌所需的秘密。 I am not sure what am I doing wrong that I keep getting "illegal key size". 我不确定自己在做什么,我会不断得到“非法密钥大小”。 My key size is 44 bytes. 我的密钥大小是44个字节。 I am adding BouncyCastleProvider in a static block. 我在静态块中添加BouncyCastleProvider。 Below is a small snippet of what I am trying to do. 以下是我正在尝试做的一小段。

SecretKeySpec skeySpec = new SecretKeySpec(keyText.getBytes(), "DES");
Cipher des = Cipher.getInstance("DES/CBC/ZeroBytePadding", "BC");
des.init(Cipher.DECRYPT_MODE, skeySpec, new IvParameterSpec(new byte[8]));
byte[] tokenData = des.doFinal(Base64.decodeBase64(token));

DES has a key size of 56-bits in 8-bytes, the lsb of each byte is reserved for parity but is generally ignored. DES的密钥大小为8位字节,为56位,每个字节的lsb保留用于奇偶校验,但通常被忽略。

So "My key size is 44 bytes" is incorrect. 因此,“我的密钥大小是44个字节”是不正确的。

Next is the IV used for decryption must be the same as was used for encryption. 接下来是用于解密的IV必须与用于加密的IV相同。 DES has a block size of 8-bytes so the IV needs to be 8-bytes. DES的块大小为8字节,因此IV必须为8字节。 One general way of handling the IV is so prefix the encrypted data with it, the IV does not need to be secret. 处理IV的一种通用方法是给加密数据加上前缀,IV不必是秘密的。

Finally, zero padding is not generally a good solution, it does not support binary data that may end with a zero byte. 最后,零填充通常不是一个好的解决方案,它不支持可能以零字节结尾的二进制数据。 PKCS#5 is the generally used padding. PKCS#5是常用的填充。

My guess is that your keyText is Base64 encoded. 我的猜测是您的keyText是Base64编码的。 You should probably decode it to get a byte[] of 32 bytes. 您可能应该对其进行解码以获得32个字节的byte []。 In Java 8 you can do something like this: 在Java 8中,您可以执行以下操作:

byte[] key = java.util.Base64.getDecoder().decode(keyText.getBytes());
SecretKeySpec skeySpec = new SecretKeySpec(key, "DES");
Cipher des = Cipher.getInstance("DES/CBC/ZeroBytePadding", "BC");
des.init(Cipher.DECRYPT_MODE, skeySpec, new IvParameterSpec(new byte[8]));
byte[] tokenData = des.doFinal(Base64.decodeBase64(token));

This other question has more information about Base64. 此其他问题具有有关Base64的更多信息。 Converting Secret Key into a String and Vice Versa 将密钥转换为字符串,反之亦然

I still think you will get invalid key size errors though. 我仍然认为您会收到无效的密钥大小错误。 Isn't a DES key 56 bits (plus 8 parity bits)? DES密钥不是56位(加上8个奇偶校验位)吗? So that would only be 8 bytes long not 44 or the 32 I think you will get when you decode Base64. 所以那将只有8个字节长,而不是44或32个字节,我认为解码Base64时会得到。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM