From 98db48ef81b43ff9309546a83f0cd5e0125374b4 Mon Sep 17 00:00:00 2001 From: Richard Ramos Date: Thu, 2 Dec 2021 03:24:12 -0400 Subject: [PATCH] generate ecdsa public key from an input public key (#219) --- crypto/ecdsa.go | 5 +++++ crypto/ecdsa_test.go | 46 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 51 insertions(+) diff --git a/crypto/ecdsa.go b/crypto/ecdsa.go index 9f8c67e..ea800ce 100644 --- a/crypto/ecdsa.go +++ b/crypto/ecdsa.go @@ -67,6 +67,11 @@ func ECDSAKeyPairFromKey(priv *ecdsa.PrivateKey) (PrivKey, PubKey, error) { return &ECDSAPrivateKey{priv}, &ECDSAPublicKey{&priv.PublicKey}, nil } +// ECDSAPublicKeyFromPubKey generates a new ecdsa public key from an input public key +func ECDSAPublicKeyFromPubKey(pub ecdsa.PublicKey) (PubKey, error) { + return &ECDSAPublicKey{pub: &pub}, nil +} + // MarshalECDSAPrivateKey returns x509 bytes from a private key func MarshalECDSAPrivateKey(ePriv ECDSAPrivateKey) ([]byte, error) { return x509.MarshalECPrivateKey(ePriv.priv) diff --git a/crypto/ecdsa_test.go b/crypto/ecdsa_test.go index eb4d181..cc75d57 100644 --- a/crypto/ecdsa_test.go +++ b/crypto/ecdsa_test.go @@ -1,6 +1,7 @@ package crypto import ( + "crypto/ecdsa" "crypto/rand" "testing" ) @@ -94,3 +95,48 @@ func TestECDSAMarshalLoop(t *testing.T) { } } + +func TestECDSAPublicKeyFromPubKey(t *testing.T) { + ecdsaPrivK, err := ecdsa.GenerateKey(ECDSACurve, rand.Reader) + if err != nil { + t.Fatal(err) + } + + privK, _, err := ECDSAKeyPairFromKey(ecdsaPrivK) + if err != nil { + t.Fatal(err) + } + + data := []byte("Hello world!") + signature, err := privK.Sign(data) + if err != nil { + t.Fatal(err) + } + + pubKey, err := ECDSAPublicKeyFromPubKey(ecdsaPrivK.PublicKey) + if err != nil { + t.Fatal(err) + } + + ok, err := pubKey.Verify(data, signature) + if err != nil { + t.Fatal(err) + } + + if !ok { + t.Fatal("signature didn't match") + } + + pubB, err := MarshalPublicKey(pubKey) + if err != nil { + t.Fatal(err) + } + pubNew, err := UnmarshalPublicKey(pubB) + if err != nil { + t.Fatal(err) + } + + if !pubKey.Equals(pubNew) || !pubNew.Equals(pubKey) { + t.Fatal("keys are not equal") + } +}