-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
128 lines (121 loc) · 2.56 KB
/
main.go
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
package main
import (
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/x509"
"encoding/pem"
"fmt"
"os"
)
const (
PRIKEY = "private.pem"
PUBKEY = "public.pem"
)
func main() {
// 生成公钥和私钥
buf, err := readKeyFile(PRIKEY)
if err != nil {
// 私钥不存在 生成并保存
privateKey, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
err = savePirvateKey(privateKey)
if err != nil {
fmt.Println(err)
return
}
err = savePublicKey(privateKey.PublicKey)
if err != nil {
fmt.Println(err)
return
}
// 重新读入数据
buf, err = readKeyFile(PRIKEY)
}
//============================================
// 解码数据流
block, _ := pem.Decode(buf)
// 还原成私钥
privateKey, err := x509.ParseECPrivateKey(block.Bytes)
if err != nil {
fmt.Println(err)
return
}
//============================================
buffer, err := readKeyFile(PUBKEY)
// 解码数据流
b, _ := pem.Decode(buffer)
// 还原成私钥
publicKey, err := x509.ParsePKIXPublicKey(b.Bytes)
if err != nil {
fmt.Println(err)
return
}
//============================================
msg := []byte("dsa签名")
// 对message进入签名操作
r, s, _ := ecdsa.Sign(rand.Reader, privateKey, msg)
switch Key := publicKey.(type) {
case *ecdsa.PublicKey:
fmt.Println(ecdsa.Verify(Key, msg, r, s), "数据未被修改")
default:
fmt.Println(false, "数据已被修改")
}
}
func readKeyFile(keyFile string) ([]byte, error) {
file, err := os.Open(keyFile)
if err != nil {
return nil, err
}
defer file.Close()
fileInfo, err := file.Stat()
if err != nil {
panic("file.Stat err!")
}
buf := make([]byte, fileInfo.Size())
file.Read(buf)
return buf, nil
}
func savePirvateKey(p *ecdsa.PrivateKey) error {
priByte, err := x509.MarshalECPrivateKey(p)
if err != nil {
return err
}
block := pem.Block{
Type: "PRIVATE KEY",
Bytes: priByte,
}
file, err := os.Create("private.pem")
if err != nil {
return err
}
defer file.Close()
// 写入私钥到文件存储
err = pem.Encode(file, &block)
if err != nil {
fmt.Println("写入私钥到文件出错了")
return err
}
return nil
}
func savePublicKey(publicKey ecdsa.PublicKey) error {
pub, err := x509.MarshalPKIXPublicKey(&publicKey)
if err != nil {
return err
}
block := pem.Block{
Type: "PUBLICK KEY",
Bytes: pub,
}
file, err := os.Create("public.pem")
if err != nil {
return err
}
defer file.Close()
// 写入私钥到文件存储
err = pem.Encode(file, &block)
if err != nil {
fmt.Println("写入公钥到文件出错了")
return err
}
return nil
}