5

我有以下方法:

public String decrypt(String strToBeDecrypted) {
    try {
        strToBeDecrypted = URLDecoder.decode(strToBeDecrypted, "UTF-8");
        DESKeySpec desKeySpec = new DESKeySpec(key);
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
        SecretKey skey = keyFactory.generateSecret(desKeySpec);

        IvParameterSpec ivSpec = new IvParameterSpec(iv);

        cipher.init(Cipher.DECRYPT_MODE, skey, ivSpec);

        byte[] keyByteArray = new BASE64Decoder().decodeBuffer(strToBeDecrypted);

        byte[] original = cipher.doFinal(keyByteArray);

        return new String(original, "UTF-8");
    } catch (Exception e) {
        logger.error(ExceptionUtil.getDetailedMessage(e));
    }
    return "";
}

这是扔

"name=javax.crypto.IllegalBlockSizeException;message=Input length must be multiple of 8 when decrypting with padded cipher;"

在下面一行:

 byte[] original = cipher.doFinal(keyByteArray);

有人可以告诉我这里有什么问题吗?

4

2 回答 2

4

它所指的输入长度是密文的长度(strToBeDecrypted),它期望是块大小的倍数。暗示默认情况下,库期望您的输入被填充。

这意味着您要么需要在解密时将填充设置为“无”(因为那是加密时使用的“填充”),要么您已经以某种方式破坏了密文。

尝试将“DES”更改为“DES/ECB/NoPadding”。我不知道您的实现的默认密码模式是什么,但它通常是“ECB”或“CBC”。如果这两个都不起作用,那么您正在沿线某处破坏您的密文。

于 2013-10-04T19:06:46.620 回答
0

请使用这个。这个对我有用。

public String decrypt(String message) throws Exception {
    final MessageDigest md = MessageDigest.getInstance("md5");
    final byte[] digestOfPassword = md.digest("HG58YZ3CR9"
            .getBytes("utf-8"));
    final byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24);
    for (int j = 0, k = 16; j < 8;) {
        keyBytes[k++] = keyBytes[j++];
    }

    final SecretKey key = new SecretKeySpec(keyBytes, "DESede");
    final IvParameterSpec iv = new IvParameterSpec(new byte[8]);
    final Cipher decipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
    decipher.init(Cipher.DECRYPT_MODE, key, iv);

    final byte[] encData = new sun.misc.BASE64Decoder().decodeBuffer(message);
    final byte[] plainText = decipher.doFinal(encData);

    return new String(plainText, "UTF-8");
}
于 2020-01-06T10:32:04.500 回答