【问题标题】:Proper way to decrypt CryptoJS DES encoded string using Java?使用Java解密CryptoJS DES编码字符串的正确方法?
【发布时间】: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


【解决方案1】:

加密和解密的 IV 必须相同。在示例中,为解密创建了一个新的随机 IV:secureRandom.nextBytes(ivspec);

您需要仔细、全面地查看CryptoJS 文档以确定如何处理 IV。通常 IV 会添加到加密数据的前面,以便在解密期间使用。

encryptedString 似乎是 Base64 编码的,解码后的长度是 32 字节,正好适合 16 字节的 IV 和 16 字节的加密数据+填充。

【讨论】:

  • 谢谢 zaph,这很有见地。我显然对 DES 的工作原理知之甚少。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-08
  • 1970-01-01
  • 1970-01-01
  • 2015-10-17
  • 1970-01-01
相关资源
最近更新 更多