1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
| package test
import ( "encoding/hex" "fmt" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common/hexutil" "github.com/ethereum/go-ethereum/crypto" "github.com/ethereum/go-ethereum/log" "testing" )
func TestGenerateKey(t *testing.T) { key, err := crypto.GenerateKey() if err != nil { t.Fatalf("failed GenerateKey with %s.", err) }
fmt.Println("private key have 0x \n", hexutil.Encode(crypto.FromECDSA(key))) fmt.Println("private key no 0x \n", hex.EncodeToString(crypto.FromECDSA(key)))
if err := crypto.SaveECDSA("privatekey", key); err != nil { log.Error(fmt.Sprintf("Failed to persist node key: %v", err)) }
fmt.Println("public key have 0x \n", hexutil.Encode(crypto.FromECDSAPub(&key.PublicKey))) fmt.Println("public key no 0x \n", hex.EncodeToString(crypto.FromECDSAPub(&key.PublicKey)))
acc1Key, _ := crypto.HexToECDSA("8a1f9a8f95be41cd7ccb6168179afb4504aefe388d1e14474d32c45c72ce7b7a") address1 := crypto.PubkeyToAddress(acc1Key.PublicKey) fmt.Println("address ", address1.String())
dummyAddr := common.HexToAddress("9b2055d370f73ec7d8a03e965129118dc8f5bf83") fmt.Println("dummyAddr",dummyAddr.String())
addr3 := common.BytesToAddress([]byte("ethereum")) fmt.Println("address ",addr3.String())
hash1 := common.BytesToHash([]byte("topic1")) fmt.Println("hash ",hash1.String())
var testAddrHex = "970e8128ab834e8eac17ab8e3812f010678cf791" var testPrivHex = "289c2857d4598e37fb9647507e47a309d6133539bf21a8b9cb6df88fd5232032" key1, _ := crypto.HexToECDSA(testPrivHex) addrtest := common.HexToAddress(testAddrHex)
msg := crypto.Keccak256([]byte("foo")) sig, err := crypto.Sign(msg, key1) recoveredPub, err := crypto.Ecrecover(msg, sig) pubKey, _ := crypto.UnmarshalPubkey(recoveredPub) recoveredAddr := crypto.PubkeyToAddress(*pubKey)
recoveredPub2, _ := crypto.SigToPub(msg, sig) recoveredAddr2 := crypto.PubkeyToAddress(*recoveredPub2)
fmt.Println("addrtest ",addrtest.String()) fmt.Println("recoveredAddr ",recoveredAddr.String()) fmt.Println("recoveredAddr2 ",recoveredAddr2.String()) }
|