Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nirui/82ac53051d676bebf466c0121231eab9 to your computer and use it in GitHub Desktop.
Save nirui/82ac53051d676bebf466c0121231eab9 to your computer and use it in GitHub Desktop.
package main
import (
"crypto/aes"
"crypto/cipher"
"fmt"
)
func decrypt(key, nonce, buf []byte, bufPadLength int) {
block, err := aes.NewCipher(key[:])
if err != nil {
panic(err.Error())
}
aesgcm, err := cipher.NewGCM(block)
if err != nil {
panic(err.Error())
}
// Notice the by setting up `bufPadLength`, we can select the actual
// section that contains the ciphertext data.
//
// Also notice that we're writing the decrypted data back to `buf`
//
plaintext, err := aesgcm.Open(
buf[:0], nonce[:], buf[bufPadLength:], nil)
if err != nil {
panic(err.Error())
}
fmt.Printf("Decrypted: %s\n", string(plaintext))
}
func main() {
key := [16]byte{}
nonce := [12]byte{}
ciphertext := []byte{
70, 240, 187, 163, 16, 218, 198, 144,
229, 206, 237, 103, 216, 213, 198, 180, 145,
29, 111, 120, 137, 40, 173,
}
// Case 1: `ciphertext` with no pad: Prints out "Decrypted: Example"
ciphertextCase1 := make([]byte, len(ciphertext))
copy(ciphertextCase1, ciphertext)
decrypt(key[:], nonce[:], ciphertextCase1[:], 0)
// Case 2: `ciphertext` with a large enough pad: Prints out "Decrypted: Example"
padSize1 := len(ciphertext)
ciphertextCase2 := make([]byte, len(ciphertext) + padSize1)
copy(ciphertextCase2[padSize1:], ciphertext)
decrypt(key[:], nonce[:], ciphertextCase2[:], padSize1)
// Case 3: `ciphertext` with just 3 bytes padding at it's
// head (Not large enough): Panic "crypto/cipher: invalid buffer overlap"
padSize2 := 3
ciphertextCase3 := make([]byte, len(ciphertext) + padSize2)
copy(ciphertextCase3[padSize2:], ciphertext)
decrypt(key[:], nonce[:], ciphertextCase3[:], padSize2)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment