Skip to content

feat: generate a subject key identifier when creating a certificate #6379

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 8 commits into from
Jun 4, 2025
Merged
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
Loading