mirror of
https://github.com/libp2p/go-libp2p-core.git
synced 2025-02-05 05:50:08 +08:00
generate ecdsa public key from an input public key (#219)
This commit is contained in:
parent
b18a4c9c56
commit
98db48ef81
@ -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)
|
||||
|
@ -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")
|
||||
}
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user