enhance(spiral):螺旋加密算法增加兼容旧式设计算法功能。
This commit is contained in:
parent
1f99378655
commit
811e056bb8
@ -13,6 +13,13 @@ import (
|
||||
"archgrid.xyz/ag/toolsbox/serialize/base64"
|
||||
)
|
||||
|
||||
type Strength int
|
||||
|
||||
const (
|
||||
Compatible Strength = iota
|
||||
Enhanced
|
||||
)
|
||||
|
||||
// 根据给定的密钥字符串生成加解密使用的密钥。
|
||||
func generateKey(key string) []byte {
|
||||
keyBytes := sha512.Sha512([]byte(key))
|
||||
@ -20,10 +27,16 @@ func generateKey(key string) []byte {
|
||||
}
|
||||
|
||||
// 对给定的数据进行加密。
|
||||
func Encrypt(data string) (string, error) {
|
||||
func Encrypt(data string, strength ...Strength) (string, error) {
|
||||
var ivGen aes.IVGenerator
|
||||
if append(strength, Compatible)[0] == Compatible {
|
||||
ivGen = aes.PrefixIVGenerator
|
||||
} else {
|
||||
ivGen = aes.XorIVGenerator
|
||||
}
|
||||
key := verifyCode.RandStr(20)
|
||||
keyBytes := generateKey(key)
|
||||
cipherData, err := aes.Encrypt([]byte(data), keyBytes, encryption.PKCS7Padding)
|
||||
cipherData, err := aes.Encrypt([]byte(data), keyBytes, encryption.PKCS7Padding, ivGen)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("加密计算失败,%w", err)
|
||||
}
|
||||
@ -35,7 +48,13 @@ func Encrypt(data string) (string, error) {
|
||||
}
|
||||
|
||||
// 对给定的数据进行解密。
|
||||
func Decrypt(data string) (string, error) {
|
||||
func Decrypt(data string, strength ...Strength) (string, error) {
|
||||
var ivGen aes.IVGenerator
|
||||
if append(strength, Compatible)[0] == Compatible {
|
||||
ivGen = aes.PrefixIVGenerator
|
||||
} else {
|
||||
ivGen = aes.XorIVGenerator
|
||||
}
|
||||
if message, found := strings.CutPrefix(data, "["); found {
|
||||
if len(message) > 20 {
|
||||
keySeed := message[:20]
|
||||
@ -44,7 +63,7 @@ func Decrypt(data string) (string, error) {
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("密文损坏无法解析,%w", err)
|
||||
}
|
||||
plainText, err := aes.Decrypt(cipherData, key, encryption.PKCS7Padding)
|
||||
plainText, err := aes.Decrypt(cipherData, key, encryption.PKCS7Padding, ivGen)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("密文解密计算失败,%w", err)
|
||||
}
|
||||
|
Loading…
x
Reference in New Issue
Block a user