Exception in thread “main” Java security. Invalidkeyexception: illegal key size or default parameter
•
Java
The following code throws this error message:
Exception in thread "main" Java security. Invalidkeyexception: illegal key size or default parameter
Cipher dcipher; byte[] salt = new String("12345678").getBytes(); int iterationCount = 1024; int keyStrength = 256; SecretKey key; byte[] iv; Decrypter(String passPhrase) throws Exception { SecretKeyFactory factory = SecretKeyFactory .getInstance("PBKDF2WithHmacSHA1"); System.out.println("factory +" + factory); KeySpec spec = new PBEKeySpec(passPhrase.tocharArray(),salt,iterationCount,keyStrength); System.out.println("spec " + spec); SecretKey tmp = factory.generateSecret(spec); System.out.println(); key = new SecretKeySpec(tmp.getEncoded(),"AES"); dcipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); } public String encrypt(String data) throws Exception { dcipher.init(Cipher.ENCRYPT_MODE,key); AlgorithmParameters params = dcipher.getParameters(); iv = params.getParameterSpec(IvParameterSpec.class).getIV(); byte[] utf8EncryptedData = dcipher.doFinal(data.getBytes()); String base64EncryptedData = new sun.misc.BASE64Encoder() .encodeBuffer(utf8EncryptedData); System.out.println("IV " + new sun.misc.BASE64Encoder().encodeBuffer(iv)); System.out.println("Encrypted Data " + base64EncryptedData); return base64EncryptedData;
Does anyone know why I got this mistake?
Solution
Maybe you haven't installed JCE policy files yet
Download this file:
> Java 6 > Java 7 > Java 8
And install the file in ${Java. Home} / JRE / lib / security /
${Java. Home} refers to the installation directory of Java
For Mac:
>Open finder > shift g > type / library / Java / javavirtualmachines > navigate to your JDK version, then contents / home / JRE / lib / Security > extract the downloaded files and put all the files here
For cli
unzip downloaded_policy_file.zip -d /Library/Java/JavaVirtualMachines/<JDK_VERSION>/Contents/Home/jre/lib/security/ mv /Library/Java/JavaVirtualMachines/<JDK_VERSION>/Contents/Home/jre/lib/security/UnlimitedJCEPolicyJDK<VERSION>/* /Library/Java/JavaVirtualMachines/<JDK_VERSION>/Contents/Home/jre/lib/security rm -rf Library/Java/JavaVirtualMachines/<JDK_VERSION>/Contents/Home/jre/lib/security/UnlimitedJCEPolicyJDK<VERSION>/
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码