Last active
September 19, 2024 21:06
-
-
Save cannium/c167a19030f2a3c6adbb5a5174bea3ff to your computer and use it in GitHub Desktop.
golang aes-256-gcm
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" | |
"crypto/rand" | |
"encoding/hex" | |
"fmt" | |
"io" | |
) | |
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()) | |
} | |
fmt.Printf("%x\n", nonce) | |
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("2df87baf86b5073ef1f03e3cc738de75b511400f5465bb0ddeacf47ae4dc267d") | |
nonce, _ := hex.DecodeString("afb8a7579bf971db9f8ceeed") | |
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", plaintext) | |
// Output: exampleplaintext | |
} | |
func main() { | |
ExampleNewGCMEncrypter() | |
ExampleNewGCMDecrypter() | |
} |
What is the magic string afb8a7579bf971db9f8ceeed
on line 45?
afb8a7579bf971db9f8ceeed
should be the nonce outputed on line 28
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Code above as a tool:
https://gist.github.com/tinti/1afe25d09ed918b4b3cf5bea8632e798