The Advanced Encryption Standard (AES) aka Rijndael is an encryption algorithm created in 2001 by NIST. It uses 128-bit blocks of data to encrypt and is a symmetric block cipher. In this post, we are going to encrypt and decrypt data using AES in Go.
Required imports
We will need the crypto/aes package for it to work.
import (
"crypto/aes"
"encoding/hex"
)
We will also use hex encoding to encode the data to a string.
Encrypting a message using AES
Now to use encryption we will need the key to be a 32-bit one. The key will be sent to the cipher to encode the plaintext.
// cipher key
key := "thisis32bitlongpassphraseimusing"
// plaintext
pt := "This is a secret"
c := EncryptAES([]byte(key), pt)
Here the EncryptAES function is as follows:
func EncryptAES(key []byte, plaintext string) string {
// create cipher
c, err := aes.NewCipher(key)
CheckError(err)
// allocate space for ciphered data
out := make([]byte, len(plaintext))
// encrypt
c.Encrypt(out, []byte(plaintext))
// return hex string
return hex.EncodeToString(out)
}
When printing the ciphertext it will produce output like this:
Decrypting a message in AES
Now, we are going to decrypt the message encrypted using the AES algorithm. Here is the code to do it.
func DecryptAES(key []byte, ct string) {
ciphertext, _ := hex.DecodeString(ct)
c, err := aes.NewCipher(key)
CheckError(err)
pt := make([]byte, len(ciphertext))
c.Decrypt(pt, ciphertext)
s := string(pt[:])
fmt.Println("DECRYPTED:", s)
}
This function decrypts the AES encrypted ciphertext from a hex string.
Now, when used it will produce output as follows:
The full source
The full source code of the program is as follows.
package main
import (
"crypto/aes"
"encoding/hex"
"fmt"
)
func main() {
// cipher key
key := "thisis32bitlongpassphraseimusing"
// plaintext
pt := "This is a secret"
c := EncryptAES([]byte(key), pt)
// plaintext
fmt.Println(pt)
// ciphertext
fmt.Println(c)
// decrypt
DecryptAES([]byte(key), c)
}
func EncryptAES(key []byte, plaintext string) string {
c, err := aes.NewCipher(key)
CheckError(err)
out := make([]byte, len(plaintext))
c.Encrypt(out, []byte(plaintext))
return hex.EncodeToString(out)
}
func DecryptAES(key []byte, ct string) {
ciphertext, _ := hex.DecodeString(ct)
c, err := aes.NewCipher(key)
CheckError(err)
pt := make([]byte, len(ciphertext))
c.Decrypt(pt, ciphertext)
s := string(pt[:])
fmt.Println("DECRYPTED:", s)
}
func CheckError(err error) {
if err != nil {
panic(err)
}
}