收藏
回答

security.InvalidKeyException: Illegal key size?

報錯Exception in thread "main" java.lang.IllegalArgumentException: java.security.InvalidKeyException: Illegal key size

回答关注问题邀请回答
收藏

2 个回答

  • Memory
    Memory
    2023-10-17

    2023-10-17
    有用 1
    回复
  • CRMEB
    CRMEB
    2023-10-17

    这个异常表示在Java程序中,使用了非法的密钥大小。具体来说,`java.security.InvalidKeyException: Illegal key size` 表示密钥的大小不符合要求。


    要解决这个问题,你需要检查你的代码中的密钥生成和加密部分,确保使用的密钥大小是合法的。通常,密钥长度应该是128位、192位或256位。如果你使用的是AES加密算法,可以参考以下示例代码:


    import javax.crypto.Cipher;
    import javax.crypto.KeyGenerator;
    import javax.crypto.SecretKey;
    import java.security.NoSuchAlgorithmException;
    import java.security.InvalidKeyException;
    import java.security.SecureRandom;
    
    public class Main {
        public static void main(String[] args) throws NoSuchAlgorithmException, InvalidKeyException {
            // 生成一个128位的AES密钥
            KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
            keyGenerator.init(128, new SecureRandom());
            SecretKey secretKey = keyGenerator.generateKey();
    
            // 使用AES密钥进行加密
            Cipher cipher = Cipher.getInstance("AES");
            cipher.init(Cipher.ENCRYPT_MODE, secretKey);
            byte[] encryptedData = cipher.doFinal("Hello, World!".getBytes());
    
            // 使用AES密钥进行解密
            cipher.init(Cipher.DECRYPT_MODE, secretKey);
            byte[] decryptedData = cipher.doFinal(encryptedData);
            System.out.println(new String(decryptedData));
        }
    }
    


    在这个示例中,我们生成了一个128位的AES密钥,并使用它进行了加密和解密操作。请根据你的实际需求调整密钥长度。

    2023-10-17
    有用 1
    回复
登录 后发表内容