Created
August 23, 2020 13:26
-
-
Save nirui/82ac53051d676bebf466c0121231eab9 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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