feat: crypto

This commit is contained in:
Bobo
2025-05-07 14:42:12 +08:00
parent 7b29f09e37
commit 0b18560901
5 changed files with 14 additions and 53 deletions

View File

@@ -6,8 +6,7 @@ import (
"crypto/aes"
"crypto/cipher"
"math/rand/v2"
"crypto/rand"
)
// DefaultAESKey 默认AES密钥(16字节)
@@ -19,8 +18,7 @@ func GenerateAESKey(length int) ([]byte, error) {
return nil, fmt.Errorf("invalid key length: %d, must be 16, 24, or 32 bytes", length)
}
key := make([]byte, length)
src := rand.ChaCha8{}
_, err := src.Read(key)
_, err := rand.Read(key)
if err != nil {
return nil, err
}

View File

@@ -1,14 +1,9 @@
package crypto
import (
"fmt"
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"golang.org/x/crypto/bcrypt"
@@ -59,44 +54,3 @@ func GenerateSalt(length int) (string, error) {
}
return hex.EncodeToString(salt), nil
}
// DecryptAES AES解密函数
func DecryptAES(cipherText, key string) (string, error) {
// 将密文从Base64解码
cipherData, err := base64.StdEncoding.DecodeString(cipherText)
if err != nil {
return "", err
}
// 创建AES块
block, err := aes.NewCipher([]byte(key))
if err != nil {
return "", err
}
// 检查密文长度是否为块大小的倍数
if len(cipherData)%aes.BlockSize != 0 {
return "", fmt.Errorf("ciphertext is not a multiple of the block size")
}
// 创建CBC解密器
iv := cipherData[:aes.BlockSize] // 提取IV
cipherData = cipherData[aes.BlockSize:]
mode := cipher.NewCBCDecrypter(block, iv)
// 解密
plainText := make([]byte, len(cipherData))
mode.CryptBlocks(plainText, cipherData)
// 去除填充
plainText = pkcs7Unpad(plainText)
return string(plainText), nil
}
// pkcs7Unpad PKCS7填充去除
func pkcs7Unpad(data []byte) []byte {
length := len(data)
padding := int(data[length-1])
return data[:length-padding]
}

View File

@@ -26,6 +26,15 @@ func TestVerifyPassword(t *testing.T) {
assert.True(t, bMatched)
}
func TestVerifyPasswordWithSalt_CorrectPassword(t *testing.T) {
password := "securePassword"
salt, _ := GenerateSalt(16)
hashedPassword, _ := HashPasswordWithSalt(password, salt)
result := VerifyPasswordWithSalt(password, salt, hashedPassword)
assert.True(t, result, "Password verification should succeed with correct password and salt")
}
func TestJwtToken(t *testing.T) {
const bearerWord string = "Bearer"
token := "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjowfQ.XgcKAAjHbA6o4sxxbEaMi05ingWvKdCNnyW9wowbJvs"

View File

@@ -11,7 +11,7 @@ require (
github.com/go-kratos/kratos/v2 v2.8.4
github.com/google/uuid v1.6.0
github.com/stretchr/testify v1.10.0
github.com/tx7do/go-utils v1.1.16
github.com/tx7do/go-utils v1.1.17
go.opentelemetry.io/otel v1.35.0
google.golang.org/protobuf v1.36.6
)

View File

@@ -1,9 +1,9 @@
git tag v1.1.17
git tag v1.1.18
git tag bank_card/v1.1.5
git tag geoip/v1.1.5
git tag entgo/v1.1.26
git tag entgo/v1.1.27
git tag gorm/v1.1.5
git push origin --tags