Search code examples
javabouncycastle

Exception in thread "main" java.security.InvalidKeyException: Illegal key size


Here's my code:

import java.security.Security;
import java.security.spec.KeySpec;
import javax.crypto.SecretKey;
import javax.crypto.spec.PBEParameterSpec;
import javax.crypto.Cipher;
import java.util.Base64;
import java.security.Provider;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.SecretKeyFactory;

public class JavaFiddle {
    public static void main(String[] args) throws Exception {
        String algorithm = "PBEWITHSHAAND3-KEYTRIPLEDES-CBC";
        String password = "eKhfdPKO54OddrfgghuBGHsA5BGTYHon";
        byte[] salt = {-87, -101, -56, 50, 86, 52, -29, 3};
        int iterations = 19;

        String text = "foobar";

        Provider bouncy = new org.bouncycastle.jce.provider.BouncyCastleProvider();
        Security.addProvider(bouncy);

        KeySpec keySpec = new PBEKeySpec(password.toCharArray(), salt, iterations);
        SecretKey key = SecretKeyFactory.getInstance(algorithm, bouncy).generateSecret(keySpec);

        Cipher cipher = Cipher.getInstance(algorithm, bouncy);
        cipher.init(1, key, new PBEParameterSpec(salt, iterations));

        System.out.println(new String(Base64.getEncoder().encode(cipher.doFinal(text.getBytes("UTF8")))));  }
}

The command I'm using to run it is java -classpath "bcprov-jdk15on-158.jar;." JavaFiddle.

java -version outputs this:

java version "1.8.0_151"
Java(TM) SE Runtime Environment (build 1.8.0_151-b12)
Java HotSpot(TM) 64-Bit Server VM (build 25.151-b12, mixed mode)

Solution

  • I think you need to install Java Cryptography Extension (JCE) the see important notes

    https://bouncycastle.org/documentation.html

    http://www.oracle.com/technetwork/java/javase/downloads/jce8-download-2133166.html