【发布时间】:2018-03-02 09:47:06
【问题描述】:
在 JavaScript 方面我使用:
CryptoJS.DES.encrypt('Content', 'password').toString()
结果:
U2FsdGVkX1/25rW2q0X7/pOtExFyP7MD
在Java端我尝试解密它:
public static void main(String[] args) throws Exception {
String password = "password";
String encryptedString = "U2FsdGVkX1/25rW2q0X7/pOtExFyP7MD";
DESKeySpec key = new DESKeySpec(password.getBytes());
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
SecureRandom secureRandom = new SecureRandom();
byte[] ivspec = new byte[cipher.getBlockSize()];
secureRandom.nextBytes(ivspec);
IvParameterSpec iv = new IvParameterSpec(ivspec);
cipher.init(Cipher.DECRYPT_MODE, keyFactory.generateSecret(key), iv);
byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(encryptedString.getBytes()));
System.out.println(new String(Base64.getEncoder().encode(decryptedBytes)));
}
但我遇到了错误的填充错误:
Exception in thread "main" javax.crypto.BadPaddingException: Given final block not properly padded. Such issues can arise if a bad key is used during decryption.
谁能告诉我出了什么问题以及解密它的正确方法是什么?假设无法更改 JavaScript 端代码(即使用 DES 加密字符串的方式)。非常感谢。
【问题讨论】:
-
一般来说,填充错误表示解密失败。
-
不要在新工作中使用 DES,它不再被认为是安全的,已被 AES(高级加密标准)取代 DES 只有密钥大小只有 56 位不被认为是安全的,AES 支持 128,192 和 256 位的密钥大小。见Security comparison of DES and AES。
-
数据总是以 53616c7465645f5f 开头。这是来自 OpenSSL 格式化程序,因此您需要使用此格式进行解码以获取 IV 和数据字节。
-
这是用于 AES 但应该类似:stackoverflow.com/questions/29151211/…
-
感谢 fgb,我终于使用链接中的示例解决了问题。如果您发布答案,我会将其标记为已接受。
标签: javascript java encryption cryptojs des