feat: 加密工具AES-CBC,配合前端CryptoJS加解密
This commit is contained in:
@@ -10,12 +10,12 @@ import (
|
||||
"io"
|
||||
)
|
||||
|
||||
// StringEncryptByAES 字符串AES加密
|
||||
func StringEncryptByAES(text string) (string, error) {
|
||||
// AESEncryptBase64 AES加密转Base64字符串
|
||||
func AESEncryptBase64(text, key string) (string, error) {
|
||||
if len(text) == 0 {
|
||||
return "", nil
|
||||
}
|
||||
xpass, err := aesEncryptWithSalt([]byte(text))
|
||||
xpass, err := AESEncrypt([]byte(text), []byte(key))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
@@ -23,8 +23,8 @@ func StringEncryptByAES(text string) (string, error) {
|
||||
return pass64, nil
|
||||
}
|
||||
|
||||
// StringDecryptByAES 字符串AES解密
|
||||
func StringDecryptByAES(text string) (string, error) {
|
||||
// AESDecryptBase64 AES解密解Base64字符串
|
||||
func AESDecryptBase64(text, key string) (string, error) {
|
||||
if len(text) == 0 {
|
||||
return "", nil
|
||||
}
|
||||
@@ -32,21 +32,16 @@ func StringDecryptByAES(text string) (string, error) {
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
tpass, err := aesDecryptWithSalt(bytesPass)
|
||||
tpass, err := AESDecrypt(bytesPass, []byte(key))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return string(tpass), nil
|
||||
}
|
||||
|
||||
// aesKey 字符串AES加解密密钥
|
||||
const aesKey = "AGT66VfY4SMaiT97a7df0aef1704d5c5"
|
||||
|
||||
// const aesKey = "AGT66VfY4SMaiT97"
|
||||
// aesEncryptWithSalt AES加密
|
||||
func aesEncryptWithSalt(plaintext []byte) ([]byte, error) {
|
||||
block, err := aes.NewCipher([]byte(aesKey))
|
||||
// AESEncrypt AES加密
|
||||
func AESEncrypt(plaintext, aeskey []byte) ([]byte, error) {
|
||||
block, err := aes.NewCipher(aeskey)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -68,8 +63,8 @@ func aesEncryptWithSalt(plaintext []byte) ([]byte, error) {
|
||||
return ciphertext, nil
|
||||
}
|
||||
|
||||
// aesDecryptWithSalt AES解密
|
||||
func aesDecryptWithSalt(ciphertext []byte) ([]byte, error) {
|
||||
// AESDecrypt AES解密
|
||||
func AESDecrypt(ciphertext, aeskey []byte) ([]byte, error) {
|
||||
blockSize := aes.BlockSize
|
||||
if len(ciphertext) < blockSize {
|
||||
return nil, fmt.Errorf("ciphertext too short")
|
||||
@@ -77,12 +72,14 @@ func aesDecryptWithSalt(ciphertext []byte) ([]byte, error) {
|
||||
|
||||
iv := ciphertext[:blockSize]
|
||||
ciphertext = ciphertext[blockSize:]
|
||||
block, err := aes.NewCipher([]byte(aeskey))
|
||||
|
||||
block, err := aes.NewCipher([]byte(aesKey))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if len(ciphertext) == 0 {
|
||||
return nil, fmt.Errorf("ciphertext is invalid")
|
||||
}
|
||||
if len(ciphertext)%blockSize != 0 {
|
||||
return nil, fmt.Errorf("ciphertext is not a multiple of the block size")
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user