feat: crypto

This commit is contained in:
Bobo
2025-05-07 15:57:19 +08:00
parent 0420e35a30
commit 78cef077e5
3 changed files with 20 additions and 8 deletions

View File

@@ -40,23 +40,29 @@ func PKCS5UnPadding(origData []byte) []byte {
} }
// AesEncrypt AES加密 // AesEncrypt AES加密
func AesEncrypt(origData, key []byte) ([]byte, error) { func AesEncrypt(origData, key []byte, iv []byte) ([]byte, error) {
block, err := aes.NewCipher(key) block, err := aes.NewCipher(key)
if err != nil { if err != nil {
return nil, err return nil, err
} }
//AES分组长度为128位所以blockSize=16单位字节 // AES分组长度为128位所以blockSize=16单位字节
blockSize := block.BlockSize() blockSize := block.BlockSize()
if iv == nil {
// 初始向量的长度必须等于块block的长度16字节
iv = key[:blockSize]
}
origData = PKCS5Padding(origData, blockSize) origData = PKCS5Padding(origData, blockSize)
blockMode := cipher.NewCBCEncrypter(block, key[:blockSize]) //初始向量的长度必须等于块block的长度16字节 blockMode := cipher.NewCBCEncrypter(block, iv)
crypted := make([]byte, len(origData)) crypted := make([]byte, len(origData))
blockMode.CryptBlocks(crypted, origData) blockMode.CryptBlocks(crypted, origData)
return crypted, nil return crypted, nil
} }
// AesDecrypt AES解密 // AesDecrypt AES解密
func AesDecrypt(crypted, key []byte) ([]byte, error) { func AesDecrypt(crypted, key []byte, iv []byte) ([]byte, error) {
block, err := aes.NewCipher(key) block, err := aes.NewCipher(key)
if err != nil { if err != nil {
return nil, err return nil, err
@@ -64,7 +70,13 @@ func AesDecrypt(crypted, key []byte) ([]byte, error) {
//AES分组长度为128位所以blockSize=16单位字节 //AES分组长度为128位所以blockSize=16单位字节
blockSize := block.BlockSize() blockSize := block.BlockSize()
blockMode := cipher.NewCBCDecrypter(block, key[:blockSize]) //初始向量的长度必须等于块block的长度16字节
if iv == nil {
// 初始向量的长度必须等于块block的长度16字节
iv = key[:blockSize]
}
blockMode := cipher.NewCBCDecrypter(block, iv)
origData := make([]byte, len(crypted)) origData := make([]byte, len(crypted))
blockMode.CryptBlocks(origData, crypted) blockMode.CryptBlocks(origData, crypted)
origData = PKCS5UnPadding(origData) origData = PKCS5UnPadding(origData)

View File

@@ -15,7 +15,7 @@ func TestDecryptAES(t *testing.T) {
aesKey = DefaultAESKey aesKey = DefaultAESKey
plainText := []byte("cloud123456") plainText := []byte("cloud123456")
encryptText, err := AesEncrypt(plainText, aesKey) encryptText, err := AesEncrypt(plainText, aesKey, nil)
if err != nil { if err != nil {
fmt.Println(err) fmt.Println(err)
return return
@@ -30,7 +30,7 @@ func TestDecryptAES(t *testing.T) {
return return
} }
decryptText, err := AesDecrypt(bytesPass, aesKey) decryptText, err := AesDecrypt(bytesPass, aesKey, nil)
if err != nil { if err != nil {
fmt.Println(err) fmt.Println(err)
return return

View File

@@ -1,4 +1,4 @@
git tag v1.1.18 git tag v1.1.19
git tag bank_card/v1.1.5 git tag bank_card/v1.1.5
git tag geoip/v1.1.5 git tag geoip/v1.1.5