Skip to content

Instantly share code, notes, and snippets.

@m4dfry
Forked from cannium/aes-256-gcm.go
Last active April 19, 2017 14:52
Show Gist options
  • Save m4dfry/f0d5d34af53a612d80d6e1035d40c13e to your computer and use it in GitHub Desktop.
Save m4dfry/f0d5d34af53a612d80d6e1035d40c13e to your computer and use it in GitHub Desktop.
golang aes-256-gcm no-magic
package main
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"fmt"
"io"
)
func ExampleNewGCMEncrypter(input string) ([]byte, []byte) {
// The key argument should be the AES key, either 16 or 32 bytes
// to select AES-128 or AES-256.
key := []byte("AES256Key-32Characters1234567890")
plaintext := []byte(input)
block, err := aes.NewCipher(key)
if err != nil {
panic(err.Error())
}
// Never use more than 2^32 random nonces with a given key because of the risk of a repeat.
nonce := make([]byte, 12)
if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
panic(err.Error())
}
fmt.Printf("Nonce:%x\n", nonce)
aesgcm, err := cipher.NewGCM(block)
if err != nil {
panic(err.Error())
}
ciphertext := aesgcm.Seal(nil, nonce, plaintext, nil)
fmt.Printf("Cyphertext:%x\n", ciphertext)
return ciphertext, nonce
}
func ExampleNewGCMDecrypter(ciphertext []byte, nonce[]byte) {
// The key argument should be the AES key, either 16 or 32 bytes
// to select AES-128 or AES-256.
key := []byte("AES256Key-32Characters1234567890")
block, err := aes.NewCipher(key)
if err != nil {
panic(err.Error())
}
aesgcm, err := cipher.NewGCM(block)
if err != nil {
panic(err.Error())
}
plaintext, err := aesgcm.Open(nil, nonce, ciphertext, nil)
if err != nil {
panic(err.Error())
}
fmt.Printf("Plaintext: %s\n", plaintext)
// Output: exampleplaintext
}
func main() {
cyphertext, nonce := ExampleNewGCMEncrypter("exampleplaintext")
ExampleNewGCMDecrypter(cyphertext, nonce)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment