1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package io.netty.example.ocsp;
18
19 import static io.netty.util.internal.ObjectUtil.checkNotNull;
20
21 import java.io.IOException;
22 import java.math.BigInteger;
23 import java.security.SecureRandom;
24 import java.security.cert.CertificateEncodingException;
25 import java.security.cert.X509Certificate;
26
27 import org.bouncycastle.asn1.DEROctetString;
28 import org.bouncycastle.asn1.ocsp.OCSPObjectIdentifiers;
29 import org.bouncycastle.asn1.x509.Extension;
30 import org.bouncycastle.asn1.x509.Extensions;
31 import org.bouncycastle.cert.X509CertificateHolder;
32 import org.bouncycastle.cert.ocsp.CertificateID;
33 import org.bouncycastle.cert.ocsp.OCSPException;
34 import org.bouncycastle.cert.ocsp.OCSPReq;
35 import org.bouncycastle.cert.ocsp.OCSPReqBuilder;
36 import org.bouncycastle.operator.DigestCalculator;
37
38
39
40
41
42
43 public class OcspRequestBuilder {
44
45 private static final SecureRandom GENERATOR = new SecureRandom();
46
47 private SecureRandom generator = GENERATOR;
48
49 private DigestCalculator calculator = Digester.sha1();
50
51 private X509Certificate certificate;
52
53 private X509Certificate issuer;
54
55 public OcspRequestBuilder generator(SecureRandom generator) {
56 this.generator = generator;
57 return this;
58 }
59
60 public OcspRequestBuilder calculator(DigestCalculator calculator) {
61 this.calculator = calculator;
62 return this;
63 }
64
65 public OcspRequestBuilder certificate(X509Certificate certificate) {
66 this.certificate = certificate;
67 return this;
68 }
69
70 public OcspRequestBuilder issuer(X509Certificate issuer) {
71 this.issuer = issuer;
72 return this;
73 }
74
75
76
77
78
79 public OCSPReq build() throws OCSPException, IOException, CertificateEncodingException {
80 SecureRandom generator = checkNotNull(this.generator, "generator");
81 DigestCalculator calculator = checkNotNull(this.calculator, "calculator");
82 X509Certificate certificate = checkNotNull(this.certificate, "certificate");
83 X509Certificate issuer = checkNotNull(this.issuer, "issuer");
84
85 BigInteger serial = certificate.getSerialNumber();
86
87 CertificateID certId = new CertificateID(calculator,
88 new X509CertificateHolder(issuer.getEncoded()), serial);
89
90 OCSPReqBuilder builder = new OCSPReqBuilder();
91 builder.addRequest(certId);
92
93 byte[] nonce = new byte[8];
94 generator.nextBytes(nonce);
95
96 Extension[] extensions = new Extension[] {
97 new Extension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce, false,
98 new DEROctetString(nonce)) };
99
100 builder.setRequestExtensions(new Extensions(extensions));
101
102 return builder.build();
103 }
104 }