golang实现加密解密的库很多, 这里使用的是aes库+base64库来实现.
使用时,需要指定一个私钥,来进行加解密.
上代码:
package main
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"encoding/base64"
"fmt"
)
type AesCrypt struct {
Key []byte
Text []byte
crypt string
}
func (t *AesCrypt) PKCS5Padding(cipherText []byte, blockSize int) []byte {
padding := blockSize - len(cipherText)%blockSize
padText := bytes.Repeat([]byte{byte(padding)}, padding)
return append(cipherText, padText...)
}
func (t *AesCrypt) PKCS5UnPadding(data []byte) []byte {
length := len(data)
unPadding := int(data[length-1])
return data[:(length - unPadding)]
}
func (t *AesCrypt) encrypt() (string, error) {
block, err := aes.NewCipher(t.Key)
if err != nil {
return "", err
}
blockSize := block.BlockSize()
t.Text = t.PKCS5Padding(t.Text, blockSize)
blockMode := cipher.NewCBCEncrypter(block, t.Key[:blockSize])
data := make([]byte, len(t.Text))
blockMode.CryptBlocks(data, t.Text)
return base64.StdEncoding.EncodeToString(data), nil
}
func (t *AesCrypt) decrypt() ([]byte, error) {
crypted, err := base64.StdEncoding.DecodeString(t.crypt)
if err != nil {
return nil, err
}
block, err := aes.NewCipher(t.Key)
if err != nil {
return nil, err
}
blockSize := block.BlockSize()
blockMode := cipher.NewCBCDecrypter(block, t.Key[:blockSize])
data := make([]byte, len(crypted))
blockMode.CryptBlocks(data, crypted)
data = t.PKCS5UnPadding(data)
return data, nil
}
func main() {
key := []byte("12345678123456cc") //私钥
word := []byte("this is test!") //要加密的字符串
var aesCrypt AesCrypt
//设置key
aesCrypt.Key = key
//加密
aesCrypt.Text = word
crypt, err := aesCrypt.encrypt()
if err != nil {
fmt.Println(err)
return
}
fmt.Printf("加密后:%vn", crypt)
//解密
aesCrypt.crypt = crypt
word, err = aesCrypt.decrypt()
if err != nil {
fmt.Println(err)
return
}
fmt.Printf("解密后:%sn", word)
}
输出:
加密后:6/soAEkh3oVaIZkABcwjJQ==
解密后:this is test!