golang aes

package uilts

import (
"bytes"
"crypto/aes"
"crypto/cipher"
"encoding/base64"
"fmt"
"strconv"
"strings"
)

const (
sKey = "chexiongdisdwa11"
ivParameter = "1234567890123411"
)

func PswEncrypt(src string) string {
key := []byte(sKey)
iv := []byte(ivParameter)

result, err := Aes128Encrypt([]byte(src), key, iv)
if err != nil {
return err.Error()
}
return base64.RawStdEncoding.EncodeToString(result)
}
func PswDecrypt(src string) (string, error) {

key := []byte(sKey)
iv := []byte(ivParameter)

var result []byte
var err error
src = strings.Replace(src, " ", "", -1)
result, err = base64.StdEncoding.DecodeString(src)
if err != nil {
return "", err
}
origData, err := Aes128Decrypt(result, key, iv)
if err != nil {
return "", err
}
var res = []string{""}
sUnicode := strings.Split(string(origData), "\\u")
var context = ""
for _, v := range sUnicode {
var additional = ""
if len(v) < 1 {
continue
}
if len(v) > 4 {
rs := []rune(v)
v = string(rs[:4])
additional = string(rs[4:])
}
temp, err := strconv.ParseInt(v, 16, 32)
if err != nil {
context += v
}
context += fmt.Sprintf("%c", temp)
context += additional
}
res = append(res, context)

s := strings.Join(res, "")
str := make([]rune, 0, len(s))
for _, v := range []rune(s) {
if v == 0 {
continue
}
str = append(str, v)
}
return string(str), nil

}
func Aes128Encrypt(origData, key []byte, IV []byte) ([]byte, error) {
if key == nil || len(key) != 16 {
return nil, nil
}
if IV != nil && len(IV) != 16 {
return nil, nil
}

block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
blockSize := block.BlockSize()
origData = PKCS5Padding(origData, blockSize)
blockMode := cipher.NewCBCEncrypter(block, IV[:blockSize])
crypted := make([]byte, len(origData))
// 根据CryptBlocks方法的说明,如下方式初始化crypted也可以
blockMode.CryptBlocks(crypted, origData)
return crypted, nil
}

func Aes128Decrypt(crypted, key []byte, IV []byte) ([]byte, error) {
if key == nil || len(key) != 16 {
return nil, nil
}
if IV != nil && len(IV) != 16 {
return nil, nil
}

block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
blockSize := block.BlockSize()
blockMode := cipher.NewCBCDecrypter(block, IV[:blockSize])
origData := make([]byte, len(crypted))
blockMode.CryptBlocks(origData, crypted)
origData = PKCS5UnPadding(origData)
return origData, 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(origData []byte) []byte {
length := len(origData)
// 去掉最后一个字节 unpadding 次
unpadding := int(origData[length-1])
return origData[:(length - unpadding)]
}

//func main(){
// encodingString := PswEncrypt("123")
// decodingString := PswDecrypt(encodingString);
// fmt.Printf("AES-128-CBC\n加密:%s\n解密:%s\n",encodingString,decodingString)
//}
posted @ 2022-02-28 15:21  酷酷的城池  阅读(160)  评论(0编辑  收藏  举报