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:
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"fmt"
"io"
)
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
}
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
}
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
}
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.