AES / CFB解密

时间:2016-11-28 10:38:44

标签: java encryption aes java-security

我正尝试使用下面的代码

使用AES / CFB模式解密
final static public String ENCRYPT_KEY = "4EBB854BC67649A99376A7B90089CFF1";
final static public String IVKEY = "ECE7D4111337A511F81CBF2E3E42D105";
private static String deCrypt(String key, String initVector, String encrypted) {
    try {
       IvParameterSpec iv = new IvParameterSpec(initVector.getBytes("UTF-8"));
        SecretKeySpec skSpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES");
        int maxKeyLen = Cipher.getMaxAllowedKeyLength("AES");

        Cipher cipher = Cipher.getInstance("AES/CFB/NoPadding");
        cipher.init(Cipher.DECRYPT_MODE, skSpec, iv);
        byte[] original = cipher.doFinal(encrypted.getBytes());

        return new String(original);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return "";
}

并抛出以下错误,

Wrong IV length: must be 16 bytes long.

以上ENCRYPT_KEY和IVKEY是有效的。任何人都可以提供帮助吗?

1 个答案:

答案 0 :(得分:2)

您正在调用"ECE7D4111337A511F81CBF2E3E42D105".getBytes("UTF-8");,这将导致大小为32的byte[],更不用说完全错误的IV。

您需要将解析字符串改为byte[],例如借用DatatypeConverter中的javax.xml.bind

IvParameterSpec iv = new IvParameterSpec(
    javax.xml.bind.DatatypeConverter.parseHexBinary(initVector));
相关问题