-
-
Notifications
You must be signed in to change notification settings - Fork 201
/
sm2.go
241 lines (218 loc) · 5.71 KB
/
sm2.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
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
package codec
import (
"crypto/rand"
"encoding/hex"
"errors"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strings"
"sync"
"github.com/admpub/ccs-gm/sm2"
"github.com/admpub/ccs-gm/sm3"
"github.com/admpub/ccs-gm/utils"
"github.com/admpub/ccs-gm/x509"
"github.com/webx-top/com"
"github.com/webx-top/echo"
)
var (
defaultKey *sm2.PrivateKey
defaultPwd []byte
defaultPublicKeyBytes []byte
defaultPublicKeyHex string
once sync.Once
)
// Initialize 初始化默认私钥
func Initialize() {
var err error
keyFile := filepath.Join(echo.Wd(), `data`, `sm2`, `default.pem`)
if !com.FileExists(keyFile) {
defaultKey, err = SM2GenKey()
if err != nil {
panic(`SM2GenKey: ` + err.Error())
}
if err = SaveKey(defaultKey, keyFile); err != nil {
panic(err)
}
} else {
defaultKey, err = ReadKey(keyFile)
if err != nil {
panic(err)
}
}
err = initSM2PublicKeyToMemory()
if err != nil {
panic(err)
}
}
// SaveKey 保存私钥公钥
func SaveKey(privateKey *sm2.PrivateKey, keyFile string, pwds ...[]byte) error {
pwd := defaultPwd
if len(pwds) > 0 {
pwd = pwds[0]
}
// 保存私钥
b, err := PrivateKeyToPEM(privateKey, pwd)
if err != nil {
return fmt.Errorf(`PrivateKeyToPEM: %w`, err)
}
if err := com.MkdirAll(filepath.Dir(keyFile), os.ModePerm); err != nil {
return err
}
if err = ioutil.WriteFile(keyFile, b, os.ModePerm); err != nil {
return fmt.Errorf(`WriteFile `+keyFile+`: %w`, err)
}
os.Chmod(keyFile, os.ModePerm)
// 保存公钥
b, err = PublicKeyToPEM(&privateKey.PublicKey, pwd)
if err != nil {
return fmt.Errorf(`PublicKeyToPEM: %w`, err)
}
keyFile += `.pub`
if err = ioutil.WriteFile(keyFile, b, os.ModePerm); err != nil {
return fmt.Errorf(`WriteFile `+keyFile+`: %w`, err)
}
os.Chmod(keyFile, os.ModePerm)
return nil
}
// ReadKey 读取私钥公钥
func ReadKey(keyFile string, pwds ...[]byte) (privateKey *sm2.PrivateKey, err error) {
pwd := defaultPwd
if len(pwds) > 0 {
pwd = pwds[0]
}
var b []byte
b, err = ioutil.ReadFile(keyFile)
if err != nil {
err = fmt.Errorf(`ReadFile `+keyFile+`: %w`, err)
return
}
privateKey, err = PEMtoPrivateKey(b, pwd)
if err != nil {
err = fmt.Errorf(`PEMtoPrivateKey: %w`, err)
return
}
keyFile += `.pub`
b, err = ioutil.ReadFile(keyFile)
if err != nil {
err = fmt.Errorf(`ReadFile `+keyFile+`: %w`, err)
return
}
var publickKey *sm2.PublicKey
publickKey, err = PEMtoPublicKey(b, pwd)
if err != nil {
err = fmt.Errorf(`PEMtoPrivateKey: %w`, err)
} else {
privateKey.PublicKey = *publickKey
}
return
}
func initSM2PublicKeyToMemory() (err error) {
defaultPublicKeyBytes, err = PublicKeyToBytes(&defaultKey.PublicKey)
if err == nil {
defaultPublicKeyHex = HexEncodeToString(defaultPublicKeyBytes)
}
return
}
// DefaultKey 默认私钥
func DefaultKey() *sm2.PrivateKey {
once.Do(Initialize)
return defaultKey
}
// SM2GenKey 生成私钥和公钥
func SM2GenKey() (*sm2.PrivateKey, error) {
return sm2.GenerateKey(rand.Reader)
}
// SM2VerifySign 验签
func SM2VerifySign(priv *sm2.PrivateKey, msg []byte) bool {
hash := sm3.SumSM3(msg)
r, s, err := sm2.Sign(rand.Reader, priv, hash[:])
if err != nil {
return false
}
return sm2.Verify(&priv.PublicKey, hash[:], r, s)
}
// SM2Encrypt 加密
func SM2Encrypt(pubKey *sm2.PublicKey, msg []byte) ([]byte, error) {
return sm2.Encrypt(rand.Reader, pubKey, msg)
}
// SM2Decrypt 解密
func SM2Decrypt(priv *sm2.PrivateKey, cipher []byte) ([]byte, error) {
return sm2.Decrypt(cipher, priv)
}
// PrivateKeyToPEM 私钥转PEM文件内容
func PrivateKeyToPEM(privateKey *sm2.PrivateKey, pwd []byte) ([]byte, error) {
return utils.PrivateKeyToPEM(privateKey, pwd)
}
// PublicKeyToPEM 公钥转PEM文件内容
func PublicKeyToPEM(publickKey *sm2.PublicKey, pwd []byte) ([]byte, error) {
return utils.PublicKeyToPEM(publickKey, pwd)
}
// PEMtoPrivateKey PEM文件内容转私钥
func PEMtoPrivateKey(raw []byte, pwd []byte) (*sm2.PrivateKey, error) {
return utils.PEMtoPrivateKey(raw, pwd)
}
// PEMtoPublicKey PEM文件内容转公钥
func PEMtoPublicKey(raw []byte, pwd []byte) (*sm2.PublicKey, error) {
return utils.PEMtoPublicKey(raw, pwd)
}
// HexEncodeToString hex编码为字符串
func HexEncodeToString(b []byte) string {
return hex.EncodeToString(b)
}
// PublicKeyToBytes marshals a public key to the bytes
func PublicKeyToBytes(publicKey *sm2.PublicKey) ([]byte, error) {
if publicKey == nil {
return nil, errors.New("invalid public key. It must be different from nil")
}
return x509.MarshalPKIXPublicKey(publicKey)
}
// PublicKeyToHexString 公钥转hex字符串
func PublicKeyToHexString(publicKey *sm2.PublicKey) string {
pubASN1, err := PublicKeyToBytes(publicKey)
if err != nil {
return err.Error()
}
return HexEncodeToString(pubASN1)
}
// SM2DecryptHex 解密
func SM2DecryptHex(priv *sm2.PrivateKey, cipher string, noBase64 ...bool) (string, error) {
if len(cipher) == 0 {
return ``, nil
}
base64 := true
if len(noBase64) > 0 {
base64 = !noBase64[0]
} else if strings.HasPrefix(cipher, `-`) {
base64 = false
cipher = strings.TrimPrefix(cipher, `-`)
}
b, err := hex.DecodeString(cipher)
if err != nil {
return ``, err
}
plain, err := SM2Decrypt(priv, b)
if err != nil {
return ``, err
}
actual := string(plain)
if !base64 {
return actual, nil
}
return com.Base64Decode(actual)
}
// DefaultPublicKeyBytes 默认公钥
func DefaultPublicKeyBytes() []byte {
DefaultKey()
return defaultPublicKeyBytes
}
// DefaultPublicKeyHex 默认公钥hex字符串
func DefaultPublicKeyHex() string {
DefaultKey()
return defaultPublicKeyHex
}
// DefaultSM2DecryptHex 默认密钥解密hex字符串
func DefaultSM2DecryptHex(cipher string, noBase64 ...bool) (string, error) {
return SM2DecryptHex(DefaultKey(), cipher, noBase64...)
}