Skip to content

Age File Encryption — Java source

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

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

// Age File Encryption — passphrase-based file encryption in the spirit of the
// age format (age-encryption.org/v1): one simple, explicit, authenticated
// envelope instead of PGP's web of signatures, key packets, and config.
//
// Language: Java (17+, standard library only)
// Ported from src/lib/age-encryption.ts
// display source — part of CosmoDev's polyglot tool pages.
//
// age's passphrase mode wraps a file key with an scrypt-derived key; this
// implementation delivers the same security properties with JDK primitives:
// PBKDF2-SHA256 (100k iterations) key stretching, a fresh random salt per
// encryption, and AES-256-GCM authenticated encryption. 100% local.
//
// Wire format (age-style header + body):
//   "cosmodev-age-v1" (15 B ASCII magic) || salt (16 B) || IV (12 B)
//   || AES-256-GCM ciphertext + tag (16 B)

import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.SecureRandom;

public final class AgeEncryption {

    public static final String AGE_HEADER = "cosmodev-age-v1";
    public static final int SALT_LENGTH = 16;
    public static final int IV_LENGTH = 12;
    public static final int ITERATIONS = 100_000;

    private static final byte[] HEADER_BYTES = AGE_HEADER.getBytes(java.nio.charset.StandardCharsets.US_ASCII);
    private static final int HEADER_LENGTH = HEADER_BYTES.length; // 15

    // GCM appends a 16-byte auth tag to the ciphertext; the smallest possible
    // encrypted payload is therefore header + salt + IV + tag = 59 bytes.
    private static final int TAG_LENGTH = 16;
    private static final int OVERHEAD = HEADER_LENGTH + SALT_LENGTH + IV_LENGTH + TAG_LENGTH;

    private static final SecureRandom RANDOM = new SecureRandom();

    private AgeEncryption() {
    }

    /** True when {@code data} starts with the cosmodev-age-v1 magic header. */
    public static boolean isAgeEncrypted(byte[] data) {
        if (data.length < HEADER_LENGTH) {
            return false;
        }
        for (int i = 0; i < HEADER_LENGTH; i++) {
            if (data[i] != HEADER_BYTES[i]) {
                return false;
            }
        }
        return true;
    }

    private static SecretKeySpec deriveKey(char[] passphrase, byte[] salt) throws Exception {
        PBEKeySpec spec = new PBEKeySpec(passphrase, salt, ITERATIONS, 256);
        SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
        byte[] keyBytes = factory.generateSecret(spec).getEncoded();
        spec.clearPassword();
        return new SecretKeySpec(keyBytes, "AES");
    }

    /** Encrypt {@code data} under {@code passphrase}. Returns header || salt || IV || ciphertext+tag. */
    public static byte[] ageEncrypt(byte[] data, String passphrase) throws Exception {
        if (passphrase.isEmpty()) {
            throw new IllegalArgumentException("Passphrase must not be empty.");
        }
        if (data.length == 0) {
            throw new IllegalArgumentException("Input data is empty - nothing to encrypt.");
        }
        byte[] salt = new byte[SALT_LENGTH];
        byte[] iv = new byte[IV_LENGTH];
        RANDOM.nextBytes(salt);
        RANDOM.nextBytes(iv);

        SecretKeySpec key = deriveKey(passphrase.toCharArray(), salt);
        Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
        cipher.init(Cipher.ENCRYPT_MODE, key, new GCMParameterSpec(128, iv));
        byte[] ciphertext = cipher.doFinal(data);

        byte[] out = new byte[HEADER_LENGTH + SALT_LENGTH + IV_LENGTH + ciphertext.length];
        System.arraycopy(HEADER_BYTES, 0, out, 0, HEADER_LENGTH);
        System.arraycopy(salt, 0, out, HEADER_LENGTH, SALT_LENGTH);
        System.arraycopy(iv, 0, out, HEADER_LENGTH + SALT_LENGTH, IV_LENGTH);
        System.arraycopy(ciphertext, 0, out, HEADER_LENGTH + SALT_LENGTH + IV_LENGTH, ciphertext.length);
        return out;
    }

    /**
     * Decrypt a payload produced by {@link #ageEncrypt}. Throws when the data
     * lacks the cosmodev-age-v1 header, the passphrase is wrong, or the payload
     * was corrupted/tampered (GCM auth-tag failure).
     */
    public static byte[] ageDecrypt(byte[] data, String passphrase) throws Exception {
        if (passphrase.isEmpty()) {
            throw new IllegalArgumentException("Passphrase must not be empty.");
        }
        if (!isAgeEncrypted(data)) {
            throw new IllegalArgumentException(
                    "Not an age-encrypted file (missing cosmodev-age-v1 header).");
        }
        if (data.length < OVERHEAD) {
            throw new IllegalArgumentException("Input is too short to be an age-encrypted file"
                    + " (needs at least " + OVERHEAD + " bytes: header + salt + IV + auth tag).");
        }
        int body = HEADER_LENGTH;
        byte[] salt = java.util.Arrays.copyOfRange(data, body, body + SALT_LENGTH);
        byte[] iv = java.util.Arrays.copyOfRange(data, body + SALT_LENGTH, body + SALT_LENGTH + IV_LENGTH);
        byte[] ciphertext = java.util.Arrays.copyOfRange(
                data, body + SALT_LENGTH + IV_LENGTH, data.length);

        SecretKeySpec key = deriveKey(passphrase.toCharArray(), salt);
        Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
        cipher.init(Cipher.DECRYPT_MODE, key, new GCMParameterSpec(128, iv));
        try {
            return cipher.doFinal(ciphertext);
        } catch (Exception e) {
            throw new IllegalArgumentException(
                    "Decryption failed: wrong passphrase or corrupted file.", e);
        }
    }
}

Also available in 8 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 →