-
Notifications
You must be signed in to change notification settings - Fork 2
/
crypto_strategy_aes.go
48 lines (40 loc) · 1.05 KB
/
crypto_strategy_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
package strategy
import (
"encoding/base64"
"github.com/duke-git/lancet/v2/cryptor"
"gorm.io/gorm"
"gorm.io/gorm/schema"
"strings"
)
type AesCryptoStrategy struct {
secretKey string
}
func NewAesCryptoStrategy(secretKey string) *AesCryptoStrategy {
return &AesCryptoStrategy{secretKey: secretKey}
}
func (d *AesCryptoStrategy) Name() string {
return "AES"
}
func (d *AesCryptoStrategy) Encrypt(src string, field *schema.Field, db *gorm.DB) string {
if len(src) == 0 {
return ""
}
return EncryptValue(src, d.secretKey)
}
func (d *AesCryptoStrategy) Decrypt(src string, field *schema.Field, db *gorm.DB) string {
if len(src) == 0 {
return ""
}
return DecryptValue(src, d.secretKey)
}
func EncryptValue(str, key string) string {
return "{AES}" + base64.StdEncoding.EncodeToString(cryptor.AesEcbEncrypt([]byte(str), []byte(key)))
}
func DecryptValue(str, key string) string {
if strings.HasPrefix(str, "{AES}") {
rs, _ := base64.StdEncoding.DecodeString(str[5:])
v := cryptor.AesEcbDecrypt(rs, []byte(key))
return string(v)
}
return str
}