Skip to content

Commit

Permalink
certtostore: Add tests for FileStorage.Sign().
Browse files Browse the repository at this point in the history
This found a bug in the test code: the leaf cert was actually a self-signed cert.

PiperOrigin-RevId: 724049109
  • Loading branch information
CertoToStore Team authored and copybara-github committed Feb 6, 2025
1 parent 817d77d commit dee7a37
Showing 1 changed file with 44 additions and 2 deletions.
46 changes: 44 additions & 2 deletions certtostore_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,8 @@ func generateCertificate(caStore CertStorage) (CertStorage, error) {
Algorithm: RSA,
Size: 2048,
}
if _, err := leafStore.Generate(opts); err != nil {
leafSigner, err := leafStore.Generate(opts)
if err != nil {
return nil, fmt.Errorf("leafStore.Generate(%v): %v", opts, err)
}
// Sign the leaf cert request with the CA certificate.
Expand All @@ -79,7 +80,7 @@ func generateCertificate(caStore CertStorage) (CertStorage, error) {
if err != nil {
return nil, fmt.Errorf("caStore.Key: %v", err)
}
der, err := x509.CreateCertificate(rand.Reader, &template, caCrt, caKey.Public(), caKey)
der, err := x509.CreateCertificate(rand.Reader, &template, caCrt, leafSigner.Public(), caKey)
if err != nil {
return nil, fmt.Errorf("x509.CreateCertificate: %v", err)
}
Expand Down Expand Up @@ -152,6 +153,47 @@ func TestCredential(t *testing.T) {
}
}

func verifySig(pub crypto.PublicKey, sig []byte, digest []byte) error {
switch pub := pub.(type) {
case *rsa.PublicKey:
return rsa.VerifyPKCS1v15(pub, crypto.SHA256, digest, sig)
default:
return fmt.Errorf("unsupported public key type: %T", pub)
}
}

func TestSign(t *testing.T) {
testmsg := []byte("test")
digest := sha256.Sum256(testmsg)
ca := NewFileStorage(testdata.CAPath())
// Use the CA CertStorage to issue a leaf cert.
leafStore, err := generateCertificate(ca)
if err != nil {
t.Fatalf("error generating certificate: %v", err)
}
k, err := leafStore.Key()
if err != nil {
t.Fatalf("error retrieving key: %v", err)
}

sig, err := k.Sign(rand.Reader, digest[:], crypto.SHA256)
if err != nil {
t.Fatalf("error signing: %v", err)
}
if len(sig) == 0 {
t.Fatalf("signature is empty")
}

pub := k.Public()
if pub == nil {
t.Fatal("public key is nil")
}
err = verifySig(pub, sig, digest[:])
if err != nil {
t.Fatalf("error verifying signature: %v", err)
}
}

func TestDecrypt(t *testing.T) {
ca := NewFileStorage(testdata.CAPath())
// Decrypt the test message.
Expand Down

0 comments on commit dee7a37

Please sign in to comment.