Skip to content

Commit

Permalink
feat: generate a subject key identifier when creating a certificate
Browse files Browse the repository at this point in the history
If a subject key id is omitted, go will generate one using sha1.
This is described as method 1 in RFC 5280 Section 4.2.1.2.

When sha1 is not available (e.g. fips only mode) this method will
panic.

Update the code to explicitly pass a subject key id to avoid calling
sha1 functions. The new SubjectKeyId is generated using
method 1 in RFC 7093 Section 2 which takes 160-bits of the SHA-256 hash.
  • Loading branch information
kruskall committed Dec 18, 2024
1 parent 0e68ce1 commit d587478
Showing 1 changed file with 16 additions and 0 deletions.
16 changes: 16 additions & 0 deletions internal/pkg/core/authority/ca.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"crypto"
"crypto/rand"
"crypto/rsa"
"crypto/sha256"
"crypto/tls"
"crypto/x509"
"crypto/x509/pkix"
Expand Down Expand Up @@ -54,6 +55,9 @@ func NewCA() (*CertificateAuthority, error) {

privateKey, _ := rsa.GenerateKey(rand.Reader, 2048)
publicKey := &privateKey.PublicKey

ca.SubjectKeyId = generateSubjectKeyID(publicKey)

caBytes, err := x509.CreateCertificate(rand.Reader, ca, ca, publicKey, privateKey)
if err != nil {
log.Println("create ca failed", err)
Expand Down Expand Up @@ -96,6 +100,16 @@ func NewCA() (*CertificateAuthority, error) {
}, nil
}

func generateSubjectKeyID(publicKey *rsa.PublicKey) []byte {
// SubjectKeyId generated using method 1 in RFC 7093, Section 2:
// 1) The keyIdentifier is composed of the leftmost 160-bits of the
// SHA-256 hash of the value of the BIT STRING subjectPublicKey
// (excluding the tag, length, and number of unused bits).
publicKeyBytes := x509.MarshalPKCS1PublicKey(publicKey)
h := sha256.Sum256(publicKeyBytes)
return h[:20]
}

// GeneratePair generates child certificate
func (c *CertificateAuthority) GeneratePair() (*Pair, error) {
return c.GeneratePairWithName("localhost")
Expand All @@ -119,6 +133,8 @@ func (c *CertificateAuthority) GeneratePairWithName(name string) (*Pair, error)
privateKey, _ := rsa.GenerateKey(rand.Reader, 2048)
publicKey := &privateKey.PublicKey

certTemplate.SubjectKeyId = generateSubjectKeyID(publicKey)

// Sign the certificate
certBytes, err := x509.CreateCertificate(rand.Reader, certTemplate, c.caCert, publicKey, c.privateKey)
if err != nil {
Expand Down

0 comments on commit d587478

Please sign in to comment.