github.com/turingchain2020/turingchain@v1.1.21/system/crypto/ed25519/ed25519_test.go (about)

     1  package ed25519
     2  
     3  import (
     4  	"encoding/hex"
     5  	"fmt"
     6  	"testing"
     7  
     8  	"github.com/turingchain2020/turingchain/common"
     9  	"github.com/stretchr/testify/assert"
    10  )
    11  
    12  func TestGenKey(t *testing.T) {
    13  	d := &Driver{}
    14  	key, err := d.GenKey()
    15  	assert.Nil(t, err)
    16  	assert.Equal(t, 64, len(key.Bytes()))
    17  }
    18  
    19  func TestPrivateKeyFromBytes(t *testing.T) {
    20  	hexstr := "99827c6a9f0aae804ab0a0a3676c6502464864fd8398e0346895e6996ac77a81ae67c2c99ce7590c3010f9f813c517f2261ccd18cde910f13ec00caaa3360ff1"
    21  	assert.Len(t, hexstr, 128)
    22  
    23  	pbytes, err := hex.DecodeString(hexstr)
    24  	assert.Nil(t, err)
    25  	d := &Driver{}
    26  	priv, err := d.PrivKeyFromBytes(pbytes)
    27  	assert.Nil(t, err)
    28  	assert.Equal(t, pbytes, priv.Bytes())
    29  
    30  	priv, err = d.PrivKeyFromBytes(pbytes[0:32])
    31  	assert.Nil(t, err)
    32  	assert.Equal(t, pbytes, priv.Bytes())
    33  
    34  	assert.Equal(t, priv.PubKey().Bytes(), pbytes[32:])
    35  	assert.True(t, priv.Equals(priv))
    36  
    37  	//sig
    38  	msg := []byte("message")
    39  	sig := priv.Sign(msg)
    40  	sighex := fmt.Sprintf("%X", sig.Bytes())
    41  	assert.Equal(t, "/"+sighex+".../", sig.String())
    42  
    43  	sigbytes, err := common.FromHex(sighex)
    44  	assert.Nil(t, err)
    45  	sig2, err := d.SignatureFromBytes(sigbytes)
    46  	assert.Nil(t, err)
    47  	assert.True(t, sig2.Equals(sig))
    48  	assert.False(t, sig2.IsZero())
    49  
    50  	//pub
    51  	pub := priv.PubKey()
    52  	pubhex := fmt.Sprintf("%X", pub.Bytes())
    53  	assert.Equal(t, pubhex, pub.KeyString())
    54  	pub2, err := d.PubKeyFromBytes(pub.Bytes())
    55  	assert.Nil(t, err)
    56  	assert.True(t, pub.Equals(pub2))
    57  
    58  	assert.True(t, pub2.VerifyBytes(msg, sig))
    59  	assert.Nil(t, d.Validate(msg, pub.Bytes(), sigbytes))
    60  }