【问题标题】:Java AES encryption using 32 Byte key - Invalid Key Size [duplicate]使用 32 字节密钥的 Java AES 加密 - 密钥大小无效 [重复]
【发布时间】:2013-01-30 22:39:21
【问题描述】:

可能重复:
InvalidKeyException Illegal key size

public static byte[] encryptBytes(byte[] bytes, byte[] key)
{
    Cipher cipher = null;

    try
    {
        cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        SecretKeySpec secretKey = new SecretKeySpec(key, "AES");
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);

        return Base64.encodeBase64(cipher.doFinal(bytes));
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }

    return null;
}

public static byte[] decrpytBytes(byte[] encryptedData, String key)
{
    byte[] keyBytes = convertToByteArray(key);
    Cipher cipher = null;

    try
    {
        cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
        SecretKeySpec secretKey = new SecretKeySpec(keyBytes, "AES");
        cipher.init(Cipher.DECRYPT_MODE, secretKey);

        return cipher.doFinal(Base64.decodeBase64(encryptedData));
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }

    return null;
}
//Simply takes every other two characters an terms them into a byte value 
    //then stuffs them into  a byteArray
public static byte[] convertToByteArray(String key)
{
    byte[] b = new byte[key.length()/2];

    for(int i=0, bStepper=0; i<key.length()+2; i+=2)
        if(i !=0)
            b[bStepper++]=((byte) Integer.parseInt((key.charAt(i-2)+""+key.charAt(i-1)), 16));

    return b;
}

public static void main(String[] args) throws Exception
{
            //This string has 64 characters. When sent to convertToByteArray it returns a byte array or 32 bytes
    String key = "00112233445566778899AABBCCDDEEFF0123456789ABCDEF0123456789ABCDEF";

            //Test it out
    byte f[] = {2,4,7};
    byte[] encrypted = encryptBytes(f, convertToByteArray(key));
    byte[] unencrypted = decrpytBytes(encrypted, key);

    System.out.print(unencrypted[0]);
}

错误:

非法密钥大小或默认参数

我不知道为什么我的密钥大小无效。它应该能够采用 32 字节密钥和 256 加密

【问题讨论】:

标签: java encryption aes


【解决方案1】:

http://www.javamex.com/tutorials/cryptography/unrestricted_policy_files.shtml

“事实证明,Cipher 类通常不允许密钥大小超过 128 位的加密。这背后的明显原因是一些国家(尽管越来越少)对导入加密的允许密钥强度有限制软件,虽然实际数字 128 是有问题的(见下文)。好消息是:

您可以通过使用 Sun 提供的其他文件覆盖安全策略文件来轻松消除限制。”

【讨论】:

    猜你喜欢
    • 2021-01-27
    • 2021-09-23
    • 2017-06-16
    • 1970-01-01
    • 2017-08-28
    • 2017-11-15
    • 1970-01-01
    • 2019-03-24
    • 1970-01-01
    相关资源
    最近更新 更多