1 Star 0 Fork 0

carlmax_my/console-core-go

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
aes.go 1.90 KB
一键复制 编辑 原始数据 按行查看 历史
carlmax_my 提交于 2024-12-02 21:32 . init project
package aes
import (
"bytes"
cryptoAes "crypto/aes"
"crypto/cipher"
"gitee.com/carlmax_my/console-core-go/pkg/crypto/base64"
)
var _ Aes = (*aes)(nil)
type Aes interface {
i()
// Encrypt
Encrypt(encryptStr string) (string, error)
// Decrypt
Decrypt(decryptStr string) (string, error)
}
type aes struct {
key string //
iv string //
url bool // base64 url safe format, replace (+/)->(-_), default is true
}
func New(key, iv string) Aes {
return &aes{
key: key,
iv: iv,
url: true,
}
}
func NewWithUrl(key, iv string, url bool) Aes {
return &aes{
key: key,
iv: iv,
url: url,
}
}
func (a *aes) i() {}
func (a *aes) Encrypt(encryptStr string) (string, error) {
encryptBytes := []byte(encryptStr)
block, err := cryptoAes.NewCipher([]byte(a.key))
if err != nil {
return "", err
}
blockSize := block.BlockSize()
encryptBytes = pkcs5Padding(encryptBytes, blockSize)
blockMode := cipher.NewCBCEncrypter(block, []byte(a.iv))
encrypted := make([]byte, len(encryptBytes))
blockMode.CryptBlocks(encrypted, encryptBytes)
return base64.New(a.url).Encode(encrypted), nil
}
func (a *aes) Decrypt(decryptStr string) (string, error) {
decryptBytes, err := base64.New(a.url).Decode(decryptStr)
if err != nil {
return "", err
}
block, err := cryptoAes.NewCipher([]byte(a.key))
if err != nil {
return "", err
}
blockMode := cipher.NewCBCDecrypter(block, []byte(a.iv))
decrypted := make([]byte, len(decryptBytes))
blockMode.CryptBlocks(decrypted, decryptBytes)
decrypted = pkcs5UnPadding(decrypted)
return string(decrypted), nil
}
func pkcs5Padding(cipherText []byte, blockSize int) []byte {
padding := blockSize - len(cipherText)%blockSize
padText := bytes.Repeat([]byte{byte(padding)}, padding)
return append(cipherText, padText...)
}
func pkcs5UnPadding(decrypted []byte) []byte {
length := len(decrypted)
unPadding := int(decrypted[length-1])
return decrypted[:(length - unPadding)]
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/carlmax_my/console-core-go.git
git@gitee.com:carlmax_my/console-core-go.git
carlmax_my
console-core-go
console-core-go
v0.0.13

搜索帮助

0d507c66 1850385 C8b1a773 1850385