golang[36]-區塊鏈-數據簽名生成

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
65
66
67
68
69
70
71
72
73
74
75
package main

import (
"crypto/ecdsa"
"crypto/rand"
"crypto/sha256"
"crypto/elliptic"
"log"
"fmt"
)

//生成私鑰和公鑰,生成的私鑰爲結構體ecdsa.PrivateKey的指針

//type PrivateKey struct {
// PublicKey
// D *big.Int
//}
func newKeyPair2() (ecdsa.PrivateKey, []byte) {
//生成secp256k1橢圓曲線
curve := elliptic.P256()
//產生的是一個結構體指針,結構體類型爲ecdsa.PrivateKey
private, err := ecdsa.GenerateKey(curve, rand.Reader)
if err != nil {
log.Panic(err)
}
//x座標與y座標拼接在一起,生成公鑰
pubKey := append(private.PublicKey.X.Bytes(), private.PublicKey.Y.Bytes()...)

return *private, pubKey
}







func main(){
//調用函數生成私鑰與公鑰
privKey,_ := newKeyPair2()


//信息的哈希,簽名什麼樣的數據
hash := sha256.Sum256([]byte("hello world\n"))

//根據私鑰和信息的哈希進行數字簽名,產生r和s
r, s, err := ecdsa.Sign(rand.Reader, &privKey, hash[:])

 if err != nil {
log.Panic(err)
}


//r和s拼接在一起實現了數字簽名
signature := append(r.Bytes(), s.Bytes()...)
//打印數字簽名的16進制顯示
fmt.Printf("%x\n", signature)


fmt.Printf("%x\n", r.Bytes())
fmt.Printf("%x\n", s.Bytes())


//補充:如何把一個字符串轉換爲16進制數據
//m := big.Int{}
//n := big.Int{}
//rr,_:=hex.DecodeString("7dccc0f58639584a3f0c879c3688d2f4a0137697cbf34245d075c764e36233d2")
//ss,_:=hex.DecodeString("cf3713bf4369eb1c02e476cdbefb7f76a25b572f53fb71d4e4742fa11c827526")
//
//m.SetBytes(rr)
//n.SetBytes(ss)
//
//fmt.Printf("%x\n", m.Bytes())
//fmt.Printf("%x\n", n.Bytes())
}

image.png

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章