1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package io.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.util.Date;
32 import java.math.BigInteger;
33 import java.security.KeyPair;
34 import java.security.PrivateKey;
35 import java.security.SecureRandom;
36 import java.security.cert.CertificateException;
37
38 import static io.netty.handler.ssl.util.SelfSignedCertificate.*;
39
40
41
42
43 final class OpenJdkSelfSignedCertGenerator {
44
45 static String[] generate(String fqdn, KeyPair keypair, SecureRandom random, Date notBefore, Date notAfter)
46 throws Exception {
47 PrivateKey key = keypair.getPrivate();
48
49
50 X509CertInfo info = new X509CertInfo();
51 X500Name owner = new X500Name("CN=" + fqdn);
52 info.set(X509CertInfo.VERSION, new CertificateVersion(CertificateVersion.V3));
53 info.set(X509CertInfo.SERIAL_NUMBER, new CertificateSerialNumber(new BigInteger(64, random)));
54 try {
55 info.set(X509CertInfo.SUBJECT, new CertificateSubjectName(owner));
56 } catch (CertificateException ignore) {
57 info.set(X509CertInfo.SUBJECT, owner);
58 }
59 try {
60 info.set(X509CertInfo.ISSUER, new CertificateIssuerName(owner));
61 } catch (CertificateException ignore) {
62 info.set(X509CertInfo.ISSUER, owner);
63 }
64 info.set(X509CertInfo.VALIDITY, new CertificateValidity(notBefore, notAfter));
65 info.set(X509CertInfo.KEY, new CertificateX509Key(keypair.getPublic()));
66 info.set(X509CertInfo.ALGORITHM_ID,
67 new CertificateAlgorithmId(new AlgorithmId(AlgorithmId.sha1WithRSAEncryption_oid)));
68
69
70 X509CertImpl cert = new X509CertImpl(info);
71 cert.sign(key, "SHA1withRSA");
72
73
74 info.set(CertificateAlgorithmId.NAME + '.' + CertificateAlgorithmId.ALGORITHM, cert.get(X509CertImpl.SIG_ALG));
75 cert = new X509CertImpl(info);
76 cert.sign(key, "SHA1withRSA");
77 cert.verify(keypair.getPublic());
78
79 return newSelfSignedCertificate(fqdn, key, cert);
80 }
81
82 private OpenJdkSelfSignedCertGenerator() { }
83 }