1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.jboss.netty.handler.ssl.util;
18
19 import org.bouncycastle.asn1.x500.X500Name;
20 import org.bouncycastle.cert.X509CertificateHolder;
21 import org.bouncycastle.cert.X509v3CertificateBuilder;
22 import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter;
23 import org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder;
24 import org.bouncycastle.jce.provider.BouncyCastleProvider;
25 import org.bouncycastle.operator.ContentSigner;
26 import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder;
27
28 import java.math.BigInteger;
29 import java.security.KeyPair;
30 import java.security.PrivateKey;
31 import java.security.Provider;
32 import java.security.SecureRandom;
33 import java.security.cert.X509Certificate;
34
35 import static org.jboss.netty.handler.ssl.util.SelfSignedCertificate.*;
36
37
38
39
40 final class BouncyCastleSelfSignedCertGenerator {
41
42 private static final Provider PROVIDER = new BouncyCastleProvider();
43
44 static String[] generate(String fqdn, KeyPair keypair, SecureRandom random) throws Exception {
45 PrivateKey key = keypair.getPrivate();
46
47
48 X500Name owner = new X500Name("CN=" + fqdn);
49 X509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(
50 owner, new BigInteger(64, random), NOT_BEFORE, NOT_AFTER, owner, keypair.getPublic());
51
52 ContentSigner signer = new JcaContentSignerBuilder("SHA256WithRSAEncryption").build(key);
53 X509CertificateHolder certHolder = builder.build(signer);
54 X509Certificate cert = new JcaX509CertificateConverter().setProvider(PROVIDER).getCertificate(certHolder);
55 cert.verify(keypair.getPublic());
56
57 return newSelfSignedCertificate(fqdn, key, cert);
58 }
59
60 private BouncyCastleSelfSignedCertGenerator() { }
61 }