Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Self signed X509 Certificate with Bouncy Castle in Java

Tags:

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

like image 759
paola91 Avatar asked Apr 24 '15 16:04

paola91


1 Answers

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)); } 
like image 145
always_a_rookie Avatar answered Sep 18 '22 17:09

always_a_rookie