java – 3DES解密错误密钥长度无效
作者:互联网
我正在使用3DESC解密数据,但我得到以下异常
java.security.InvalidKeyException: Invalid key length: 16 bytes
我的代码:
public static byte[] decrypt3DESCBC(byte[] keyBytes, byte[] ivBytes,
byte[] dataBytes) {
try {
AlgorithmParameterSpec ivSpec = new IvParameterSpec(ivBytes);
SecretKeySpec newKey = new SecretKeySpec(keyBytes, "DESede");
Cipher cipher = Cipher.getInstance("DESede/CBC/NoPadding");
cipher.init(Cipher.DECRYPT_MODE, newKey, ivSpec); // Causes Exception
return cipher.doFinal(dataBytes);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
打印上面使用的所有字节数组
keyBytes : FC15780BB4B0**********0876482C1B // Masked 10 Characters
ivBytes : 0000000000000000
dataBytes : AF53C90F7FAD977E**********69DB5A2BF3080F9F07F4BFEA3EDB4DE96887BE7D40A5A590C0911A // Masked 10 Characters
解决方法:
DES-EDE密码可以与3个不同的子密钥一起使用,因此密钥大小应该是24个字节(3个8字节).如果你只想使用2个键(即在这种模式下,第一个键==最后一个键),那么你只需要复制键数组的前8个字节.
byte[] key;
if (keyBytes.length == 16) {
key = new byte[24];
System.arraycopy(keyBytes, 0, key, 0, 16);
System.arraycopy(keyBytes, 0, key, 16, 8);
} else {
key = keyBytes;
}
标签:3des,java,encryption,cryptography 来源: https://codeday.me/bug/20191001/1840155.html