11

下面的代码抛出此错误消息:

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

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;

有人知道我为什么会收到这个错误吗?

4

5 回答 5

24

可能您还没有安装 JCE 策略文件。

下载此文件:

并将文件安装在${java.home}/jre/lib/security/.

${java.home}指你的Java安装目录

对于麦克:

  • 打开查找器
  • command+ shift+g
  • 类型/Library/Java/JavaVirtualMachines
  • 导航到您的 JDK 版本
  • 然后Contents/Home/jre/lib/security
  • 解压下载的文件并将所有文件放在这里

用于 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>/
于 2013-11-08T10:12:45.663 回答
1

从此链接下载 Java 7 的 JCE http://www.oracle.com/technetwork/java/javase/downloads/jce-7-download-432124.html

并打开路径C:\Program Files\Java\jdk1.7.0_80\jre\lib\security并在此处粘贴两个罐子。(即使两个罐子已经存在,也替换这两个罐子)

于 2015-07-31T13:35:20.367 回答
0

对于 JAVA 7,下载链接是jce-7-download

将两个下载的 jar 复制到 Java\jdk1.7.0_10\jre\lib\security 中备份旧 jar 以更安全。

于 2014-02-13T08:24:42.217 回答
0

从 JDK 1.8u151 开始,无需单独下载 JCE 库。简单编辑:

$JDK_HOME/jre/lib/security/java.security

并取消注释该行:

crypto.policy=unlimited
于 2017-10-20T00:30:52.623 回答
0

如果您将 Mac 与自制软件一起使用

brew cask install jce-unlimited-strength-policy
于 2017-08-14T19:07:27.427 回答