使用标准库crypto/aes
实现AES加密和解密
代码实现
package main import ( "crypto/aes" "encoding/hex" ) func EncryptAES(key string, plainText string) (string, error) { cipher, err := aes.NewCipher([]byte(key)) if err != nil { return "", err } out := make([]byte, len(plainText)) cipher.Encrypt(out, []byte(plainText)) return hex.EncodeToString(out), nil } func DecryptAES(key string, encryptText string) (string, error) { decodeText, _ := hex.DecodeString(encryptText) cipher, err := aes.NewCipher([]byte(key)) if err != nil { return "", err } out := make([]byte, len(decodeText)) cipher.Decrypt(out, decodeText) return string(out[:]), nil }
加密
// cipher key key := "thisisakeymustmorethan16" // plaintext text := "This is a secret" encrypt, err := EncryptAES(key, text) if err != nil { log.Fatal(err) } fmt.Println(encrypt) // db647f5df56904ef3463834abc019c1d
解密
// cipher key key := "thisisakeymustmorethan16" // decrypt decrypt := "db647f5df56904ef3463834abc019c1d" plaintext, err := DecryptAES(key, decrypt) if err != nil { log.Fatal(err) } fmt.Println(plaintext) // This is a secret
参考