github.com/turingchain2020/turingchain@v1.1.21/system/crypto/secp256r1/secp256r1_test.go (about) 1 package ecdsa 2 3 import ( 4 "strings" 5 "testing" 6 7 "github.com/stretchr/testify/assert" 8 "github.com/stretchr/testify/require" 9 ) 10 11 func TestAll(t *testing.T) { 12 testCrypto(t) 13 testFromBytes(t) 14 testCryptoCompress(t) 15 } 16 17 func testFromBytes(t *testing.T) { 18 require := require.New(t) 19 20 c := &Driver{} 21 22 priv, err := c.GenKey() 23 require.Nil(err) 24 25 priv2, err := c.PrivKeyFromBytes(priv.Bytes()) 26 require.Nil(err) 27 require.Equal(true, priv.Equals(priv2)) 28 29 s1 := string(priv.Bytes()) 30 s2 := string(priv2.Bytes()) 31 require.Equal(0, strings.Compare(s1, s2)) 32 33 pub := priv.PubKey() 34 require.NotNil(pub) 35 36 pub2, err := c.PubKeyFromBytes(pub.Bytes()) 37 require.Nil(err) 38 require.Equal(true, pub.Equals(pub2)) 39 40 s1 = string(pub.Bytes()) 41 s2 = string(pub2.Bytes()) 42 require.Equal(0, strings.Compare(s1, s2)) 43 44 var msg = []byte("hello world") 45 sign1 := priv.Sign(msg) 46 sign2 := priv2.Sign(msg) 47 48 sign3, err := c.SignatureFromBytes(sign1.Bytes()) 49 require.Nil(err) 50 require.Equal(true, sign3.Equals(sign1)) 51 52 require.Equal(true, pub.VerifyBytes(msg, sign1)) 53 require.Equal(true, pub2.VerifyBytes(msg, sign1)) 54 require.Equal(true, pub.VerifyBytes(msg, sign2)) 55 require.Equal(true, pub2.VerifyBytes(msg, sign2)) 56 require.Equal(true, pub.VerifyBytes(msg, sign3)) 57 require.Equal(true, pub2.VerifyBytes(msg, sign3)) 58 } 59 60 func testCrypto(t *testing.T) { 61 require := require.New(t) 62 63 c := &Driver{} 64 65 priv, err := c.GenKey() 66 require.Nil(err) 67 t.Logf("priv:%X, len:%d", priv.Bytes(), len(priv.Bytes())) 68 69 pub := priv.PubKey() 70 require.NotNil(pub) 71 t.Logf("pub:%X, len:%d", pub.Bytes(), len(pub.Bytes())) 72 73 msg := []byte("hello world") 74 signature := priv.Sign(msg) 75 t.Logf("sign:%X, len:%d", signature.Bytes(), len(signature.Bytes())) 76 77 ok := pub.VerifyBytes(msg, signature) 78 require.Equal(true, ok) 79 } 80 81 func testCryptoCompress(t *testing.T) { 82 require := require.New(t) 83 84 c := &Driver{} 85 86 priv, err := c.GenKey() 87 require.Nil(err) 88 t.Logf("priv:%X, len:%d", priv.Bytes(), len(priv.Bytes())) 89 90 pub := priv.PubKey() 91 require.NotNil(pub) 92 t.Logf("pub:%X, len:%d, string:%s", pub.Bytes(), len(pub.Bytes()), pub.KeyString()) 93 94 pubkey, err := parsePubKeyCompressed(pub.Bytes()) 95 assert.Nil(t, err) 96 97 pubbytes := SerializePublicKeyCompressed(pubkey) 98 pub2, err := c.PubKeyFromBytes(pubbytes) 99 assert.Nil(t, err) 100 101 msg := []byte("hello world") 102 signature := priv.Sign(msg) 103 t.Logf("sign:%X, len:%d, string:%s", signature.Bytes(), len(signature.Bytes()), signature.String()) 104 105 ok := pub.VerifyBytes(msg, signature) 106 require.Equal(true, ok) 107 108 assert.True(t, pub2.VerifyBytes(msg, signature)) 109 }