package main import ( "crypto/ecdsa" "crypto/elliptic" "crypto/rand" "fmt" "crypto/sha256" "math/big" "log" "encoding/gob" "bytes" ) //import ( // "fmt" // "github.com/boltdb/bolt" // "blockchaindemo01/myblock" //) func main() { privateKey,
import (
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"fmt"
"crypto/sha256"
"math/big"
"log"
"encoding/gob"
"bytes"
)
//import (
// "fmt"
// "github.com/boltdb/bolt"
// "blockchaindemo01/myblock"
//)
func main() {
privateKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
log.Panic(err)
}
pubKeyRaw := privateKey.PublicKey
data := "helloworld"
dataHash := sha256.Sum256([]byte(data))
// func Sign(rand io.Reader, priv *PrivateKey, hash []byte) (r, s *big.Int, err error) {
r, s, _ := ecdsa.Sign(rand.Reader, privateKey, dataHash[:])
//将r,s拼接成字节流
signature := append(r.Bytes(), s.Bytes()...)
//将公钥拼接成字节流传递,在对端拆分
//type PublicKey struct {
// elliptic.Curve
// X, Y *big.Int
//}
//真正传递的形式
pubKey := append(pubKeyRaw.X.Bytes(), pubKeyRaw.Y.Bytes()...)
//....
//根据signature 切出来r1, s1, 一分为二
r1 := big.Int{}
s1 := big.Int{}
r1Data := signature[:len(signature)/2]
s1Data := signature[len(signature)/2:]
r1.SetBytes(r1Data)
s1.SetBytes(s1Data)
//切pubkey字节流
x1 := big.Int{}
y1 := big.Int{}
x1Data := pubKey[:len(pubKey)/2]
y1Data := pubKey[len(pubKey)/2:]
x1.SetBytes(x1Data)
y1.SetBytes(y1Data)
curve := elliptic.P256()
pubKeyOrigin := ecdsa.PublicKey{curve, &x1, &y1}
// func Verify(pub *PublicKey, hash []byte, r, s *big.Int) bool {
//res := ecdsa.Verify(&pubKey, dataHash[:], r, s)
res := ecdsa.Verify(&pubKeyOrigin, dataHash[:], &r1, &s1)
fmt.Printf("res : %v\n", res)
}
//block := myblock.NewBlock([]byte{}, "this is the gensis ")
//BlockChainRun()
//转账
//myblock.BlockChainRun()
//fmt.Println("你好")
//BoltDemo()
func funcName() {
privateKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
fmt.Println("产生公钥出错")
}
publicKey := privateKey.PublicKey
info := []byte("hello")
hash := sha256.Sum256(info)
ecdsa.Sign(rand.Reader, privateKey, hash[:])
if err != nil {
fmt.Println("签名失败")
}
signature := append(publicKey.X.Bytes(), publicKey.Y.Bytes()...)
publicKeyToBytes := PublicKeyToBytes(&publicKey)
publicKeyFromBytes := PublicKeyFromBytes(publicKeyToBytes)
r1data := signature[:len(signature)/2]
s1data := signature[len(signature)/2:]
r11 := big.Int{}
s11 := big.Int{}
r11.SetBytes(r1data)
s11.SetBytes(s1data)
//publicKey1 := ecdsa.PublicKey{elliptic.P256(), &r11, &s11}
verify := ecdsa.Verify(publicKeyFromBytes, hash[:], &r11, &s11)
fmt.Println(verify)
}
func PublicKeyToBytes(pk *ecdsa.PublicKey) []byte{
var buf bytes.Buffer
encoder := gob.NewEncoder(&buf)
encode := encoder.Encode(&pk)
if encode!=nil {
fmt.Println(encode)
}
return buf.Bytes()
}
func PublicKeyFromBytes(data []byte) *ecdsa.PublicKey{
var pk ecdsa.PublicKey
decoder := gob.NewDecoder(bytes.NewReader(data))
err := decoder.Decode(&pk)
if err!=nil {
fmt.Println(err)
}
return &pk
}