...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 package ct
16
17 import (
18 "crypto"
19 "crypto/ecdsa"
20 "crypto/elliptic"
21 "crypto/rsa"
22 "crypto/sha256"
23 "encoding/base64"
24 "encoding/pem"
25 "fmt"
26 "log"
27
28 "github.com/google/certificate-transparency-go/tls"
29 "github.com/google/certificate-transparency-go/x509"
30 )
31
32
33
34
35 var AllowVerificationWithNonCompliantKeys = false
36
37
38 func PublicKeyFromPEM(b []byte) (crypto.PublicKey, SHA256Hash, []byte, error) {
39 p, rest := pem.Decode(b)
40 if p == nil {
41 return nil, [sha256.Size]byte{}, rest, fmt.Errorf("no PEM block found in %s", string(b))
42 }
43 k, err := x509.ParsePKIXPublicKey(p.Bytes)
44 return k, sha256.Sum256(p.Bytes), rest, err
45 }
46
47
48 func PublicKeyFromB64(b64PubKey string) (crypto.PublicKey, error) {
49 der, err := base64.StdEncoding.DecodeString(b64PubKey)
50 if err != nil {
51 return nil, fmt.Errorf("error decoding public key: %s", err)
52 }
53 return x509.ParsePKIXPublicKey(der)
54 }
55
56
57 type SignatureVerifier struct {
58 PubKey crypto.PublicKey
59 }
60
61
62 func NewSignatureVerifier(pk crypto.PublicKey) (*SignatureVerifier, error) {
63 switch pkType := pk.(type) {
64 case *rsa.PublicKey:
65 if pkType.N.BitLen() < 2048 {
66 e := fmt.Errorf("public key is RSA with < 2048 bits (size:%d)", pkType.N.BitLen())
67 if !AllowVerificationWithNonCompliantKeys {
68 return nil, e
69 }
70 log.Printf("WARNING: %v", e)
71 }
72 case *ecdsa.PublicKey:
73 params := *(pkType.Params())
74 if params != *elliptic.P256().Params() {
75 e := fmt.Errorf("public is ECDSA, but not on the P256 curve")
76 if !AllowVerificationWithNonCompliantKeys {
77 return nil, e
78 }
79 log.Printf("WARNING: %v", e)
80
81 }
82 default:
83 return nil, fmt.Errorf("unsupported public key type %v", pkType)
84 }
85
86 return &SignatureVerifier{PubKey: pk}, nil
87 }
88
89
90 func (s SignatureVerifier) VerifySignature(data []byte, sig tls.DigitallySigned) error {
91 return tls.VerifySignature(s.PubKey, data, sig)
92 }
93
94
95 func (s SignatureVerifier) VerifySCTSignature(sct SignedCertificateTimestamp, entry LogEntry) error {
96 sctData, err := SerializeSCTSignatureInput(sct, entry)
97 if err != nil {
98 return err
99 }
100 return s.VerifySignature(sctData, tls.DigitallySigned(sct.Signature))
101 }
102
103
104 func (s SignatureVerifier) VerifySTHSignature(sth SignedTreeHead) error {
105 sthData, err := SerializeSTHSignatureInput(sth)
106 if err != nil {
107 return err
108 }
109 return s.VerifySignature(sthData, tls.DigitallySigned(sth.TreeHeadSignature))
110 }
111
View as plain text