工具代码
package tool
import (
"bytes"
"crypto/aes"
"crypto/cipher"
)
var key []byte = []byte("0@#3456789ABCDEF")
func Encrypt(data []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
paddingLen := aes.BlockSize - (len(data) % aes.BlockSize)
paddedData := append(data, bytes.Repeat([]byte{byte(paddingLen)}, paddingLen)...)
encrypted := make([]byte, len(paddedData))
iv := make([]byte, aes.BlockSize)
mode := cipher.NewCBCEncrypter(block, iv)
mode.CryptBlocks(encrypted, paddedData)
return encrypted, nil
}
func Decrypt(encryptedData []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
decrypted := make([]byte, len(encryptedData))
iv := make([]byte, aes.BlockSize)
mode := cipher.NewCBCDecrypter(block, iv)
mode.CryptBlocks(decrypted, encryptedData)
paddingLen := int(decrypted[len(decrypted)-1])
decrypted = decrypted[:len(decrypted)-paddingLen]
return decrypted, nil
}
func CalculateEncryptedLength(dataLen int) int {
paddingLen := aes.BlockSize - (dataLen % aes.BlockSize)
encryptedLen := dataLen + paddingLen
return encryptedLen
}
测试类
package test
import (
"beego_test/tool"
"testing"
)
func Test_encryption(t *testing.T) {
originalBytes := []byte{115, 91, 212, 128, 220, 50, 0, 247, 207, 91, 178, 183, 207, 59, 115, 91}
encryptedBytes, err := tool.Encrypt(originalBytes)
if err != nil {
log.Fatal(err)
}
d, err := tool.Decrypt(encryptedBytes)
fmt.Println("原始的字节为", originalBytes)
fmt.Println("加密后的字节为", encryptedBytes)
fmt.Println("加密后的字节的长度为", len(encryptedBytes))
fmt.Println("字节49加密后的长度", tool.CalculateEncryptedLength(49))
fmt.Println("解密后的字节为", d)
fmt.Println("无法根据密文长度推出原文长度")
fmt.Println("可以根据密文退出原文")
fmt.Println("可以根据原文长度推出密文长度")
fmt.Println("如果字节无法解密会报错")
tool.Decrypt(originalBytes)
}