Skip to content

Text Encryptor — Go source

Encrypt or decrypt text with a password using AES-256-GCM. Share the ciphertext safely - only someone with the password can read it.

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

// Package textencryptor ports src/lib/text-encryptor.ts (dual source: the web
// lib is TypeScript, the CLI lib is Go — kept in lock-step). Pure logic, never
// panics — invalid input returns an error. The table-driven tests in
// text_encryptor_test.go share vectors with src/lib/text-encryptor.test.ts so
// the two implementations are held to the same contract.
//
// Format (byte-for-byte compatible with the Web Crypto original): PBKDF2
// (SHA-256, 100k iterations, 16-byte random salt) derives an AES-256 key from
// the password; AES-GCM encrypts with a 12-byte random IV and a 16-byte tag.
// The canonical Base64 output packs salt + IV + ciphertext (+ tag), so every
// encryption is unique and self-contained — a string sealed by either twin
// decrypts under the other.
package textencryptor

import (
	"crypto/aes"
	"crypto/cipher"
	"crypto/hmac"
	"crypto/rand"
	"crypto/sha256"
	"encoding/base64"
	"encoding/binary"
	"errors"
	"fmt"
	"strings"
	"unicode"
)

const (
	pbkdf2Iterations = 100_000
	saltBytes        = 16
	ivBytes          = 12
	// minBytes is the smallest valid packed payload: salt + IV + one AES-GCM
	// block (tag). Mirrors MIN_BYTES in the TS lib.
	minBytes = saltBytes + ivBytes + 16
	keyBytes = 32 // AES-256
)

// base64Alphabet is the canonical Base64 alphabet, same as ALPHABET in the TS.
const base64Alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"

// stripWhitespace removes every whitespace rune, mirroring the TS codec's
// b64.replace(/\s+/g, '') tolerance for wrapped ciphertext.
func stripWhitespace(s string) string {
	var b strings.Builder
	b.Grow(len(s))
	for _, r := range s {
		if unicode.IsSpace(r) {
			continue
		}
		b.WriteRune(r)
	}
	return b.String()
}

// base64ToBytes decodes canonical Base64. It accepts surrounding (and interior)
// whitespace; it errors on any other non-alphabet character, a length that is
// not a multiple of 4, or misplaced padding — the same checks, in the same
// order, as base64ToBytes in the TS lib.
func base64ToBytes(b64 string) ([]byte, error) {
	clean := stripWhitespace(b64)
	if clean == "" {
		return nil, errors.New("Invalid Base64: input is empty")
	}
	if len(clean)%4 != 0 {
		return nil, errors.New("Invalid Base64: length must be a multiple of 4")
	}
	// ^[A-Za-z0-9+/]+={0,2}$ — at least one data char, padding only at the end,
	// and every data char from the canonical alphabet.
	n := len(clean)
	data := strings.TrimRight(clean, "=")
	if data == "" || len(data) < n-2 || strings.ContainsRune(data, '=') {
		bad := rune('?')
		for _, r := range clean {
			if !strings.ContainsRune(base64Alphabet, r) && r != '=' {
				bad = r
				break
			}
		}
		return nil, fmt.Errorf("Invalid Base64: unexpected character %q", bad)
	}
	for _, r := range data {
		if !strings.ContainsRune(base64Alphabet, r) {
			return nil, fmt.Errorf("Invalid Base64: unexpected character %q", r)
		}
	}
	// StdEncoding (non-strict) ignores non-canonical trailing bits, matching
	// the TS hand decoder's leniency.
	return base64.StdEncoding.DecodeString(clean)
}

