PBEWITHSHA256AND128BITAES-CBC-BC creating java.security.NoSuchAlgorithmException on RedHat 6.4

旧时模样 提交于 2019-12-05 03:53:54

Do you have the BouncyCastle provider JAR (e.g. bcprov-jdk15on-149.jar) in your classpath?

I tested your scenario with a minimal CentOS 6.4 (64-bit) installation, OpenJDK 1.7 and BouncyCastle 1.49, and found no issues with it.

I placed the JAR in the JRE lib/ext directory:

/usr/lib/jvm/java-1.7.0-openjdk.x86_64/jre/lib/ext

I try to confirm your issue and looks like problem in your environment. Here is sample of code i successfully run on clean OpenJDK 1.7, 1.6, Oracle JDK 1.7 and 1.6

$ java -version
java version "1.7.0_19"
OpenJDK Runtime Environment (rhel-2.3.9.1.el6_4-x86_64)
OpenJDK 64-Bit Server VM (build 23.7-b01, mixed mode):

Command line: java -cp bcprov-jdk15on-149.jar:. Test

Output: OK

import org.bouncycastle.jce.provider.BouncyCastleProvider;

import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import java.security.NoSuchAlgorithmException;
import java.security.Security;
import java.security.spec.InvalidKeySpecException;

public class Test {
    public static void main(String[] args) throws Exception{
        String cryptoAlgorithm = "PBEWITHSHA256AND128BITAES-CBC-BC";
        Security.addProvider(new BouncyCastleProvider());

        char[] passPhrase = null;
        passPhrase = "12321".toCharArray();
        PBEKeySpec pbeKeySpec = new PBEKeySpec(passPhrase);
        try {
            SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance(cryptoAlgorithm, "BC");
            SecretKey newSecretKey = secretKeyFactory.generateSecret(pbeKeySpec);
            assert newSecretKey != null;
            System.out.println("OK");
        } catch (NoSuchAlgorithmException e) {
            System.out.println("The algorithm is not found: " + cryptoAlgorithm);
        } catch (InvalidKeySpecException e) {
            System.out.println("The key spec is invalid");
        }
    }
}

Try to run that program on your environment. BouncyCastle jar you can download from here http://downloads.bouncycastle.org/java/bcprov-jdk15on-149.jar



I guess the order of the security providers is different in both environments.

for (Provider provider : Security.getProviders())
{
    System.out.println("Name: " + provider.getName() + " Version: " + provider.getVersion());
}

you can try to insert the bouncy castle provider at a specific position in the chain of providers. Here for example at the first position, if no other security provider is used this should not lead into problems.

Security.insertProviderAt(new BouncyCastleProvider(), 1);

the use of a specific provider for an algorithm is not recommended

SecretKeyFactory.getInstance(cryptoAlgorithm, provider)

see: Java ™ Cryptography Architecture(JCA) Reference Guide

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!