Go provides built-in support for AES-256 encryption through its "crypto/aes" package. Here's a practical example of how to use AES-256 encryption and decryption:
package main
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"encoding/base64"
"fmt"
"io"
)
func encrypt(plaintext []byte, key []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
// Create a new GCM
gcm, err := cipher.NewGCM(block)
if err != nil {
return nil, err
}
// Create a nonce
nonce := make([]byte, gcm.NonceSize())
if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
return nil, err
}
// Encrypt and seal
return gcm.Seal(nonce, nonce, plaintext, nil), nil
}
func decrypt(ciphertext []byte, key []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
gcm, err := cipher.NewGCM(block)
if err != nil {
return nil, err
}
nonceSize := gcm.NonceSize()
if len(ciphertext) < nonceSize {
return nil, fmt.Errorf("ciphertext too short")
}
nonce, ciphertext := ciphertext[:nonceSize], ciphertext[nonceSize:]
return gcm.Open(nil, nonce, ciphertext, nil)
}
func main() {
// Key must be 32 bytes for AES-256
key := make([]byte, 32)
if _, err := rand.Read(key); err != nil {
panic(err)
}
message := []byte("Hello, AES-256!")
// Encrypt
encrypted, err := encrypt(message, key)
if err != nil {
panic(err)
}
fmt.Printf("Encrypted: %s\n", base64.StdEncoding.EncodeToString(encrypted))
// Decrypt
decrypted, err := decrypt(encrypted, key)
if err != nil {
panic(err)
}
fmt.Printf("Decrypted: %s\n", string(decrypted))
}
This example uses AES-GCM (Galois/Counter Mode), which provides both confidentiality and authenticity. Some key points about the implementation:
Important security considerations: