How to use AES encryption and decryption in Go?

To use AES encryption and decryption in Go, you can utilize the crypto/aes package that provides the necessary functionality. Here's an example of how you can perform AES encryption and decryption:

  1. Import the required packages:
import ( "crypto/aes" "crypto/cipher" "crypto/rand" "fmt" "io" )
  1. Create a function for generating a AES key of the desired size (16, 24, or 32 bytes):
func generateAESKey(size int) []byte { key := make([]byte, size) _, err := rand.Read(key) if err != nil { panic(err) // error handling should be improved } return key }
  1. Implement the encryption function:
func encrypt(plainText []byte, key []byte) ([]byte, error) { block, err := aes.NewCipher(key) if err != nil { return nil, err } iv := make([]byte, aes.BlockSize) _, err = io.ReadFull(rand.Reader, iv) if err != nil { return nil, err } stream := cipher.NewCTR(block, iv) cipherText := make([]byte, len(plainText)) stream.XORKeyStream(cipherText, plainText) return append(iv, cipherText...), nil }
  1. Implement the decryption function:
func decrypt(cipherText []byte, key []byte) ([]byte, error) { block, err := aes.NewCipher(key) if err != nil { return nil, err } if len(cipherText) < aes.BlockSize { return nil, fmt.Errorf("cipherText too short") } iv := cipherText[:aes.BlockSize] cipherText = cipherText[aes.BlockSize:] stream := cipher.NewCTR(block, iv) plainText := make([]byte, len(cipherText)) stream.XORKeyStream(plainText, cipherText) return plainText, nil }
  1. Use the functions:
func main() { key := generateAESKey(32) // Generate a 32-byte key plainText := []byte("Hello, AES!") // Text to be encrypted cipherText, err := encrypt(plainText, key) if err != nil { panic(err) } decryptedText, err := decrypt(cipherText, key) if err != nil { panic(err) } fmt.Printf("Original Text: %s\n", plainText) fmt.Printf("Decrypted Text: %s\n", decryptedText) }

This example demonstrates a basic usage of AES encryption and decryption in Go. It's important to handle errors and implement appropriate error handling mechanisms in a production environment.