Skip to content

Age File Encryption — Go source

Encrypt and decrypt files with age — a modern, simple alternative to PGP. Password-based encryption runs entirely in your browser.

This is the Go implementation — the same logic the interactive tool runs, in a shareable, citable form.

// Package ageencryption ports src/lib/age-encryption.ts (dual source: the web
// lib is TypeScript, the CLI lib is Go — kept in lock-step). It implements
// passphrase-based file encryption in the spirit of the age format
// (age-encryption.org/v1): one simple, explicit, authenticated envelope.
//
// The TS lib wraps the file key with Web Crypto primitives: PBKDF2-SHA256
// (100k iterations) key stretching, a fresh random salt per encryption, and
// AES-256-GCM authenticated encryption. This port uses the same construction
// with the Go stdlib — an RFC 8018 PBKDF2-HMAC-SHA256 built on crypto/hmac
// (Web Crypto and this package produce identical derived keys; see the
// known-answer vectors in age_encryption_test.go), crypto/aes GCM with the
// standard 12-byte IV and 16-byte tag, matching the Web Crypto wire format
// byte for byte.
//
// Wire format (age-style header + body), identical to the TS lib:
//
//	"cosmodev-age-v1" (15 B ASCII magic) || salt (16 B) || IV (12 B)
//	|| AES-256-GCM ciphertext + tag (16 B)
//
// Never panics; invalid input returns an error. Pure library, no I/O.
package ageencryption

import (
	"crypto/aes"
	"crypto/cipher"
	"crypto/hmac"
	"crypto/rand"
	"crypto/sha256"
	"errors"
	"fmt"
)

// AgeHeader is the ASCII magic prefix of every encrypted payload.
const AgeHeader = "cosmodev-age-v1"

// SaltLength is the PBKDF2 salt size in bytes.
const SaltLength = 16

// IVLength is the AES-GCM nonce size in bytes.
const IVLength = 12

// Iterations is the PBKDF2-SHA256 iteration count used for key stretching.
const Iterations = 100_000

var headerBytes = []byte(AgeHeader)

const (
	headerLength = 15 // len(AgeHeader)
	tagLength    = 16 // GCM auth tag appended to the ciphertext
	// Overhead is the smallest possible encrypted payload: header + salt +
	// IV + tag.
	Overhead = headerLength + SaltLength + IVLength + tagLength
)

// IsAgeEncrypted reports whether data starts with the cosmodev-age-v1 magic
// header. It mirrors isAgeEncrypted() in the TS lib.
func IsAgeEncrypted(data []byte) bool {
	return len(data) >= headerLength && hmac.Equal(data[:headerLength], headerBytes)
}

// pbkdf2Key derives a key of keyLen bytes from password and salt using
// PBKDF2-HMAC-SHA256 with iter iterations (RFC 8018, section 5.2). It is
// byte-identical to Web Crypto's PBKDF2 with hash: 'SHA-256'.
func pbkdf2Key(password, salt []byte, iter, keyLen int) []byte {
	prf := hmac.New(sha256.New, password)
	hashLen := prf.Size()
	numBlocks := (keyLen + hashLen - 1) / hashLen
	dk := make([]byte, 0, numBlocks*hashLen)
	u := make([]byte, hashLen)
	var blockBytes [4]byte
	for block := 1; block <= numBlocks; block++ {
		// U1 = PRF(password, salt || INT_32_BE(block))
		prf.Reset()
		prf.Write(salt)
		blockBytes[0] = byte(block >> 24)
		blockBytes[1] = byte(block >> 16)
		blockBytes[2] = byte(block >> 8)
		blockBytes[3] = byte(block)
		prf.Write(blockBytes[:])
		dk = prf.Sum(dk)
		t := dk[len(dk)-hashLen:]
		copy(u, t)
		// U_n = PRF(password, U_{n-1}); T = T xor U_n
		for n := 2; n <= iter; n++ {
			prf.Reset()
			prf.Write(u)
			u = prf.Sum(u[:0])
			for x := range u {
				t[x] ^= u[x]
			}
		}
	}
	return dk[:keyLen]
}

// deriveAESKey stretches a passphrase into a 256-bit AES-GCM key.
func deriveAESKey(passphrase string, salt []byte) (cipher.Block, error) {
	key := pbkdf2Key([]byte(passphrase), salt, Iterations, 32)
	return aes.NewCipher(key)
}

// encryptWith encrypts data under passphrase with a caller-supplied salt and
// IV (ageEncrypt generates fresh crypto/rand values; tests pin them to verify
// byte-for-byte parity with Web Crypto). Returns header || salt || IV ||
// ciphertext+tag.
func encryptWith(data []byte, passphrase string, salt, iv []byte) ([]byte, error) {
	block, err := deriveAESKey(passphrase, salt)
	if err != nil {
		return nil, err
	}
	gcm, err := cipher.NewGCM(block)
	if err != nil {
		return nil, err
	}
	out := make([]byte, 0, Overhead+len(data))
	out = append(out, headerBytes...)
	out = append(out, salt...)
	out = append(out, iv...)
	return gcm.Seal(out, iv, data, nil), nil
}

// AgeEncrypt encrypts data under passphrase. It returns
// header || salt || IV || ciphertext+tag, mirroring ageEncrypt() in the TS
// lib: a fresh random salt and IV make every encryption of the same input
// produce different bytes. It errors when the passphrase is empty or data is
// empty.
func AgeEncrypt(data []byte, passphrase string) ([]byte, error) {
	if passphrase == "" {
		return nil, errors.New("Passphrase must not be empty.")
	}
	if len(data) == 0 {
		return nil, errors.New("Input data is empty - nothing to encrypt.")
	}
	salt := make([]byte, SaltLength)
	if _, err := rand.Read(salt); err != nil {
		return nil, err
	}
	iv := make([]byte, IVLength)
	if _, err := rand.Read(iv); err != nil {
		return nil, err
	}
	return encryptWith(data, passphrase, salt, iv)
}

// AgeDecrypt decrypts a payload produced by AgeEncrypt (or by the TS lib's
// ageEncrypt — the wire format is shared). It errors when the passphrase is
// empty, the data lacks the cosmodev-age-v1 header, the payload is too short,
// or the passphrase is wrong / the payload was tampered with (GCM auth-tag
// failure). It mirrors ageDecrypt() in the TS lib.
func AgeDecrypt(data []byte, passphrase string) ([]byte, error) {
	if passphrase == "" {
		return nil, errors.New("Passphrase must not be empty.")
	}
	if !IsAgeEncrypted(data) {
		return nil, errors.New("Not an age-encrypted file (missing cosmodev-age-v1 header).")
	}
	if len(data) < Overhead {
		return nil, fmt.Errorf(
			"Input is too short to be an age-encrypted file (needs at least %d bytes: header + salt + IV + auth tag).",
			Overhead,
		)
	}
	salt := data[headerLength : headerLength+SaltLength]
	iv := data[headerLength+SaltLength : headerLength+SaltLength+IVLength]
	ciphertext := data[headerLength+SaltLength+IVLength:]
	block, err := deriveAESKey(passphrase, salt)
	if err != nil {
		return nil, err
	}
	gcm, err := cipher.NewGCM(block)
	if err != nil {
		return nil, err
	}
	plaintext, err := gcm.Open(nil, iv, ciphertext, nil)
	if err != nil {
		// A GCM auth-tag failure means the key did not match (wrong
		// passphrase) or the payload was modified after encryption.
		return nil, errors.New("Decryption failed: wrong passphrase or corrupted file.")
	}
	return plaintext, nil
}

Also available in 13 other languages

Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →