java - 无效 key 异常 :Ilegal key size

标签 java jsp encryption aes

我正在尝试加密一个字符串,但出现错误无效 key 异常:非法 key 大小,我试图在一个月内制定解决方案,我需要帮助:(。“对不起,我的英语不好”

    private static String secretKey = "PSKDF2";
    private static String salt = "ssshhhhhhhhhhh!!!!";

    public static String encrypt(String strToEncrypt, String secret) {
        try {
            byte[] iv = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
            IvParameterSpec ivspec = new IvParameterSpec(iv);

            SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
            KeySpec spec = new PBEKeySpec(secretKey.toCharArray(), salt.getBytes(), 65536, 256);
            SecretKey tmp = factory.generateSecret(spec);
            SecretKeySpec secretKey = new SecretKeySpec(tmp.getEncoded(), "AES");

            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivspec);
            return Base64.getEncoder().encodeToString(cipher.doFinal(strToEncrypt.getBytes("UTF-8")));
        } catch (Exception e) {
            System.out.println("Error while encrypting: " + e.toString());
        }
        return null;
    }

    public static String decrypt(String strToDecrypt, String secret) {
        try {
            byte[] iv = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
            IvParameterSpec ivspec = new IvParameterSpec(iv);

            SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
            KeySpec spec = new PBEKeySpec(secretKey.toCharArray(), salt.getBytes(), 65536, 256);
            SecretKey tmp = factory.generateSecret(spec);
            SecretKeySpec secretKey = new SecretKeySpec(tmp.getEncoded(), "AES");

            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
            cipher.init(Cipher.DECRYPT_MODE, secretKey, ivspec);
            return new String(cipher.doFinal(Base64.getDecoder().decode(strToDecrypt)));
        } catch (Exception e) {
            System.out.println("Error while decrypting: " + e.toString());
        }
        return null;
    }

我认为错误就在这里。

Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");

错误是这样的

Error while encrypting: java.security.InvalidKeyException: Illegal key size

请帮忙:(

最佳答案

您可以尝试以下ways来解决这个问题。好像有些软件包还没有安装。

关于java - 无效 key 异常 :Ilegal key size,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59969065/

相关文章:

java - 在 Java/grails 中使用 AES 128 加密字符串

java - 为什么 EnumMap 构造函数需要类参数?

JavaFX:父级及其子级的鼠标单击事件

jsp - 从 JSTL 访问方法

php - 使用 OpenSSL 解密字符串在终端中有效,但在 PHP 脚本中无效

go - 解密不稳定,有时会得到密码:消息身份验证失败

java - 优化 xstream 加载速度

java - Android Espresso 测试在物理设备上失败(PerformException)

java - 在 spring mvc 中获取 400 错误

java - 将序列的下一个值与字符串连接起来