线程中的异常“main”java.security.InvalidKeyException:非法键大小或默认参数

下面的代码是抛出这个错误信息:

线程中的异常“main”java.security.InvalidKeyException:非法键大小或认参数

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;

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

解决方法

可能你还没有安装JCE策略文件.

下载此文件

> Java 6
> Java 7
> Java 8

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

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

对于mac:

>打开查找器
>按命令shift g
>类型/库/ 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>/

相关文章

最近看了一下学习资料,感觉进制转换其实还是挺有意思的,尤...
/*HashSet 基本操作 * --set:元素是无序的,存入和取出顺序不...
/*list 基本操作 * * List a=new List(); * 增 * a.add(inde...
/* * 内部类 * */ 1 class OutClass{ 2 //定义外部类的成员变...
集合的操作Iterator、Collection、Set和HashSet关系Iterator...
接口中常量的修饰关键字:public,static,final(常量)函数...