1 Star 0 Fork 0

tech4good/common

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
aes.go 1.27 KB
一键复制 编辑 原始数据 按行查看 历史
v_chaoni 提交于 2022-04-02 14:57 +08:00 . --other=merge
package utils
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"encoding/hex"
"github.com/spf13/viper"
)
//支持16、24、32bytes的密钥
//aes加密,输入string格式的明文,返回hex string格式的密文
func AesCtrEncrypt(plaintext string) (string, error) {
key := []byte(viper.GetString("aes.key"))
msg := []byte(plaintext)
// 创建aes密码接口
block, err := aes.NewCipher(key)
if err != nil {
return "", err
}
// 创建分组模式ctr
iv := bytes.Repeat([]byte("1"), block.BlockSize())
stream := cipher.NewCTR(block, iv)
// 加密
dst := make([]byte, len(msg))
stream.XORKeyStream(dst, msg)
//返回hex string格式的密文
return hex.EncodeToString(dst), nil
}
//aes解密,输入hex string格式的密文,返回string格式的明文
func AesCtrDecrypt(ciphertext string) (string, error) {
key := []byte(viper.GetString("aes.key"))
msg, err := hex.DecodeString(ciphertext)
if err != nil {
return "", err
}
// 创建aes密码接口
block, err := aes.NewCipher(key)
if err != nil {
return "", err
}
// 创建分组模式ctr
iv := bytes.Repeat([]byte("1"), block.BlockSize())
stream := cipher.NewCTR(block, iv)
// 解密
dst := make([]byte, len(msg))
stream.XORKeyStream(dst, msg)
//返回string格式的密文
return string(dst), nil
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/tech4good/common.git
git@gitee.com:tech4good/common.git
tech4good
common
common
v1.0.2

搜索帮助