线程" main"中的例外情况java.security.InvalidKeyException:非法的密钥大小

时间:2017-12-29 03:28:58

标签: java bouncycastle

这是我的代码:

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")))));  }
}

我用来运行它的命令是java -classpath "bcprov-jdk15on-158.jar;." JavaFiddle

java -version输出:

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)

1 个答案:

答案 0 :(得分:2)

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

https://bouncycastle.org/documentation.html

的href

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