1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package io.netty.pkitesting;
17
18 import org.bouncycastle.asn1.ASN1Encodable;
19 import org.bouncycastle.asn1.ASN1ObjectIdentifier;
20 import org.bouncycastle.asn1.ASN1Primitive;
21 import org.bouncycastle.asn1.DERBitString;
22 import org.bouncycastle.asn1.DERSequence;
23 import org.bouncycastle.asn1.x509.AlgorithmIdentifier;
24
25 import java.io.ByteArrayInputStream;
26 import java.io.IOException;
27 import java.io.InputStream;
28 import java.io.UncheckedIOException;
29 import java.security.InvalidKeyException;
30 import java.security.NoSuchAlgorithmException;
31 import java.security.PrivateKey;
32 import java.security.Signature;
33 import java.security.SignatureException;
34 import java.util.Objects;
35
36 final class Signed {
37 private final byte[] toBeSigned;
38 private final String algorithmIdentifier;
39 private final PrivateKey privateKey;
40
41 Signed(byte[] toBeSigned, X509Bundle signer) {
42 this(toBeSigned, signer.getCertificate().getSigAlgName(), signer.getKeyPair().getPrivate());
43 }
44
45 Signed(byte[] toBeSigned, String algorithmIdentifier, PrivateKey privateKey) {
46 this.toBeSigned = Objects.requireNonNull(toBeSigned, "toBeSigned");
47 this.algorithmIdentifier = Objects.requireNonNull(algorithmIdentifier, "algorithmIdentifier");
48 this.privateKey = privateKey;
49 }
50
51 byte[] getEncoded() throws NoSuchAlgorithmException, InvalidKeyException, SignatureException {
52 Signature signature = Algorithms.signature(algorithmIdentifier);
53 signature.initSign(privateKey);
54 signature.update(toBeSigned);
55 byte[] signatureBytes = signature.sign();
56 try {
57 return new DERSequence(new ASN1Encodable[]{
58 ASN1Primitive.fromByteArray(toBeSigned),
59 new AlgorithmIdentifier(new ASN1ObjectIdentifier(
60 Algorithms.oidForAlgorithmName(algorithmIdentifier))),
61 new DERBitString(signatureBytes)
62 }).getEncoded("DER");
63 } catch (IOException e) {
64 throw new UncheckedIOException(e);
65 }
66 }
67
68 InputStream toInputStream() throws NoSuchAlgorithmException, SignatureException, InvalidKeyException {
69 return new ByteArrayInputStream(getEncoded());
70 }
71 }