使用BouncyCastle
编写代码以生成数字证书。
这是导致问题的代码的基本部分。
public X509Certificate generateCertWithKeypair(KeyPair caPair)
throws InvalidKeyException, SecurityException, SignatureException {
X509V3CertificateGenerator v3CertGen = new X509V3CertificateGenerator();
v3CertGen
.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis()));
v3CertGen
.setIssuerDN(new X509Principal("CN=cn, O=o, L=L, ST=il, C= c"));
v3CertGen.setNotBefore(new Date(System.currentTimeMillis() - 1000L * 60
* 60 * 24));
v3CertGen.setNotAfter(new Date(System.currentTimeMillis()
+ (1000L * 60 * 60 * 24 * 365 * 10)));
v3CertGen
.setSubjectDN(new X509Principal("CN=cn, O=o, L=L, ST=il, C= c"));
v3CertGen.setPublicKey(caPair.getPublic());
v3CertGen.setSignatureAlgorithm("SHA1WithRSAEncryption");
X509Certificate generateX509Certificate = v3CertGen
.generateX509Certificate(caPair.getPrivate());//**here**
return generateX509Certificate;
}
面临例外
Exception in "main" java.lang.SecurityException: BC provider not installed!
at X509V3CertificateGenerator.generateX509Certificate(Unknown Source)
at chapter4.Dupe.generateCertWithKeypair(Dupe.java:74)
at chapter4.Dupe.main(Dupe.java:32)
在搜索I found时,最新的jar解决了这个问题,但没有运气。
我错过了什么吗?
答案 0 :(得分:8)
你应该在JRE中“注册”BC。您可以通过两种方式完成此操作:将bcprov.jar放入$ JRE / lib / ext文件夹并添加$JRE/lib/security/java.security
行
security.provider.N = org.bouncycastle.jce.provider.BouncyCastleProvider
或将bcprov.jar放在classpath中,不要修改java.security,而是在某处添加代码
static { Security.addProvider(new BouncyCastleProvider()); }
http://www.bouncycastle.org/wiki/display/JA1/Provider+Installation
答案 1 :(得分:0)
我遇到了类似的问题,添加到了公认的答案中,这是为我工作的解决方案。
解决方案1: 更新JRE / lib / security / java.security
security.provider.1=org.bouncycastle.jce.provider.BouncyCastleProvider
security.provider.2=org.bouncycastle.jsse.provider.BouncyCastleJsseProvider
security.provider.3=sun.security.provider.Sun
security.provider.4=sun.security.rsa.SunRsaSign
security.provider.5=com.sun.net.ssl.internal.ssl.Provider
security.provider.6=com.sun.crypto.provider.SunJCE
security.provider.7=sun.security.jgss.SunProvider
security.provider.8=com.sun.security.sasl.Provider
BC库必须位于顶部(1&2)
解决方案2: 将其添加到项目中
static {
if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) {
Security.insertProviderAt(new BouncyCastleProvider(), 1);
}
if (Security.getProvider(BouncyCastleJsseProvider.PROVIDER_NAME) == null) {
Security.insertProviderAt(new BouncyCastleJsseProvider(), 2);
}
}