本文介紹了使用 Java 中的 Bouncy Castle 自簽名 X509 證書(shū)的處理方法,對(duì)大家解決問(wèn)題具有一定的參考價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)吧!
問(wèn)題描述
我需要使用 Java 中的 Bouncy Castle 創(chuàng)建自簽名 X509 證書(shū),但我嘗試包含的每個(gè)類(lèi)都已棄用.我該如何解決這個(gè)問(wèn)題?是否還有其他課程要包括在內(nèi)?謝謝
I need to create a self signed X509 Certificate with Bouncy Castle in Java, but every class I try to include is deprecated. How can I solve this? Is there some other class to include? Thanks
推薦答案
使用Bouncycastle最新版本-1.55 1.66
更新@Bewusstsein 的答案.自此答案(2017 年 5 月 11 日)起,最新版本不推薦使用 bouncycastle 類(lèi).如果您使用的是 1.55 或更高版本:
Using Bouncycastle latest version - 1.55 1.66
Update to the answer by @Bewusstsein. The bouncycastle classes are deprecated in the latest version as of this answer (5/11/2017). If you are using version 1.55 or later:
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)); // <-- Using the current timestamp as the certificate serial number
Calendar calendar = Calendar.getInstance();
calendar.setTime(startDate);
calendar.add(Calendar.YEAR, 1); // <-- 1 Yr validity
Date endDate = calendar.getTime();
String signatureAlgorithm = "SHA256WithRSA"; // <-- Use appropriate signature algorithm based on your keyPair algorithm.
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); // <-- true for CA, false for EndEntity
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));
}
這篇關(guān)于使用 Java 中的 Bouncy Castle 自簽名 X509 證書(shū)的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!
【網(wǎng)站聲明】本站部分內(nèi)容來(lái)源于互聯(lián)網(wǎng),旨在幫助大家更快的解決問(wèn)題,如果有圖片或者內(nèi)容侵犯了您的權(quán)益,請(qǐng)聯(lián)系我們刪除處理,感謝您的支持!