Skip to content

Commit

Permalink
Merge pull request #34 from TRON-US/BTFS-1078
Browse files Browse the repository at this point in the history
Move functions to common and add unit test
  • Loading branch information
jin-tron authored Nov 26, 2019
2 parents 58c231a + 6daf776 commit 29935ec
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 0 deletions.
17 changes: 17 additions & 0 deletions crypto/crypto.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package crypto

import (
"encoding/base64"

"github.com/gogo/protobuf/proto"
ic "github.com/libp2p/go-libp2p-core/crypto"
)
Expand All @@ -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)
}
46 changes: 46 additions & 0 deletions crypto/crypto_test.go
Original file line number Diff line number Diff line change
@@ -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")
}
}

0 comments on commit 29935ec

Please sign in to comment.