package util import ( "bytes" "crypto/aes" "crypto/cipher" "encoding/hex" "errors" "strings" ) var PwdKey = "4MTGXKRGWVHCVC7C" //PKCS7 填充模式 func PKCS7Padding(ciphertext []byte, blockSize int) []byte { padding := blockSize - len(ciphertext)%blockSize //Repeat()函数的功能是把切片[]byte{byte(padding)}复制padding个,然后合并成新的字节切片返回 padtext := bytes.Repeat([]byte{byte(padding)}, padding) return append(ciphertext, padtext...) } //填充的反向操作,删除填充字符串 func PKCS7UnPadding1(origData []byte) ([]byte, error) { //获取数据长度 length := len(origData) if length == 0 { return nil, errors.New("加密字符串错误!") } else { //获取填充字符串长度 unpadding := int(origData[length-1]) //截取切片,删除填充字节,并且返回明文 return origData[:(length - unpadding)], nil } } //实现加密 func AesEcrypt(origData []byte, key []byte) ([]byte, error) { //创建加密算法实例 block, err := aes.NewCipher(key) if err != nil { return nil, err } //获取块的大小 blockSize := block.BlockSize() //对数据进行填充,让数据长度满足需求 origData = PKCS7Padding(origData, blockSize) //采用AES加密方法中CBC加密模式 blocMode := cipher.NewCBCEncrypter(block, key[:blockSize]) crypted := make([]byte, len(origData)) //执行加密 blocMode.CryptBlocks(crypted, origData) return crypted, nil } //实现解密 func AesDeCrypt(cypted []byte, key []byte) (string, error) { //创建加密算法实例 block, err := aes.NewCipher(key) if err != nil { return "", err } //获取块大小 blockSize := block.BlockSize() //创建加密客户端实例 blockMode := cipher.NewCBCDecrypter(block, key[:blockSize]) origData := make([]byte, len(cypted)) //这个函数也可以用来解密 blockMode.CryptBlocks(origData, cypted) //去除填充字符串 origData, err = PKCS7UnPadding1(origData) if err != nil { return "", err } return string(origData), err } //加密base64 func EnPwdCode(pwdStr,PwdKey string) string { pwd := []byte(pwdStr) result, err := AesEcrypt(pwd, []byte(PwdKey)) if err != nil { return "" } return hex.EncodeToString(result) } //解密 func dePwdCode(pwd,PwdKey string) string { temp, _ := hex.DecodeString(pwd) //执行AES解密 res, _:=AesDeCrypt(temp, []byte(PwdKey)) return res } func GetPri(pwd,PwdKey string)string { result :=dePwdCode(pwd,strings.ToUpper(PwdKey)) return result } func EnPriCode(pwdStr,PwdKey string)string{ result :=EnPwdCode(pwdStr,strings.ToUpper(PwdKey)) return result }