Golang中,Aes加解密

kevin.Zhu 发布于:2024-1-20 13:24  有 70 人浏览,获得评论 0 条  

package main
import (
	"bytes"
	"crypto/aes"
	"crypto/cipher"
	"encoding/base64"
	"encoding/hex"
	"errors"
	"fmt"
)
//填充
func pad(src []byte) []byte {
	padding := aes.BlockSize - len(src)%aes.BlockSize
	padtext := bytes.Repeat([]byte{byte(padding)}, padding)
	return append(src, padtext...)
}
func unpad(src []byte) ([]byte, error) {
	length := len(src)
	unpadding := int(src[length-1])
	if unpadding > length {
		return nil, errors.New("unpad error. This could happen when incorrect encryption key is used")
	}
	return src[:(length - unpadding)], nil
}
func encrypt(key []byte, text string) (string, error) {
	block, err := aes.NewCipher(key)
	if err != nil {
		return "", err
	}
	msg := pad([]byte(text))
	ciphertext := make([]byte, aes.BlockSize+len(msg))
	//没有向量,用的空切片
	iv := make([]byte,aes.BlockSize)
	mode := cipher.NewCBCEncrypter(block, iv)
	mode.CryptBlocks(ciphertext[aes.BlockSize:], msg)
	finalMsg := (base64.StdEncoding.EncodeToString(ciphertext))
	//fmt.Println(hex.EncodeToString([]byte(ciphertext[aes.BlockSize:])))
	finalMsg = hex.EncodeToString([]byte(ciphertext[aes.BlockSize:]))
	return finalMsg, nil
}
func decrypt(key []byte, text string) (string, error) {
	block, err := aes.NewCipher(key)
	if err != nil {
		return "", err
	}
	decodedMsg,_ := hex.DecodeString(text)
	iv  :=make([]byte,aes.BlockSize)
	msg := decodedMsg
	mode := cipher.NewCBCDecrypter(block, iv)
	mode.CryptBlocks(msg,msg)
	unpadMsg, err := unpad(msg)
	if err != nil {
		return "", err
	}
	return string(unpadMsg), nil
}
func main() {
	key := []byte("ytruidghj1234597")
	encryptText, _ := encrypt(key, "xrdp:3389,1705728510")
	rawText, _ := decrypt(key, encryptText )
	fmt.Printf("text %s \n", rawText)
	fmt.Printf("text %s \n", encryptText)
}