天天看點

java 自簽名_用Java的Bouncy Castle自簽名的X509證書

小編典典

使用BouncyCastle的最新版本- 1.55 1.66

通過@Bewusstsein更新答案。截至此答案(5/11/2017),最新版本不推薦使用bouncycastle類。如果您使用的是1.55或更高版本:

public static Certificate selfSign(KeyPair keyPair, String subjectDN) throws OperatorCreationException, CertificateException, IOException

{

Provider bcProvider = new BouncyCastleProvider();

Security.addProvider(bcProvider);

long now = System.currentTimeMillis();

Date startDate = new Date(now);

X500Name dnName = new X500Name(subjectDN);

BigInteger certSerialNumber = new BigInteger(Long.toString(now)); //

Calendar calendar = Calendar.getInstance();

calendar.setTime(startDate);

calendar.add(Calendar.YEAR, 1); //

Date endDate = calendar.getTime();

String signatureAlgorithm = "SHA256WithRSA"; //

ContentSigner contentSigner = new JcaContentSignerBuilder(signatureAlgorithm).build(keyPair.getPrivate());

JcaX509v3CertificateBuilder certBuilder = new JcaX509v3CertificateBuilder(dnName, certSerialNumber, startDate, endDate, dnName, keyPair.getPublic());

// Extensions --------------------------

// Basic Constraints

BasicConstraints basicConstraints = new BasicConstraints(true); //

certBuilder.addExtension(new ASN1ObjectIdentifier("2.5.29.19"), true, basicConstraints); // Basic Constraints is usually marked as critical.

// -------------------------------------

return new JcaX509CertificateConverter().setProvider(bcProvider).getCertificate(certBuilder.build(contentSigner));

}

2020-11-05