-
Notifications
You must be signed in to change notification settings - Fork 1
/
encrypt_aes.go
84 lines (72 loc) · 1.69 KB
/
encrypt_aes.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
package xorm
import (
"crypto/aes"
"crypto/cipher"
"encoding/base64"
)
const (
tempkey = "1234567890!@#$%^&*()_+-="
)
type AesEncrypt struct {
PubKey string
}
func (this *AesEncrypt) getKey() []byte {
strKey := this.PubKey
keyLen := len(strKey)
if keyLen < 16 {
rs := []rune(tempkey)
strKey = strKey + string(rs[0:16-keyLen])
}
if keyLen > 16 && keyLen < 24 {
rs := []rune(tempkey)
strKey = strKey + string(rs[0:24-keyLen])
}
if keyLen > 24 && keyLen < 32 {
rs := []rune(tempkey)
strKey = strKey + string(rs[0:32-keyLen])
}
arrKey := []byte(strKey)
if keyLen >= 32 {
return arrKey[:32]
}
if keyLen >= 24 {
return arrKey[:24]
}
return arrKey[:16]
}
//加密字符串
func (this *AesEncrypt) Encrypt(strMesg string) ([]byte, error) {
key := this.getKey()
var iv = []byte(key)[:aes.BlockSize]
encrypted := make([]byte, len(strMesg))
aesBlockEncrypter, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
aesEncrypter := cipher.NewCFBEncrypter(aesBlockEncrypter, iv)
aesEncrypter.XORKeyStream(encrypted, []byte(strMesg))
return encrypted, nil
}
//解密字符串
func (this *AesEncrypt) Decrypt(src []byte) (decrypted []byte, err error) {
defer func() {
if e := recover(); e != nil {
err = e.(error)
}
}()
src, err = base64.StdEncoding.DecodeString(string(src))
if err != nil {
return nil, err
}
key := this.getKey()
var iv = []byte(key)[:aes.BlockSize]
decrypted = make([]byte, len(src))
var aesBlockDecrypter cipher.Block
aesBlockDecrypter, err = aes.NewCipher([]byte(key))
if err != nil {
return nil, err
}
aesDecrypter := cipher.NewCFBDecrypter(aesBlockDecrypter, iv)
aesDecrypter.XORKeyStream(decrypted, src)
return decrypted, nil
}