Ai
1 Star 0 Fork 0

zhuim/zmf

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
index.go 2.37 KB
一键复制 编辑 原始数据 按行查看 历史
zmf 提交于 2023-02-25 03:13 +08:00 . zmf
package auth
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"encoding/base64"
"errors"
"fmt"
"github.com/cloudwego/hertz/pkg/common/json"
"github.com/spf13/viper"
)
type H struct {
User_id string
Time int64
Role_id string
}
var mKey = ""
// pkcs7Padding 填充
func pkcs7Padding(data []byte, blockSize int) []byte {
//判断缺少几位长度。最少1,最多 blockSize
padding := blockSize - len(data)%blockSize
//补足位数。把切片[]byte{byte(padding)}复制padding个
padText := bytes.Repeat([]byte{byte(padding)}, padding)
return append(data, padText...)
}
func pkcs7UnPadding(data []byte) ([]byte, error) {
length := len(data)
if length == 0 {
return nil, errors.New("error!")
}
unPadding := int(data[length-1])
if unPadding >= length {
return nil, errors.New("error!")
}
return data[:(length - unPadding)], nil
}
func aesEncrypt(data []byte, key []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, errors.New("key error")
}
blockSize := block.BlockSize()
encryptBytes := pkcs7Padding(data, blockSize)
crypted := make([]byte, len(encryptBytes))
blockMode := cipher.NewCBCEncrypter(block, key[:blockSize])
blockMode.CryptBlocks(crypted, encryptBytes)
return crypted, nil
}
func aesDecrypt(data []byte, key []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
blockSize := block.BlockSize()
blockMode := cipher.NewCBCDecrypter(block, key[:blockSize])
crypted := make([]byte, len(data))
blockMode.CryptBlocks(crypted, data)
crypted, err = pkcs7UnPadding(crypted)
if err != nil {
return nil, err
}
return crypted, nil
}
func EncryptByAes(data H) (string, error) {
sdat, err := json.Marshal(data)
if err != nil {
return "", err
}
res, err := aesEncrypt(sdat, []byte(mKey))
if err != nil {
return "", err
}
return base64.StdEncoding.EncodeToString(res), nil
}
func DecryptByAes(data string) (*H, error) {
dataByte, err := base64.StdEncoding.DecodeString(data)
if err != nil {
return nil, err
}
dat, err := aesDecrypt(dataByte, []byte(mKey))
if err != nil {
return nil, err
}
var ret = new(H)
err = json.Unmarshal(dat, ret)
if err != nil {
return nil, err
}
return ret, nil
}
func init() {
viper.SetConfigFile("./config.json")
err := viper.ReadInConfig()
if err != nil {
fmt.Println(err)
return
}
mKey = viper.GetString("authKey")
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/phpvipzm/zmf.git
git@gitee.com:phpvipzm/zmf.git
phpvipzm
zmf
zmf
v0.3.1

搜索帮助