Skip to content

Instantly share code, notes, and snippets.

@kkirsche
Last active November 12, 2024 02:47
Show Gist options
  • Select an option

  • Save kkirsche/e28da6754c39d5e7ea10 to your computer and use it in GitHub Desktop.

Select an option

Save kkirsche/e28da6754c39d5e7ea10 to your computer and use it in GitHub Desktop.
AES-256 GCM Encryption Example in Golang
package example_test
import (
"crypto/aes"
"crypto/cipher"
"hex"
"io"
)
// AES-GCM should be used because the operation is an authenticated encryption
// algorithm designed to provide both data authenticity (integrity) as well as
// confidentiality.
// Merged into Golang in https://go-review.googlesource.com/#/c/18803/
func ExampleNewGCMEncrypter() {
// 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("exampleplaintext")
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())
}
aesgcm, err := cipher.NewGCM(block)
if err != nil {
panic(err.Error())
}
ciphertext := aesgcm.Seal(nil, nonce, plaintext, nil)
fmt.Printf("%x\n", ciphertext)
}
func ExampleNewGCMDecrypter() {
// The key argument should be the AES key, either 16 or 32 bytes
// to select AES-128 or AES-256.
key := []byte("AES256Key-32Characters1234567890")
ciphertext, _ := hex.DecodeString("f90fbef747e7212ad7410d0eee2d965de7e890471695cddd2a5bc0ef5da1d04ad8147b62141ad6e4914aee8c512f64fba9037603d41de0d50b718bd665f019cdcd")
nonce, _ := hex.DecodeString("bb8ef84243d2ee95a41c6c57")
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("%s\n", string(plaintext))
}
@soloink

soloink commented Mar 5, 2016

Copy link
Copy Markdown

I attempted to run the code but I get the following error message:

panic: cipher: message authentication failed

This happens on line 60, with the 'aesgcm.Open'.

Using go version go1.5.1 darwin/amd64

@zingero

zingero commented Aug 9, 2016

Copy link
Copy Markdown

I got the same message using go1.6.3.

@cannium

cannium commented Sep 1, 2016

Copy link
Copy Markdown

@airdamien

Copy link
Copy Markdown

it's because your nonce is randomly generated for encryption, but set for decryption

@dakait

dakait commented Aug 29, 2018

Copy link
Copy Markdown

@sergiopp

sergiopp commented Dec 29, 2020

Copy link
Copy Markdown

Hi there! I'm new with golang and im trying to separate "enc" and "dec" in separated binaries but I have the same message that "soloink" had

panic: cipher: message authentication failed

goroutine 1 [running]:
main.ExampleNewGCMDecrypter(0xc000086030, 0x2c)
C:/Users/sergiop/Desktop/GOLANG/all2_dec.go:32 +0x345
main.main()
C:/Users/sergiop/Desktop/GOLANG/all2_dec.go:42 +0x4b
exit status 2

would you like to help me guys? Thanks!!

note: I'm passing the enc data as a parameter to "dec" binary

@kkirsche

kkirsche commented Dec 29, 2020

Copy link
Copy Markdown
Author

Id recommend reviewing the following PR to Go’s upstream where I had examples added to standard library.

https://go-review.googlesource.com/c/go/+/18803

also in latest code:
https://golang.org/src/crypto/cipher/example_test.go

@kkirsche

kkirsche commented Dec 29, 2020

Copy link
Copy Markdown
Author

If more support is needed, I’d ask for a more detailed bug report related to what has been tried, what the issue is, and a test case for me to reproduce the issue.

Most common cause for authentication issues I find is bit flips on messages when sent over public IP, I think my failure rate was about 0.7% sending data every 30s. Look into ICMP ping pattern (https://linux.die.net/man/8/ping look at -p pattern) option for detecting these.

Depending on your implementation, time drift can also cause issues which you wouldn’t expect (eg the clock on the sender and receiver aren’t in sync, usually when it’s more than 60 seconds off are when issues start)

@anotherGoogleFan

Copy link
Copy Markdown

What if I want an aes128-gcm?

@kkirsche

kkirsche commented Mar 4, 2021

Copy link
Copy Markdown
Author

@anotherGoogleFan it’s stated in the code.

// The key argument should be the AES key, either 16 or 32 bytes
// to select AES-128 or AES-256.

@anotherGoogleFan

Copy link
Copy Markdown

I read some documents, they say the nonce for decryption could be read by the encrypt result. So you only need to know the key to decrypt. But in the example we must know both the nonce and the key to decrypt. So, if we really can decrypt the result by only using key(without knowing the nonce)?

@Nv7-GitHub

Copy link
Copy Markdown

I am also wondering, how do you decrypt without the nonce?

@ManouchehrRasoulli

Copy link
Copy Markdown

actually nonce are pre-setted between devices, or somehow securely will sent into client to decrypt response

@kkirsche

kkirsche commented Dec 9, 2021

Copy link
Copy Markdown
Author

@ManouchehrRasoulli depends on your use case. You assumed how this is being used, and assumed incorrectly. This was written for one way usage in which it is impossible for that to occur as you described.

@kkirsche

kkirsche commented Dec 9, 2021

Copy link
Copy Markdown
Author

@Nv7-GitHub nonce and iv technically aren't secret in GCM (this can differ with other versions like CTR). You can append it to the ciphertext. With that said, some circumstances don't allow that, in which I'd direct you to https://datatracker.ietf.org/doc/html/rfc5116#section-3.2.1

@lukejoshuapark

lukejoshuapark commented Feb 12, 2023

Copy link
Copy Markdown

This code is just bad. The encryption code generates a random nonce:

// 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())
	}

and the decryption code uses a fixed nonce:

nonce, _ := hex.DecodeString("bb8ef84243d2ee95a41c6c57")

The correct mechanism is to attach the nonce to the ciphertext in the encrypt function and detach and use it in the decrypt function. The nonce isn't a secret value.

Further, don't use a "32 character AES key":

  1. Some characters are more than 1 byte 😉
  2. Any key that gets used that isn't randomly generated should always be passed through a KDF first. Argon2 is a good option.

@kkirsche

Copy link
Copy Markdown
Author

@lukejoshuapark thanks for the feedback, this was not and is not a "use this example for whatever encryption you want". For the original use case, the code has been vetted by an outside security firm and the points you raised are not in play for the use case this specific code was designed for.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment