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