-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathencrypt.go
421 lines (378 loc) · 9.74 KB
/
encrypt.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
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
package wen
import (
"bytes"
"crypto"
"crypto/aes"
"crypto/cipher"
"crypto/md5"
"crypto/rand"
"crypto/rsa"
"crypto/sha1"
"crypto/sha256"
"crypto/sha512"
"crypto/x509"
"encoding/base64"
"encoding/hex"
"errors"
"io"
"golang.org/x/crypto/bcrypt"
)
type SignType string
const (
MD5 SignType = "MD5"
SHA1 SignType = "SHA1"
SHA256 SignType = "SHA256"
SHA512 SignType = "SHA512"
)
// MD5加密
func EncryptMD5(message string) string {
hash := md5.New()
hash.Write([]byte(message))
bytes := hash.Sum(nil)
hashCode := hex.EncodeToString(bytes)
return hashCode
}
// SHA1加密
func EncryptSHA1(message string) string {
hash := sha1.New()
hash.Write([]byte(message))
bytes := hash.Sum(nil)
hashCode := hex.EncodeToString(bytes)
return hashCode
}
// SHA256加密
func EncryptSHA256(message string) string {
hash := sha256.New()
hash.Write([]byte(message))
bytes := hash.Sum(nil)
hashCode := hex.EncodeToString(bytes)
return hashCode
}
// SHA512加密
func EncryptSHA512(message string) string {
hash := sha512.New()
hash.Write([]byte(message))
bytes := hash.Sum(nil)
hashCode := hex.EncodeToString(bytes)
return hashCode
}
// BASE64编码
func EncryptBASE64(message []byte) string {
return base64.StdEncoding.EncodeToString(message)
}
// AES 加密
func EncryptAES(data, key []byte) []byte {
//Create a new Cipher Block from the key
block, err := aes.NewCipher(key)
if err != nil {
panic(err.Error())
}
//Create a new GCM - https://en.wikipedia.org/wiki/Galois/Counter_Mode
//https://golang.org/pkg/crypto/cipher/#NewGCM
aesGCM, err := cipher.NewGCM(block)
if err != nil {
panic(err.Error())
}
//Create a nonce. Nonce should be from GCM
nonce := make([]byte, aesGCM.NonceSize())
if _, err = io.ReadFull(rand.Reader, nonce); err != nil {
panic(err.Error())
}
//Encrypt the data using aesGCM.Seal
//Since we don't want to save the nonce somewhere else in this case, we add it as a prefix to the encrypted data. The first nonce argument in Seal is the prefix.
ciphertext := aesGCM.Seal(nonce, nonce, data, nil)
return ciphertext
}
// AES 解密
func DecryptAES(data, key []byte) []byte {
//Create a new Cipher Block from the key
block, err := aes.NewCipher(key)
if err != nil {
panic(err.Error())
}
//Create a new GCM
aesGCM, err := cipher.NewGCM(block)
if err != nil {
panic(err.Error())
}
//Get the nonce size
nonceSize := aesGCM.NonceSize()
//Extract the nonce from the encrypted data
nonce, ciphertext := data[:nonceSize], data[nonceSize:]
//Decrypt the data
plaintext, err := aesGCM.Open(nil, nonce, ciphertext, nil)
if err != nil {
panic(err.Error())
}
return plaintext
}
// func DecryptAESCBC(data, key []byte) ([]byte, error) {
// var aesBlockDecrypt cipher.Block
// aesBlockDecrypt, err := aes.NewCipher(key)
// if err != nil {
// return nil, err
// }
// // aesDecrypt := cipher.NewCBCDecrypter(aesBlockDecrypt)
// return nil, nil
// }
// BASE64解码
func DecryptBASE64(message string) ([]byte, error) {
return base64.StdEncoding.DecodeString(message)
}
// 生成RSA密钥对
func GenerateRSAKey(bits int, isPKCS8 bool) (string, string, error) {
if bits < 512 || bits > 2048 {
return "", "", errors.New("密钥位数需在512-2048之间")
}
// 生成私钥
privateKey, err := rsa.GenerateKey(rand.Reader, bits)
if err != nil {
return "", "", err
}
var privateDer []byte
if isPKCS8 {
privateDer, err = x509.MarshalPKCS8PrivateKey(privateKey)
if err != nil {
return "", "", err
}
} else {
privateDer = x509.MarshalPKCS1PrivateKey(privateKey)
}
// 生成公钥
publicDer, err := x509.MarshalPKIXPublicKey(&privateKey.PublicKey)
if err != nil {
return "", "", err
}
return EncryptBASE64(privateDer), EncryptBASE64(publicDer), nil
}
// RSA公钥加密
func EncryptRSA(message, publicKey string) (string, error) {
key, err := DecryptBASE64(publicKey)
if err != nil {
return "", err
}
pubKey, err := x509.ParsePKIXPublicKey(key)
if err != nil {
return "", err
}
encryptedData, err := rsa.EncryptPKCS1v15(rand.Reader, pubKey.(*rsa.PublicKey), []byte(message))
if err != nil {
return "", err
}
return EncryptBASE64(encryptedData), nil
}
// RSA私钥解密
func DecryptRSA(message, privateKey string, isPKCS8 bool) (string, error) {
messageBytes, err := DecryptBASE64(message)
if err != nil {
return "", err
}
key, err := DecryptBASE64(privateKey)
if err != nil {
return "", err
}
var priKey interface{}
if isPKCS8 {
priKey, err = x509.ParsePKCS8PrivateKey(key)
} else {
priKey, err = x509.ParsePKCS1PrivateKey(key)
}
if err != nil {
return "", err
}
decryptedData, err := rsa.DecryptPKCS1v15(rand.Reader, priKey.(*rsa.PrivateKey), messageBytes)
if err != nil {
return "", err
}
return string(decryptedData), nil
}
// RSA私钥签名
func SignRSA(message, privateKey string, signType SignType, isPKCS8 bool) (string, error) {
key, err := DecryptBASE64(privateKey)
if err != nil {
return "", err
}
var priKey interface{}
if isPKCS8 {
priKey, err = x509.ParsePKCS8PrivateKey(key)
} else {
priKey, err = x509.ParsePKCS1PrivateKey(key)
}
if err != nil {
return "", err
}
var signature []byte
switch signType {
case MD5:
h := md5.New()
h.Write([]byte(message))
hash := h.Sum(nil)
signature, err = rsa.SignPKCS1v15(rand.Reader, priKey.(*rsa.PrivateKey), crypto.MD5, hash)
case SHA1:
h := sha1.New()
h.Write([]byte(message))
hash := h.Sum(nil)
signature, err = rsa.SignPKCS1v15(rand.Reader, priKey.(*rsa.PrivateKey), crypto.SHA1, hash)
case SHA256:
h := sha256.New()
h.Write([]byte(message))
hash := h.Sum(nil)
signature, err = rsa.SignPKCS1v15(rand.Reader, priKey.(*rsa.PrivateKey), crypto.SHA256, hash)
case SHA512:
h := sha512.New()
h.Write([]byte(message))
hash := h.Sum(nil)
signature, err = rsa.SignPKCS1v15(rand.Reader, priKey.(*rsa.PrivateKey), crypto.SHA512, hash)
default:
return "", errors.New("不支持的签名类型")
}
if err != nil {
return "", err
}
return EncryptBASE64(signature), nil
}
// RSA公钥验签
func VerifyRSA(message, publicKey, sign string, signType SignType) error {
signBytes, err := DecryptBASE64(sign)
if err != nil {
return err
}
key, err := DecryptBASE64(publicKey)
if err != nil {
return err
}
pubKey, err := x509.ParsePKIXPublicKey(key)
if err != nil {
return err
}
switch signType {
case MD5:
h := md5.New()
h.Write([]byte(message))
hash := h.Sum(nil)
err = rsa.VerifyPKCS1v15(pubKey.(*rsa.PublicKey), crypto.MD5, hash, signBytes)
case SHA1:
h := sha1.New()
h.Write([]byte(message))
hash := h.Sum(nil)
err = rsa.VerifyPKCS1v15(pubKey.(*rsa.PublicKey), crypto.SHA1, hash, signBytes)
case SHA256:
h := sha256.New()
h.Write([]byte(message))
hash := h.Sum(nil)
err = rsa.VerifyPKCS1v15(pubKey.(*rsa.PublicKey), crypto.SHA256, hash, signBytes)
case SHA512:
h := sha512.New()
h.Write([]byte(message))
hash := h.Sum(nil)
err = rsa.VerifyPKCS1v15(pubKey.(*rsa.PublicKey), crypto.SHA512, hash, signBytes)
default:
return errors.New("不支持的签名类型")
}
if err != nil {
return err
}
return nil
}
// bcrypt 加密
func Bcrypt(plainPwd string) (hashedPwd string, err error) {
pwd := []byte(plainPwd)
hash, err := bcrypt.GenerateFromPassword(pwd, bcrypt.MinCost)
if err != nil {
return
}
hashedPwd = string(hash)
return
}
// bcrypt 验证密码
func BcryptCompare(hashedPwd string, plainPwd string) bool {
byteHash := []byte(hashedPwd)
bytePwd := []byte(plainPwd)
err := bcrypt.CompareHashAndPassword(byteHash, bytePwd)
if err != nil {
return false
}
return true
}
func EncryptAESECBPKCS5(data []byte, key []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
// 加密
ecrypt := NewECBEncrypter(block)
src := PKCS5Padding(data, ecrypt.BlockSize())
out := make([]byte, len(src))
ecrypt.CryptBlocks(out, src)
return out, nil
}
func DecryptAESECBPKCS5(data []byte, key []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
ecb := NewECBDecrypter(block)
out := make([]byte, len(data))
ecb.CryptBlocks(out, data)
return PKCS5UnPadding(out), nil
}
func PKCS5Padding(ciphertext []byte, blockSize int) []byte {
padding := blockSize - len(ciphertext)%blockSize
padtext := bytes.Repeat([]byte{byte(padding)}, padding)
return append(ciphertext, padtext...)
}
func PKCS5UnPadding(origData []byte) []byte {
length := len(origData)
unpadding := int(origData[length-1])
return origData[:(length - unpadding)]
}
type ecb struct {
b cipher.Block
blockSize int
}
func newECB(b cipher.Block) *ecb {
return &ecb{
b: b,
blockSize: b.BlockSize(),
}
}
type ecbEncrypter ecb
// NewECBEncrypter returns a BlockMode which encrypts in electronic code book
// mode, using the given Block.
func NewECBEncrypter(b cipher.Block) cipher.BlockMode {
return (*ecbEncrypter)(newECB(b))
}
func (x *ecbEncrypter) BlockSize() int { return x.blockSize }
func (x *ecbEncrypter) CryptBlocks(dst, src []byte) {
if len(src)%x.blockSize != 0 {
panic("crypto/cipher: input not full blocks")
}
if len(dst) < len(src) {
panic("crypto/cipher: output smaller than input")
}
for len(src) > 0 {
x.b.Encrypt(dst, src[:x.blockSize])
src = src[x.blockSize:]
dst = dst[x.blockSize:]
}
}
type ecbDecrypter ecb
// NewECBDecrypter returns a BlockMode which decrypts in electronic code book
// mode, using the given Block.
func NewECBDecrypter(b cipher.Block) cipher.BlockMode {
return (*ecbDecrypter)(newECB(b))
}
func (x *ecbDecrypter) BlockSize() int { return x.blockSize }
func (x *ecbDecrypter) CryptBlocks(dst, src []byte) {
if len(src)%x.blockSize != 0 {
panic("crypto/cipher: input not full blocks")
}
if len(dst) < len(src) {
panic("crypto/cipher: output smaller than input")
}
for len(src) > 0 {
x.b.Decrypt(dst, src[:x.blockSize])
src = src[x.blockSize:]
dst = dst[x.blockSize:]
}
}