diff --git a/crypto/crypto.go b/crypto/crypto.go index d1186e7..a4763c2 100644 --- a/crypto/crypto.go +++ b/crypto/crypto.go @@ -47,7 +47,23 @@ func ToPubKey(pubKey string) (ic.PubKey, error) { if err != nil { return nil, err } - return ic.UnmarshalSecp256k1PublicKey(raw) + return ic.UnmarshalPublicKey(raw) +} + +func FromPubKey(pubKey ic.PubKey) (string, error) { + pkb, err := ic.MarshalPublicKey(pubKey) + if err != nil { + return "", err + } + return base64.StdEncoding.EncodeToString(pkb), nil +} + +func FromPrivKey(privKey ic.PrivKey) (string, error) { + prkb, err := ic.MarshalPrivateKey(privKey) + if err != nil { + return "", err + } + return base64.StdEncoding.EncodeToString(prkb), nil } // Secp256k1 private key string to ic.PrivKey interface diff --git a/crypto/crypto_test.go b/crypto/crypto_test.go index e34fbac..a02da94 100644 --- a/crypto/crypto_test.go +++ b/crypto/crypto_test.go @@ -1,6 +1,7 @@ package crypto import ( + "bytes" "testing" ledgerPb "github.com/tron-us/go-btfs-common/protos/ledger" @@ -55,3 +56,50 @@ func TestEncryptDecrypt(t *testing.T) { t.Errorf("Decrypt failed") } } + +func TestSerializeDeserializeKey(t *testing.T) { + privKey, err := ToPrivKey(KeyString) + if err != nil { + t.Error("ToPrivKey failed", err) + return + } + privKeyString, err := FromPrivKey(privKey) + if err != nil { + t.Error("FromPrivKey failed", err) + return + } + if privKeyString != KeyString { + t.Error("serialize and deserialize private key fail", err) + return + } + + pubKey := privKey.GetPublic() + pubKeyString, err := FromPubKey(pubKey) + if err != nil { + t.Error("FromPubKey failed", err) + return + } + + nPubKey, err := ToPubKey(pubKeyString) + if err != nil { + t.Error("ToPubKey failed", err) + return + } + + pubkeyRaw, err := pubKey.Raw() + if err != nil { + t.Error("get pubkey raw failed", err) + return + } + nPubkeyRaw, err := nPubKey.Raw() + if err != nil { + t.Error("get PubKey raw failed", err) + return + } + + if bytes.Compare(pubkeyRaw, nPubkeyRaw) != 0 { + t.Error("serialize and deserialize pub key fail", err) + return + } + +}