From 6daf77645ac3c606b3bbd51d4f5e267f4d8a0055 Mon Sep 17 00:00:00 2001 From: Jin Liu Date: Tue, 26 Nov 2019 11:42:58 -0800 Subject: [PATCH] Move functions to common and add unit test --- crypto/crypto.go | 17 ++++++++++++++++ crypto/crypto_test.go | 46 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 63 insertions(+) create mode 100644 crypto/crypto_test.go diff --git a/crypto/crypto.go b/crypto/crypto.go index 2aae305..7e38866 100644 --- a/crypto/crypto.go +++ b/crypto/crypto.go @@ -1,6 +1,8 @@ package crypto import ( + "encoding/base64" + "github.com/gogo/protobuf/proto" ic "github.com/libp2p/go-libp2p-core/crypto" ) @@ -20,3 +22,18 @@ func Verify(key ic.PubKey, channelMessage proto.Message, sig []byte) (bool, erro } return key.Verify(raw, sig) } + +// private key string to ic.PrivKey interface +// btfs config stores base64 of private key +func ToPrivKey(privKey string) (ic.PrivKey, error) { + raw, err := base64.StdEncoding.DecodeString(privKey) + if err != nil { + return nil, err + } + return ic.UnmarshalPrivateKey(raw) +} + +// public key string to ic.PubKey interface +func ToPubKey(pubKey []byte) (ic.PubKey, error) { + return ic.UnmarshalSecp256k1PublicKey(pubKey) +} diff --git a/crypto/crypto_test.go b/crypto/crypto_test.go new file mode 100644 index 0000000..69b35aa --- /dev/null +++ b/crypto/crypto_test.go @@ -0,0 +1,46 @@ +package crypto + +import ( + "testing" + + ledgerPb "github.com/tron-us/go-btfs-common/protos/ledger" +) + +const ( + KeyString = "CAISIJFNZZd5ZSvi9OlJP/mz/vvUobvlrr2//QN4DzX/EShP" +) + +func TestSignVerify(t *testing.T) { + // test get privKey and pubKey + privKey, err := ToPrivKey(KeyString) + if err != nil { + t.Error("ToPrivKey failed") + return + } + + rawPubKey, err := privKey.GetPublic().Raw() + if err != nil { + t.Error("get raw public key from privKey failed") + return + } + pubKey, err := ToPubKey(rawPubKey) + if err != nil { + t.Error("ToPubKey failed") + return + } + + // test sign and verify the key string + message := &ledgerPb.PublicKey{ + Key: rawPubKey, + } + + sign, err := Sign(privKey, message) + if err != nil { + t.Error("Sign with private key failed") + return + } + ret, err := Verify(pubKey, message, sign) + if err != nil || !ret { + t.Error("Verify with public key failed") + } +}