golang aes encryption example
To perform AES encryption in Go (Golang), you can use the "crypto/aes" package. Here is an example that demonstrates the steps involved in AES encryption:
Step 1: Import the required packages:
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"errors"
"io"
)
Step 2: Define a function to encrypt the data:
func encrypt(key, plaintext []byte) ([]byte, error) {
// Create a new AES cipher block using the provided key.
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
// Generate a random initialization vector (IV).
iv := make([]byte, aes.BlockSize)
if _, err := io.ReadFull(rand.Reader, iv); err != nil {
return nil, err
}
// Create a new AES-GCM cipher using the block and IV.
aesGCM, err := cipher.NewGCM(block)
if err != nil {
return nil, err
}
// Encrypt the plaintext using the AES-GCM cipher.
ciphertext := aesGCM.Seal(nil, iv, plaintext, nil)
// Prepend the IV to the ciphertext.
ciphertext = append(iv, ciphertext...)
return ciphertext, nil
}
Step 3: Define a function to decrypt the data:
func decrypt(key, ciphertext []byte) ([]byte, error) {
// Create a new AES cipher block using the provided key.
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
// Ensure that the ciphertext is long enough to contain the IV.
if len(ciphertext) < aes.BlockSize {
return nil, errors.New("ciphertext too short")
}
// Extract the IV from the ciphertext.
iv := ciphertext[:aes.BlockSize]
ciphertext = ciphertext[aes.BlockSize:]
// Create a new AES-GCM cipher using the block and IV.
aesGCM, err := cipher.NewGCM(block)
if err != nil {
return nil, err
}
// Decrypt the ciphertext using the AES-GCM cipher.
plaintext, err := aesGCM.Open(nil, iv, ciphertext, nil)
if err != nil {
return nil, err
}
return plaintext, nil
}
Step 4: Use the encrypt and decrypt functions:
func main() {
key := []byte("0123456789abcdef") // 16-byte AES key
plaintext := []byte("Hello, World!")
ciphertext, err := encrypt(key, plaintext)
if err != nil {
panic(err)
}
decrypted, err := decrypt(key, ciphertext)
if err != nil {
panic(err)
}
fmt.Println("Plaintext:", string(plaintext))
fmt.Println("Ciphertext:", ciphertext)
fmt.Println("Decrypted:", string(decrypted))
}
This example demonstrates how to perform AES encryption and decryption using the "crypto/aes" package in Go.