Data encryption with AES-GCM
Below program will randomly generate a 32 byte (128 bit) AES key.
Example
package main
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"fmt"
"io"
)
func main() {
plaintext := []byte("Golang Programs")
key := make([]byte, 32)
if _, err := io.ReadFull(rand.Reader, key); err != nil {
panic(err.Error())
}
block, err := aes.NewCipher(key)
if err != nil {
panic(err.Error())
}
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("Key:\t\t%x", key)
fmt.Printf("\nCiphertext:\t%x", ciphertext)
}
Output
Key: adbb347fd8f1260b7796fcc17bda48d67f7aadd9b9bcd81242e430ec9ca37233
Ciphertext: 0c2da800fa0acbb152a461515f0846e22c8fa80a5819814e26e7d233010d91
Most Helpful This Week
How to import structs from another package in Go?
Example to create custom error
Example: Stack and Caller from RUNTIME package
How to get the current date and time with timestamp in local and other timezones ?
How to check if a map contains a key in Go?
What is Rune? How to get ASCII value of any character in Go?