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.Provider;
33 import java.security.Signature;
34 import java.security.SignatureException;
35 import java.util.Objects;
36
37 final class Signed {
38 private final byte[] toBeSigned;
39 private final String algorithmIdentifier;
40 private final PrivateKey privateKey;
41
42 Signed(byte[] toBeSigned, X509Bundle signer) {
43 this(toBeSigned, signer.getCertificate().getSigAlgName(), signer.getKeyPair().getPrivate());
44 }
45
46 Signed(byte[] toBeSigned, String algorithmIdentifier, PrivateKey privateKey) {
47 this.toBeSigned = Objects.requireNonNull(toBeSigned, "toBeSigned");
48 this.algorithmIdentifier = Objects.requireNonNull(algorithmIdentifier, "algorithmIdentifier");
49 this.privateKey = privateKey;
50 }
51
52 byte[] getEncoded(Provider provider) throws NoSuchAlgorithmException, InvalidKeyException, SignatureException {
53 Signature signature = Algorithms.signature(algorithmIdentifier, provider);
54 signature.initSign(privateKey);
55 signature.update(toBeSigned);
56 byte[] signatureBytes = signature.sign();
57 try {
58 return new DERSequence(new ASN1Encodable[]{
59 ASN1Primitive.fromByteArray(toBeSigned),
60 new AlgorithmIdentifier(new ASN1ObjectIdentifier(
61 Algorithms.oidForAlgorithmName(algorithmIdentifier))),
62 new DERBitString(signatureBytes)
63 }).getEncoded("DER");
64 } catch (IOException e) {
65 throw new UncheckedIOException(e);
66 }
67 }
68
69 InputStream toInputStream(Provider provider)
70 throws NoSuchAlgorithmException, SignatureException, InvalidKeyException {
71 return new ByteArrayInputStream(getEncoded(provider));
72 }
73 }