mirror of
https://github.com/libp2p/go-libp2p.git
synced 2025-10-27 02:01:39 +08:00
generate ecdsa public key from an input public key (#219)
This commit is contained in:
@@ -67,6 +67,11 @@ func ECDSAKeyPairFromKey(priv *ecdsa.PrivateKey) (PrivKey, PubKey, error) {
|
|||||||
return &ECDSAPrivateKey{priv}, &ECDSAPublicKey{&priv.PublicKey}, nil
|
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
|
// MarshalECDSAPrivateKey returns x509 bytes from a private key
|
||||||
func MarshalECDSAPrivateKey(ePriv ECDSAPrivateKey) ([]byte, error) {
|
func MarshalECDSAPrivateKey(ePriv ECDSAPrivateKey) ([]byte, error) {
|
||||||
return x509.MarshalECPrivateKey(ePriv.priv)
|
return x509.MarshalECPrivateKey(ePriv.priv)
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
package crypto
|
package crypto
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"crypto/ecdsa"
|
||||||
"crypto/rand"
|
"crypto/rand"
|
||||||
"testing"
|
"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")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user