This example demonstrates basic AES (Advanced Encryption Standard) GCM (Galois/Counter Mode) encryption and decryption using the aesgcm package.
The aes example showcases:
- Defining a hexadecimal AES key.
- Encrypting a plaintext byte slice (
[]byte("0123456789abcdef")) usingaesgcm.AESEncrypt. - Decrypting the resulting ciphertext using
aesgcm.AESDecryptwith the same key. - Printing the decrypted data.
package main
import (
"encoding/hex"
"fmt"
aes "github.com/bsv-blockchain/go-sdk/primitives/aesgcm"
)
func main() {
// Define an AES key (must be 16, 24, or 32 bytes for AES-128, AES-192, or AES-256 respectively)
key, _ := hex.DecodeString("000102030405060708090a0b0c0d0e0f") // 16 bytes for AES-128
plaintext := []byte("0123456789abcdef")
// Encrypt the data
encryptedData, err := aes.AESEncrypt(plaintext, key)
if err != nil {
fmt.Println("Encryption error:", err)
return
}
fmt.Printf("Encrypted data (hex): %x\n", encryptedData)
// Decrypt the data
decryptedData, err := aes.AESDecrypt(encryptedData, key)
if err != nil {
fmt.Println("Decryption error:", err)
return
}
fmt.Printf("Decrypted data: %s\n", decryptedData)
}This section shows:
- Initialization of a 16-byte AES key.
- Encryption of a sample plaintext using
aes.AESEncrypt. This function handles nonce generation and prepends it to the ciphertext. - Decryption of the ciphertext using
aes.AESDecrypt. This function extracts the nonce from the ciphertext and performs decryption.
To run this example:
go run aes.goThe output will show the hexadecimal representation of the encrypted data, followed by the successfully decrypted original message.
Note:
- The key used is hardcoded. In real applications, keys should be securely generated and managed.
- The
aesgcmpackage uses AES in GCM mode, which provides both confidentiality and authenticity. - The nonce is generated internally by
AESEncryptand prepended to the ciphertext.AESDecryptexpects this format.
To use AES GCM encryption/decryption in your application:
For Encryption:
- Obtain or generate a secure AES key of appropriate length (16, 24, or 32 bytes).
- Call
ciphertext, err := aesgcm.AESEncrypt(plaintextBytes, key). - Store or transmit the
ciphertext.
For Decryption:
- Obtain the same AES key used for encryption.
- Call
plaintextBytes, err := aesgcm.AESDecrypt(ciphertext, key). - The
plaintextByteswill contain the original data if decryption is successful.
Ensure proper key management practices are followed.
For more information, see:
- Package Documentation - aesgcm
- NIST Special Publication 800-38D for GCM mode.