// pbkdf2SHA256 derives keyLen bytes from password and salt via PBKDF2 with
// HMAC-SHA256 (RFC 8018). It replaces the TS lib's crypto.subtle.deriveKey so
// this package stays stdlib-only on Go 1.22, and produces identical output.
func pbkdf2SHA256(password string, salt []byte, iterations, keyLen int) []byte {
	mac := hmac.New(sha256.New, []byte(password))
	hashLen := sha256.Size
	blocks := (keyLen + hashLen - 1) / hashLen
	out := make([]byte, 0, blocks*hashLen)
	var counter [4]byte
	u := make([]byte, 0, hashLen)
	for block := 1; block <= blocks; block++ {
		mac.Reset()
		mac.Write(salt)
		binary.BigEndian.PutUint32(counter[:], uint32(block))
		mac.Write(counter[:])
		u = mac.Sum(u[:0])
		t := make([]byte, hashLen)
		copy(t, u)
		for i := 1; i < iterations; i++ {
			mac.Reset()
			mac.Write(u)
			u = mac.Sum(u[:0])
			for j := range t {
				t[j] ^= u[j]
			}
		}
		out = append(out, t...)
	}
	return out[:keyLen]
}

// deriveKey runs PBKDF2-SHA256 (100k iterations) and returns a 32-byte AES-256
// key. Mirrors deriveKey() in the TS lib.
func deriveKey(password string, salt []byte) []byte {
	return pbkdf2SHA256(password, salt, pbkdf2Iterations, keyBytes)
}

// EncryptText encrypts UTF-8 plaintext under password and returns the Base64
// string packing salt + IV + AES-256-GCM ciphertext. It is the Go twin of
// encryptText() in src/lib/text-encryptor.ts: same packed format, same errors
// on empty plaintext or password. Every call draws a fresh salt and IV.
func EncryptText(plaintext, password string) (string, error) {
	if plaintext == "" {
		return "", errors.New("Nothing to encrypt: input is empty")
	}
	if password == "" {
		return "", errors.New("Password must not be empty")
	}
	salt := make([]byte, saltBytes)
	iv := make([]byte, ivBytes)
	if _, err := rand.Read(salt); err != nil {
		return "", fmt.Errorf("failed to read random salt: %w", err)
	}
	if _, err := rand.Read(iv); err != nil {
		return "", fmt.Errorf("failed to read random IV: %w", err)
	}
	key := deriveKey(password, salt)
	gcm, err := newGCM(key)
	if err != nil {
		return "", err
	}
	packed := make([]byte, 0, saltBytes+ivBytes+len(plaintext)+16)
	packed = append(packed, salt...)
	packed = append(packed, iv...)
	packed = gcm.Seal(packed, iv, []byte(plaintext), nil)
	return base64.StdEncoding.EncodeToString(packed), nil
}

// DecryptText decrypts a Base64 string produced by EncryptText back to
// plaintext. It is the Go twin of decryptText() in src/lib/text-encryptor.ts:
// tolerant of wrapped whitespace, and erroring on empty input/password,
// invalid Base64, a payload too short to be one of ours, or a GCM
// authentication failure (wrong password / tampered data).
func DecryptText(ciphertext, password string) (string, error) {
	trimmed := strings.TrimSpace(ciphertext)
	if trimmed == "" {
		return "", errors.New("Nothing to decrypt: input is empty")
	}
	if password == "" {
		return "", errors.New("Password must not be empty")
	}
	packed, err := base64ToBytes(trimmed)
	if err != nil {
		return "", err
	}
	if len(packed) < minBytes {
		return "", errors.New("Ciphertext too short - not a valid salt + IV + AES-GCM payload")
	}
	salt := packed[:saltBytes]
	iv := packed[saltBytes : saltBytes+ivBytes]
	data := packed[saltBytes+ivBytes:]
	key := deriveKey(password, salt)
	gcm, err := newGCM(key)
	if err != nil {
		return "", err
	}
	plain, err := gcm.Open(nil, iv, data, nil)
	if err != nil {
		return "", errors.New("Decryption failed - wrong password or corrupted ciphertext")
	}
	return string(plain), nil
}

// newGCM builds the AES-256-GCM AEAD with the standard 12-byte nonce and
// 16-byte tag — the exact parameters Web Crypto's AES-GCM uses.
func newGCM(key []byte) (cipher.AEAD, error) {
	block, err := aes.NewCipher(key)
	if err != nil {
		return nil, fmt.Errorf("failed to initialize AES-256: %w", err)
	}
	gcm, err := cipher.NewGCM(block)
	if err != nil {
		return nil, fmt.Errorf("failed to initialize AES-GCM: %w", err)
	}
	return gcm, 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 →