Skip to content

Instantly share code, notes, and snippets.

@aksiksi aksiksi/aesgcm.go
Last active Oct 22, 2017

Embed
What would you like to do?
Encrypt and decrypt a plaintext with AES-GCM in Go. Plaintext is passed in as command line argument.
package main
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"fmt"
"io"
"os"
)
func main() {
if len(os.Args) < 2 {
fmt.Println("Usage: aesgcm <plaintext>")
os.Exit(0)
}
fmt.Println("Plaintext = " + os.Args[1])
// Get plaintext as a byte slice
plaintext := []byte(os.Args[1])
// Randomly generate a 32 byte (128 bit) AES key
key := make([]byte, 32)
if _, err := io.ReadFull(rand.Reader, key); err != nil {
panic(err.Error())
}
fmt.Printf("Key = %x\n", key)
// Get an AES cipher instance using the key
block, err := aes.NewCipher(key)
if err != nil {
panic(err.Error())
}
// Generate a nonce for GCM
nonce := make([]byte, 12)
if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
panic(err.Error())
}
// Get GCM instance that uses the AES cipher
aesgcm, err := cipher.NewGCM(block)
if err != nil {
panic(err.Error())
}
// Perform AES-GCM encryption with generated nonce
ciphertext := aesgcm.Seal(nil, nonce, plaintext, nil)
fmt.Printf("Ciphertext = %x\n", ciphertext)
// Now perform decryption of the ciphertext
plaintextNew, err := aesgcm.Open(nil, nonce, ciphertext, nil)
if err != nil {
panic(err.Error())
}
fmt.Printf("Decrypted Plaintext = %s\n", plaintextNew)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.