golang使用aes加密和解密
密码学中的高级加密标准(Advanced Encryption Standard,AES)(对称加密算法),又称Rijndael加密法,这个标准用来替代原先的DES。AES加密数据块分组长度必须为128bit,密钥长度可以是128bit、192bit、256bit中的任意一个。
示例代码
// aes.go
package main
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"encoding/hex"
"errors"
"fmt"
"io"
"sync"
)
func main() {
se, err := AesEncrypt("aes-20170416-30-1000")
fmt.Println(se, err)
sd, err := AesDecrypt(se)
fmt.Println(sd, err)
}
var (
commonkey = []byte("nanjishidu170416")
syncMutex sync.Mutex
)
func SetAesKey(key string) {
syncMutex.Lock()
defer syncMutex.Unlock()
commonkey = []byte(key)
}
func AesEncrypt(plaintext string) (string, error) {
block, err := aes.NewCipher(commonkey)
if err != nil {
return "", err
}
ciphertext := make([]byte, aes.BlockSize+len(plaintext))
iv := ciphertext[:aes.BlockSize]
if _, err := io.ReadFull(rand.Reader, iv); err != nil {
return "", err
}
cipher.NewCFBEncrypter(block, iv).XORKeyStream(ciphertext[aes.BlockSize:],
[]byte(plaintext))
return hex.EncodeToString(ciphertext), nil
}
func AesDecrypt(d string) (string, error) {
ciphertext, err := hex.DecodeString(d)
if err != nil {
return "", err
}
block, err := aes.NewCipher(commonkey)
if err != nil {
return "", err
}
if len(ciphertext) < aes.BlockSize {
return "", errors.New("ciphertext too short")
}
iv := ciphertext[:aes.BlockSize]
ciphertext = ciphertext[aes.BlockSize:]
fmt.Println(len(ciphertext), len(iv))
cipher.NewCFBDecrypter(block, iv).XORKeyStream(ciphertext, ciphertext)
return string(ciphertext), nil
}