Last active
October 22, 2017 19:55
-
-
Save aksiksi/3f86145ae436ec99e95c0c8ca3443a11 to your computer and use it in GitHub Desktop.
Encrypt and decrypt a plaintext with AES-GCM in Go. Plaintext is passed in as command line argument.
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" | |
"fmt" | |
"io" | |
"os" | |
) | |
func main() { | |
if len(os.Args) < 2 { | |
fmt.Println("Usage: aesgcm <plaintext>") | |
os.Exit(0) | |
} | |
fmt.Println("Plaintext = " + os.Args[1]) | |
// Get plaintext as a byte slice | |
plaintext := []byte(os.Args[1]) | |
// Randomly generate a 32 byte (128 bit) AES key | |
key := make([]byte, 32) | |
if _, err := io.ReadFull(rand.Reader, key); err != nil { | |
panic(err.Error()) | |
} | |
fmt.Printf("Key = %x\n", key) | |
// Get an AES cipher instance using the key | |
block, err := aes.NewCipher(key) | |
if err != nil { | |
panic(err.Error()) | |
} | |
// Generate a nonce for GCM | |
nonce := make([]byte, 12) | |
if _, err := io.ReadFull(rand.Reader, nonce); err != nil { | |
panic(err.Error()) | |
} | |
// Get GCM instance that uses the AES cipher | |
aesgcm, err := cipher.NewGCM(block) | |
if err != nil { | |
panic(err.Error()) | |
} | |
// Perform AES-GCM encryption with generated nonce | |
ciphertext := aesgcm.Seal(nil, nonce, plaintext, nil) | |
fmt.Printf("Ciphertext = %x\n", ciphertext) | |
// Now perform decryption of the ciphertext | |
plaintextNew, err := aesgcm.Open(nil, nonce, ciphertext, nil) | |
if err != nil { | |
panic(err.Error()) | |
} | |
fmt.Printf("Decrypted Plaintext = %s\n", plaintextNew) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment