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 sun.security.x509.AlgorithmId;
20 import sun.security.x509.CertificateAlgorithmId;
21 import sun.security.x509.CertificateIssuerName;
22 import sun.security.x509.CertificateSerialNumber;
23 import sun.security.x509.CertificateSubjectName;
24 import sun.security.x509.CertificateValidity;
25 import sun.security.x509.CertificateVersion;
26 import sun.security.x509.CertificateX509Key;
27 import sun.security.x509.X500Name;
28 import sun.security.x509.X509CertImpl;
29 import sun.security.x509.X509CertInfo;
30
31 import java.math.BigInteger;
32 import java.security.KeyPair;
33 import java.security.PrivateKey;
34 import java.security.SecureRandom;
35 import java.security.cert.CertificateException;
36
37 import static org.jboss.netty.handler.ssl.util.SelfSignedCertificate.*;
38
39
40
41
42 final class OpenJdkSelfSignedCertGenerator {
43
44 static String[] generate(String fqdn, KeyPair keypair, SecureRandom random) throws Exception {
45 PrivateKey key = keypair.getPrivate();
46
47
48 X509CertInfo info = new X509CertInfo();
49 X500Name owner = new X500Name("CN=" + fqdn);
50 info.set(X509CertInfo.VERSION, new CertificateVersion(CertificateVersion.V3));
51 info.set(X509CertInfo.SERIAL_NUMBER, new CertificateSerialNumber(new BigInteger(64, random)));
52 try {
53 info.set(X509CertInfo.SUBJECT, new CertificateSubjectName(owner));
54 } catch (CertificateException ignore) {
55 info.set(X509CertInfo.SUBJECT, owner);
56 }
57 try {
58 info.set(X509CertInfo.ISSUER, new CertificateIssuerName(owner));
59 } catch (CertificateException ignore) {
60 info.set(X509CertInfo.ISSUER, owner);
61 }
62 info.set(X509CertInfo.VALIDITY, new CertificateValidity(NOT_BEFORE, NOT_AFTER));
63 info.set(X509CertInfo.KEY, new CertificateX509Key(keypair.getPublic()));
64 info.set(X509CertInfo.ALGORITHM_ID,
65 new CertificateAlgorithmId(new AlgorithmId(AlgorithmId.sha1WithRSAEncryption_oid)));
66
67
68 X509CertImpl cert = new X509CertImpl(info);
69 cert.sign(key, "SHA1withRSA");
70
71
72 info.set(CertificateAlgorithmId.NAME + '.' + CertificateAlgorithmId.ALGORITHM, cert.get(X509CertImpl.SIG_ALG));
73 cert = new X509CertImpl(info);
74 cert.sign(key, "SHA1withRSA");
75 cert.verify(keypair.getPublic());
76
77 return newSelfSignedCertificate(fqdn, key, cert);
78 }
79
80 private OpenJdkSelfSignedCertGenerator() { }
81 }