IllegalBlockSizeException:使用填充密码解密时,输入长度必须是8的倍数

时间:2013-06-20 05:14:25

标签: java encryption des

我有以下方法:

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);

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

2 个答案:

答案 0 :(得分:2)

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

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

尝试更改" DES"到" DES / ECB / NoPadding"。我不知道您的实施的默认密码模式是什么,但它通常是" ECB"或者" CBC"。如果这两个都不起作用,那么你就会在线路的某个地方破坏你的密文。

答案 1 :(得分: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");
}