5
5
package certs
6
6
7
7
import (
8
+ "crypto"
9
+ "crypto/ecdsa"
10
+ "crypto/elliptic"
8
11
"crypto/rand"
9
12
"crypto/rsa"
13
+ "crypto/sha256"
10
14
"crypto/tls"
11
15
"crypto/x509"
12
16
"crypto/x509/pkix"
@@ -91,6 +95,8 @@ func GenCA(t *testing.T) tls.Certificate {
91
95
t .Fatalf ("fail to generate RSA key: %v" , err )
92
96
}
93
97
98
+ ca .SubjectKeyId = generateSubjectKeyID (caKey )
99
+
94
100
caBytes , err := x509 .CreateCertificate (rand .Reader , ca , ca , & caKey .PublicKey , caKey )
95
101
if err != nil {
96
102
t .Fatalf ("fail to create certificate: %v" , err )
@@ -108,6 +114,23 @@ func GenCA(t *testing.T) tls.Certificate {
108
114
}
109
115
}
110
116
117
+ func generateSubjectKeyID (pub crypto.PublicKey ) []byte {
118
+ // SubjectKeyId generated using method 1 in RFC 7093, Section 2:
119
+ // 1) The keyIdentifier is composed of the leftmost 160-bits of the
120
+ // SHA-256 hash of the value of the BIT STRING subjectPublicKey
121
+ // (excluding the tag, length, and number of unused bits).
122
+ var publicKeyBytes []byte
123
+ switch publicKey := pub .(type ) {
124
+ case * rsa.PublicKey :
125
+ publicKeyBytes = x509 .MarshalPKCS1PublicKey (publicKey )
126
+ case * ecdsa.PublicKey :
127
+ //nolint:staticcheck // no alternative
128
+ publicKeyBytes = elliptic .Marshal (publicKey .Curve , publicKey .X , publicKey .Y )
129
+ }
130
+ h := sha256 .Sum256 (publicKeyBytes )
131
+ return h [:20 ]
132
+ }
133
+
111
134
// GenCert generates a test keypair and signs the cert with the passed CA.
112
135
// copied from elastic-agent-libs/transport/tlscommon/ca_pinning_test.go
113
136
func GenCert (t * testing.T , ca tls.Certificate ) tls.Certificate {
0 commit comments