Encryption and decryption with AES GCM

suggest change

You have a file and a password and you want to encrypt the file with a password.

There are many encryption algorithms.

This chapter describes how to use symmetric algorithm AES (Advanced Encryption Standard) in GCM mode.

GCM mode provides both encryption and authentication.

Without authentication an attacker could change ciphertext bytes and decryption could still succeed, returning corrupted plaintext. GCM authentication detects that change.

Symmetric means that we can use the same password to both encrypt and decrypt the data.

AES keys are 16, 24, or 32 bytes (AES-128, AES-192, or AES-256). This example derives a 32-byte key. Humans prefer passwords of arbitrary length.

To support humans we need to derive AES key from a human password. This is harder than it looks so you should use one of the methods that are well researched and considered cryptographically secure. One of those methods is scrypt key derivation function.

package main

import (
	"bytes"
	"crypto/aes"
	"crypto/cipher"
	"crypto/rand"
	"errors"
	"fmt"
	"io"
	"os"
	"log"

	"golang.org/x/crypto/scrypt"
)

func aesKeyFromPassword(password string) ([]byte, error) {
	// DO NOT use this salt. Generate a random salt per encryption (16 bytes
	// is a reasonable length) and store it with the ciphertext. A salt is
	// not a secret. Reusing one salt for every password makes precomputation
	// easier.
	secretSalt := []byte{0xbc, 0x1e, 0x07, 0xd7, 0xb2, 0xa2, 0x5e, 0x2c}
	return scrypt.Key([]byte(password), secretSalt, 32768, 8, 1, 32)
}

func aesGcmEncrypt(unencrypted []byte, password string) ([]byte, error) {
	key, err := aesKeyFromPassword(password)
	if err != nil {
		return nil, err
	}
	block, err := aes.NewCipher(key)
	if err != nil {
		return nil, err
	}

	gcm, err := cipher.NewGCM(block)
	if err != nil {
		return nil, err
	}

	// generate a random nonce (makes encryption stronger)
	nonce := make([]byte, gcm.NonceSize())
	if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
		return nil, err
	}

	encrypted := gcm.Seal(nil, nonce, unencrypted, nil)
	// we need nonce for decryption so we put it at the beginning
	// of encrypted text
	return append(nonce, encrypted...), nil
}

func aesGcmDecrypt(encrypted []byte, password string) ([]byte, error) {
	key, err := aesKeyFromPassword(password)
	if err != nil {
		return nil, err
	}

	block, err := aes.NewCipher(key)
	if err != nil {
		return nil, err
	}

	gcm, err := cipher.NewGCM(block)
	if err != nil {
		return nil, err
	}

	if len(encrypted) < gcm.NonceSize() {
		return nil, errors.New("Invalid data")
	}

	// extract random nonce we added to the beginning of the file
	nonce := encrypted[:gcm.NonceSize()]
	encrypted = encrypted[gcm.NonceSize():]

	return gcm.Open(nil, nonce, encrypted, nil)
}

func main() {
	password := "my password"
	d, err := os.ReadFile("main.go")
	if err != nil {
		log.Fatalf("os.ReadFile() failed with %s\n", err)
	}
	encrypted, err := aesGcmEncrypt(d, password)
	if err != nil {
		log.Fatalf("aesGcmEncrypt() failed with %s\n", err)
	}
	decrypted, err := aesGcmDecrypt(encrypted, password)
	if err != nil {
		log.Fatalf("aesGcmDecrypt() failed with %s\n", err)
	}
	if !bytes.Equal(d, decrypted) {
		log.Fatalf("decryption created data different from the original\n")
	} else {
		fmt.Printf("Encryption and decryption worked!\n")
	}
}

Encryption is a tricky subject and it's easy to make a mistake that would make it easy for the attacker to break encryption and decrypt the file.

It's really important to convert a human-readable password to a random encryption key.

Humans tend to use only a subset of possible bytes for passwords which makes them much easier to break.

Scrypt is a reasonable algorithm for deriving an encryption key from a human password. The salt should be unique for each encryption and stored next to the ciphertext. It does not need to be secret. The salt in the sample is fixed so the example can run; do not ship that.

There are several variants of AES algorithms. We chose GCM because it combines authentication with encryption. Authentication detects modification of encrypted data.

GCM requires a nonce. This code generates a unique nonce for each encryption and stores it at the beginning of the ciphertext. The nonce does not have to be secret.

Do not reuse a nonce with the same key. Repeating a GCM nonce is not a harmless shortcut: it breaks the confidentiality of the messages.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents