Skip to content
This repository has been archived by the owner on Sep 6, 2022. It is now read-only.

generate ecdsa public key from an input public key #219

Merged
merged 1 commit into from
Dec 2, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions crypto/ecdsa.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
46 changes: 46 additions & 0 deletions crypto/ecdsa_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package crypto

import (
"crypto/ecdsa"
"crypto/rand"
"testing"
)
Expand Down Expand Up @@ -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")
}
}