Skip to content

File Encryptor — Go source

Encrypt or decrypt any file with AES-256-GCM in your browser. Password-based, zero server contact. Drag, drop, done.

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

// Package fileencryptor ports src/lib/file-encryptor.ts (dual source: the web
// lib is TypeScript, the CLI lib is Go — kept in lock-step). Password-based
// AES-256-GCM encryption of raw bytes: the key is derived from the password
// with PBKDF2-SHA256 (fresh random salt per encryption) and the data is sealed
// with AES-256-GCM under a fresh random 12-byte IV.
//
// Wire format (identical to the TS lib, so payloads interop between web and
// CLI): salt (16 B) || IV (12 B) || AES-256-GCM ciphertext + tag (16 B). The
// same input + password therefore never encrypts to the same bytes, and the
// password is never stored or derivable from the output.
//
// The TS lib delegates to the Web Crypto API; Go needs no such guard
// (crypto/rand is always available), so the "Web Crypto is not available"
// error path has no twin here. PBKDF2 is implemented in-file on top of
// crypto/hmac + crypto/sha256 (RFC 8018) because the stdlib crypto/pbkdf2
// package requires Go >= 1.24 and this module targets 1.22.
package fileencryptor

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

// Key-derivation and wire-format constants, mirroring the TS lib's exported
// SALT_LENGTH / IV_LENGTH / ITERATIONS.
const (
	SaltLength = 16
	IVLength   = 12
	Iterations = 100_000
)

// GCM appends a 16-byte auth tag to the ciphertext; the smallest possible
// encrypted payload is therefore salt + IV + tag = 44 bytes.
const (
	tagLength = 16
	minLength = SaltLength + IVLength + tagLength
)

// Errors mirror the TS lib's thrown messages exactly, so callers (and shared
// test vectors) can match on the same substrings in both languages.
var (
	ErrEmptyPassword = errors.New("Password must not be empty.")
	ErrEmptyData     = errors.New("Input data is empty - nothing to encrypt.")
	ErrDecrypt       = errors.New("Decryption failed: wrong password or corrupted file.")
)

// pbkdf2Key derives keyLen bytes via PBKDF2-HMAC-SHA256 (RFC 8018). It plays
// the role of the TS lib's deriveKey(), which hands Web Crypto the same
// parameters ({name: 'PBKDF2', salt, iterations, 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

	var buf [4]byte
	dk := make([]byte, 0, numBlocks*hashLen)
	U := make([]byte, hashLen)
	for block := 1; block <= numBlocks; block++ {
		// T_1 = PRF(P, Salt || INT(block)); T_n = T_{n-1} ^ PRF(P, U_{n-1}).
		prf.Reset()
		prf.Write(salt)
		buf[0] = byte(block >> 24)
		buf[1] = byte(block >> 16)
		buf[2] = byte(block >> 8)
		buf[3] = byte(block)
		prf.Write(buf[:4])
		dk = prf.Sum(dk)
		T := dk[len(dk)-hashLen:]
		copy(U, T)

		for n := 2; n <= iter; n++ {
			prf.Reset()
			prf.Write(U)
			U = U[:0]
			U = prf.Sum(U)
			for x := range U {
				T[x] ^= U[x]
			}
		}
	}
	return dk[:keyLen]
}

// gcm seals/opens with the AES-256-GCM parameters the TS lib uses: 12-byte
// nonce, 16-byte tag, no additional authenticated data.
func gcm(key []byte) (cipher.AEAD, error) {
	block, err := aes.NewCipher(key)
	if err != nil {
		return nil, err
	}
	return cipher.NewGCM(block)
}

// EncryptFile encrypts data under password. It returns
// salt || IV || ciphertext+tag, mirroring encryptFile() in the TS lib.
func EncryptFile(data []byte, password string) ([]byte, error) {
	if password == "" {
		return nil, ErrEmptyPassword
	}
	if len(data) == 0 {
		return nil, ErrEmptyData
	}

	salt := make([]byte, SaltLength)
	if _, err := rand.Read(salt); err != nil {
		return nil, fmt.Errorf("reading random salt: %w", err)
	}
	iv := make([]byte, IVLength)
	if _, err := rand.Read(iv); err != nil {
		return nil, fmt.Errorf("reading random IV: %w", err)
	}

	key := pbkdf2Key([]byte(password), salt, Iterations, 32)
	aead, err := gcm(key)
	if err != nil {
		return nil, fmt.Errorf("initializing AES-256-GCM: %w", err)
	}
	ciphertext := aead.Seal(nil, iv, data, nil)

	out := make([]byte, 0, SaltLength+IVLength+len(ciphertext))
	out = append(out, salt...)
	out = append(out, iv...)
	return append(out, ciphertext...), nil
}

// DecryptFile decrypts a payload produced by EncryptFile (or by the TS
// encryptFile — the wire format is shared). It returns an error when the
// password is wrong or the payload was corrupted/tampered (GCM auth-tag
// failure), mirroring decryptFile() in the TS lib.
func DecryptFile(data []byte, password string) ([]byte, error) {
	if password == "" {
		return nil, ErrEmptyPassword
	}
	if len(data) < minLength {
		return nil, fmt.Errorf(
			"Input is too short to be an encrypted file (needs at least %d bytes: salt + IV + auth tag).",
			minLength,
		)
	}

	salt := data[:SaltLength]
	iv := data[SaltLength : SaltLength+IVLength]
	ciphertext := data[SaltLength+IVLength:]

	key := pbkdf2Key([]byte(password), salt, Iterations, 32)
	aead, err := gcm(key)
	if err != nil {
		return nil, fmt.Errorf("initializing AES-256-GCM: %w", err)
	}
	plaintext, err := aead.Open(nil, iv, ciphertext, nil)
	if err != nil {
		// A GCM auth-tag failure means the key did not match (wrong password)
		// or the payload was modified after encryption.
		return nil, ErrDecrypt
	}
	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 →