Skip to content

Commit 81c6724

Browse files
michel-latermanmergify[bot]
authored andcommitted
Change CA generation in tests to avoid using SHA1 (#4361)
(cherry picked from commit 8909668)
1 parent b0e3be2 commit 81c6724

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

internal/pkg/testing/certs/certs.go

+23
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,12 @@
55
package certs
66

77
import (
8+
"crypto"
9+
"crypto/ecdsa"
10+
"crypto/elliptic"
811
"crypto/rand"
912
"crypto/rsa"
13+
"crypto/sha256"
1014
"crypto/tls"
1115
"crypto/x509"
1216
"crypto/x509/pkix"
@@ -91,6 +95,8 @@ func GenCA(t *testing.T) tls.Certificate {
9195
t.Fatalf("fail to generate RSA key: %v", err)
9296
}
9397

98+
ca.SubjectKeyId = generateSubjectKeyID(caKey)
99+
94100
caBytes, err := x509.CreateCertificate(rand.Reader, ca, ca, &caKey.PublicKey, caKey)
95101
if err != nil {
96102
t.Fatalf("fail to create certificate: %v", err)
@@ -108,6 +114,23 @@ func GenCA(t *testing.T) tls.Certificate {
108114
}
109115
}
110116

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+
111134
// GenCert generates a test keypair and signs the cert with the passed CA.
112135
// copied from elastic-agent-libs/transport/tlscommon/ca_pinning_test.go
113136
func GenCert(t *testing.T, ca tls.Certificate) tls.Certificate {

0 commit comments

Comments
 (0)