How to Resolve java.security.InvalidKeyException: Illegal Key Size When Using BouncyCastle in Java?

Question

What causes the 'java.security.InvalidKeyException: Illegal key size' error when running a BouncyCastle encryption on a TeamCity server?

private byte[] aesEncryptedInfo(String info) throws UnsupportedEncodingException, IllegalBlockSizeException, BadPaddingException, InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidParameterSpecException, InvalidAlgorithmParameterException, NoSuchProviderException {
    Security.addProvider(new BouncyCastleProvider());
    SecretKey secret = new SecretKeySpec(CUSTOMLONGSECRETKEY.substring(0, 32).getBytes(), "AES");
    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding", "BC");
    cipher.init(Cipher.ENCRYPT_MODE, secret, new IvParameterSpec(VECTOR_SECRET_KEY.getBytes()));
    return cipher.doFinal(info.getBytes("UTF-8"));
}

Answer

The 'java.security.InvalidKeyException: Illegal key size' error typically occurs when the application tries to use an encryption key that exceeds the legal size set by the Java Cryptography Extension (JCE) policy files. This can be a common issue when transitioning code from a local development environment where the policy allows larger key sizes, to a CI/CD environment like TeamCity where the default policy may still apply, particularly when using Java 1.6.

// Example code for AES encryption using BouncyCastle
private byte[] aesEncryptedInfo(String info) throws UnsupportedEncodingException, IllegalBlockSizeException, BadPaddingException, InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidParameterSpecException, InvalidAlgorithmParameterException, NoSuchProviderException {
    Security.addProvider(new BouncyCastleProvider());
    SecretKey secret = new SecretKeySpec(CUSTOMLONGSECRETKEY.substring(0, 32).getBytes(), "AES");
    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding", "BC");
    cipher.init(Cipher.ENCRYPT_MODE, secret, new IvParameterSpec(VECTOR_SECRET_KEY.getBytes()));
    return cipher.doFinal(info.getBytes("UTF-8"));
}

Causes

  • Java Cryptography Extension (JCE) policy restrictions that limit key sizes to less than 256 bits in some installations of Java 6.
  • Different configurations between local development environment and CI servers that may not support the same key sizes or have different security providers set up.

Solutions

  • Install the Unlimited Strength Jurisdiction Policy Files for Java 6 on the TeamCity server to allow the use of larger keys.
  • Alternatively, switch to a cryptographic library like BouncyCastle that does not enforce these restrictions and can handle larger key sizes without additional configuration.

Common Mistakes

Mistake: Assuming the same JCE settings are applied on both the development and CI environments.

Solution: Verify and ensure that Unlimited Strength Policy Files are installed on the CI/CD environment.

Mistake: Using default Java security settings, which may not allow for higher key sizes in older Java versions.

Solution: Consider updating the Java version or explicitly installing the required policy files.

Helpers

  • java.security.InvalidKeyException
  • Illegal key size error
  • BouncyCastle encryption Java
  • Unlimited Strength Jurisdiction Policy Files
  • Java 6 encryption issues

Related Questions

⦿How to Count the Number of Items in an ArrayList in Java

Learn how to count the number of items in an ArrayList with a Java code example and best practices.

⦿How to Set Java System Properties in IntelliJ or Eclipse for Debugging?

Learn how to set Java system properties in IntelliJ and Eclipse for easy debugging. Get stepbystep instructions and code snippets.

⦿Understanding Modifications to Final Arrays in Java

Learn why final arrays in Java can have their contents modified while keeping their reference immutable. Explore code examples for clarity.

⦿How to Retrieve UserDetails from the Security Context in a Spring MVC Controller

Learn how to fetch UserDetails from the Security Context in Spring MVC to get the currently loggedin users username.

⦿Why is Lombok's @Builder Not Initializing Collections by Default?

Learn why Lomboks Builder does not initialize collections and how to use Singular for proper initialization.

⦿How to Fix Installation Errors for Plugins in Eclipse Luna?

Learn how to resolve installation issues with plugins in Eclipse Luna particularly errors related to SWT Designer and Papyrus. Expert tips included.

⦿How to Deserialize Java 8 LocalDateTime Using Jackson Mapper in Spring Boot

Learn how to correctly deserialize LocalDateTime objects from JSON in Spring Boot using Jackson Mapper. Troubleshoot common issues and find solutions.

⦿How to Implement Spring Batch Without Database Metadata Persistence?

Learn how to run Spring Batch jobs without persisting metadata to a database. Discover solutions and troubleshooting tips for common errors.

⦿How to Uninstall Plugins in Eclipse 3.4.X and Higher Versions

Learn how to effectively uninstall plugins in Eclipse 3.4.X and higher versions with detailed steps and solutions for common issues.

⦿Running a JAR File in the Linux Command Line: How to Set the Classpath and Execute with Arguments

Learn how to run a JAR file in Linux set the classpath to the current directory and pass arguments effectively.

© Copyright 2025 - CodingTechRoom.com