Skip to content

Commit

Permalink
Merge pull request #50 from TRON-US/AddCrypto
Browse files Browse the repository at this point in the history
Add serialize pubKey and privateKey to String function
  • Loading branch information
taiyangc authored Dec 12, 2019
2 parents 51c60ac + 81b11e1 commit b90d8e8
Show file tree
Hide file tree
Showing 2 changed files with 65 additions and 1 deletion.
18 changes: 17 additions & 1 deletion crypto/crypto.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
48 changes: 48 additions & 0 deletions crypto/crypto_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package crypto

import (
"bytes"
"testing"

ledgerPb "github.com/tron-us/go-btfs-common/protos/ledger"
Expand Down Expand Up @@ -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
}

}

0 comments on commit b90d8e8

Please sign in to comment.