Skip to content

Commit

Permalink
Adding methods for exporting
Browse files Browse the repository at this point in the history
Adds a method to KeyPair and CertificateAuthority to export the
certificate to an struct directly.
  • Loading branch information
mys721tx committed Dec 26, 2024
1 parent 5cf4d0f commit b49928d
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 0 deletions.
10 changes: 10 additions & 0 deletions testcerts.go
Original file line number Diff line number Diff line change
Expand Up @@ -194,6 +194,11 @@ func (ca *CertificateAuthority) NewKeyPairFromConfig(config KeyPairConfig) (*Key
return kp, nil
}

// Cert returns the CertificateAuthority Certificate.
func (ca *CertificateAuthority) Cert() *x509.Certificate {
return ca.cert
}

// CertPool returns a Certificate Pool of the CertificateAuthority Certificate.
func (ca *CertificateAuthority) CertPool() *x509.CertPool {
return ca.certPool
Expand Down Expand Up @@ -271,6 +276,11 @@ func (ca *CertificateAuthority) GenerateTLSConfig() *tls.Config {
}
}

// Cert returns the Certificate of the KeyPair.
func (kp *KeyPair) Cert() *x509.Certificate {
return kp.cert
}

// PrivateKey returns the private key of the KeyPair.
func (kp *KeyPair) PrivateKey() []byte {
return pem.EncodeToMemory(kp.privateKey)
Expand Down
18 changes: 18 additions & 0 deletions testcerts_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,18 @@ func TestCertsUsage(t *testing.T) {
t.Errorf("Unexpected key length from public/private key")
}

t.Run("Verify Cert",
func(t *testing.T) {
if cert := ca.Cert(); cert == nil {
t.Fatalf("Expected certificate, got nil")
} else if cert.SerialNumber.Cmp(big.NewInt(42)) != 0 {
t.Errorf("Unexpected Serial Number, expected 42 got %v", cert.SerialNumber)
} else if cert.Subject.Organization[0] != "Never Use this Certificate in Production Inc." {
t.Errorf("Unexpected Organization, expected 'Never Use this Certificate in Production Inc.' got %v", cert.Subject.Organization[0])
}
},
)

t.Run("Verify CertPool", func(t *testing.T) {
cp := x509.NewCertPool()
if cp.AppendCertsFromPEM(ca.PublicKey()) {
Expand Down Expand Up @@ -112,6 +124,12 @@ func TestCertsUsage(t *testing.T) {
t.Errorf("NewKeyPair() returned error when generating with domains: %s", err)
}

t.Run("Verify Cert", func(t *testing.T) {
if cert := kp.Cert(); cert == nil {
t.Fatalf("Expected certificate, got nil")
}
})

t.Run("Validate Key Length", func(t *testing.T) {
if len(kp.PrivateKey()) == 0 || len(kp.PublicKey()) == 0 {
t.Errorf("Unexpected key length from public/private key")
Expand Down

0 comments on commit b49928d

Please sign in to comment.