From 811e056bb8adc4b40d92fd91b17f53193f45d465 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=BE=90=E6=B6=9B?= Date: Tue, 18 Jul 2023 16:07:35 +0800 Subject: [PATCH] =?UTF-8?q?enhance(spiral):=E8=9E=BA=E6=97=8B=E5=8A=A0?= =?UTF-8?q?=E5=AF=86=E7=AE=97=E6=B3=95=E5=A2=9E=E5=8A=A0=E5=85=BC=E5=AE=B9?= =?UTF-8?q?=E6=97=A7=E5=BC=8F=E8=AE=BE=E8=AE=A1=E7=AE=97=E6=B3=95=E5=8A=9F?= =?UTF-8?q?=E8=83=BD=E3=80=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- encryption/spiral/spiral.go | 27 +++++++++++++++++++++++---- 1 file changed, 23 insertions(+), 4 deletions(-) diff --git a/encryption/spiral/spiral.go b/encryption/spiral/spiral.go index 0617ebd..3e090e1 100644 --- a/encryption/spiral/spiral.go +++ b/encryption/spiral/spiral.go @@ -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) }