/
sm2.go
318 lines (281 loc) · 7.75 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
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
package codec
import (
"crypto/rand"
"encoding/hex"
"errors"
"fmt"
"os"
"path/filepath"
"strings"
"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/admpub/once"
"github.com/webx-top/com"
"github.com/webx-top/echo"
)
var DefaultSM2 = NewSM2(`default`)
func NewSM2(name string) *SM2 {
return &SM2{
sm2Name: name,
}
}
type SM2 struct {
sm2Name string
defaultKey *sm2.PrivateKey
defaultPwd []byte
defaultPublicKeyBytes []byte
defaultPublicKeyHex string
sm2once once.Once
keyFile string
}
// Initialize 初始化默认私钥
func (s *SM2) init() {
var err error
if len(s.keyFile) == 0 {
s.keyFile = filepath.Join(echo.Wd(), `data`, `sm2`, s.sm2Name+`.pem`)
}
if !com.FileExists(s.keyFile) {
s.defaultKey, err = SM2GenKey()
if err != nil {
panic(`SM2GenKey: ` + err.Error())
}
if err = SaveKey(s.defaultKey, s.keyFile); err != nil {
panic(err)
}
} else {
s.defaultKey, err = ReadKey(s.keyFile)
if err != nil {
panic(err)
}
}
err = s.initPublicKeyToMemory()
if err != nil {
panic(err)
}
}
// SaveKey 保存私钥公钥
func (s *SM2) SaveKey(privateKey *sm2.PrivateKey, keyFile string, pwds ...[]byte) error {
pwd := s.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 = os.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 = os.WriteFile(keyFile, b, os.ModePerm); err != nil {
return fmt.Errorf(`WriteFile `+keyFile+`: %w`, err)
}
os.Chmod(keyFile, os.ModePerm)
return nil
}
// ReadKey 读取私钥公钥
func (s *SM2) ReadKey(keyFile string, pwds ...[]byte) (privateKey *sm2.PrivateKey, err error) {
pwd := s.defaultPwd
if len(pwds) > 0 {
pwd = pwds[0]
}
var b []byte
b, err = os.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 = os.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 (s *SM2) initPublicKeyToMemory() (err error) {
s.defaultPublicKeyBytes, err = PublicKeyToBytes(&s.defaultKey.PublicKey)
if err == nil {
s.defaultPublicKeyHex = HexEncodeToString(s.defaultPublicKeyBytes)
}
return
}
// DefaultKey 默认私钥
func (s *SM2) DefaultKey() *sm2.PrivateKey {
s.sm2once.Do(s.init)
return s.defaultKey
}
// DefaultPublicKeyBytes 默认公钥
func (s *SM2) DefaultPublicKeyBytes() []byte {
s.DefaultKey()
return s.defaultPublicKeyBytes
}
// DefaultPublicKeyHex 默认公钥hex字符串
func (s *SM2) DefaultPublicKeyHex() string {
s.DefaultKey()
return s.defaultPublicKeyHex
}
// DefaultSM2EncryptHex 默认密钥加密并返回hex字符串
func (s *SM2) DefaultEncryptHex(cipher string, noBase64 ...bool) (string, error) {
return SM2EncryptHex(&s.DefaultKey().PublicKey, cipher, noBase64...)
}
// DefaultSM2DecryptHex 默认密钥解密hex字符串
func (s *SM2) DefaultDecryptHex(cipher string, noBase64 ...bool) (string, error) {
return SM2DecryptHex(s.DefaultKey(), cipher, noBase64...)
}
func (s *SM2) Reset() {
s.sm2once.Reset()
}
// ----------------
// SaveKey 保存私钥公钥
func SaveKey(privateKey *sm2.PrivateKey, keyFile string, pwds ...[]byte) error {
return DefaultSM2.SaveKey(privateKey, keyFile, pwds...)
}
// ReadKey 读取私钥公钥
func ReadKey(keyFile string, pwds ...[]byte) (privateKey *sm2.PrivateKey, err error) {
return DefaultSM2.ReadKey(keyFile, pwds...)
}
// DefaultKey 默认私钥
func DefaultKey() *sm2.PrivateKey {
return DefaultSM2.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)
}
// SM2EncryptHex 加密
func SM2EncryptHex(publicKey *sm2.PublicKey, cipher string, noBase64 ...bool) (string, error) {
base64 := true
if len(noBase64) > 0 {
base64 = !noBase64[0]
}
if base64 {
cipher = com.Base64Encode(cipher)
}
encrypted, err := SM2Encrypt(publicKey, []byte(cipher))
if err != nil {
return ``, err
}
return HexEncodeToString(encrypted), nil
}
// 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 {
return DefaultSM2.DefaultPublicKeyBytes()
}
// DefaultPublicKeyHex 默认公钥hex字符串
func DefaultPublicKeyHex() string {
return DefaultSM2.DefaultPublicKeyHex()
}
// DefaultSM2DecryptHex 默认密钥解密hex字符串
func DefaultSM2DecryptHex(cipher string, noBase64 ...bool) (string, error) {
return DefaultSM2.DefaultDecryptHex(cipher, noBase64...)
}
// DefaultSM2EncryptHex 默认密钥加密并返回hex字符串
func DefaultSM2EncryptHex(cipher string, noBase64 ...bool) (string, error) {
return DefaultSM2.DefaultEncryptHex(cipher, noBase64...)
}
func SM2Reset() {
DefaultSM2.Reset()
}