Skip to content

Text Encryptor — Java 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 Java implementation — the same logic the interactive tool runs, in a shareable, citable form.

// Text Encryptor — password-based AES-256-GCM text encryption.
//
// Language: Java (17+, standard library only)
// Ported from src/lib/text-encryptor.ts
// display source — part of CosmoDev's polyglot tool pages.
//
// Format: 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.
// The Base64 output packs salt + IV + ciphertext (+ GCM tag), so every
// encryption is unique and self-contained — decrypt needs only the string and
// the password. The JDK's javax.crypto replaces the browser's SubtleCrypto.

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;
import java.util.Base64;

public final class TextEncryptor {

    private static final int PBKDF2_ITERATIONS = 100_000;
    private static final int SALT_BYTES = 16;
    private static final int IV_BYTES = 12;
    /** Smallest valid packed payload: salt + IV + one AES-GCM block (tag). */
    private static final int MIN_BYTES = SALT_BYTES + IV_BYTES + 16;

    private static final SecureRandom RANDOM = new SecureRandom();

    private TextEncryptor() {
    }

    /** PBKDF2-SHA256 (100k iterations) -> a raw AES-256 key. */
    private static SecretKeySpec deriveKey(char[] password, byte[] salt) throws Exception {
        PBEKeySpec spec = new PBEKeySpec(password, salt, PBKDF2_ITERATIONS, 256);
        SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
        byte[] keyBytes = factory.generateSecret(spec).getEncoded();
        spec.clearPassword();
        return new SecretKeySpec(keyBytes, "AES");
    }

    /**
     * Encrypt UTF-8 {@code plaintext} under {@code password} and return the Base64
     * string packing salt + IV + AES-256-GCM ciphertext. Throws if either input
     * is empty.
     */
    public static String encryptText(String plaintext, String password) throws Exception {
        if (plaintext.isEmpty()) {
            throw new IllegalArgumentException("Nothing to encrypt: input is empty");
        }
        if (password.isEmpty()) {
            throw new IllegalArgumentException("Password must not be empty");
        }
        byte[] salt = new byte[SALT_BYTES];
        byte[] iv = new byte[IV_BYTES];
        RANDOM.nextBytes(salt);
        RANDOM.nextBytes(iv);

        SecretKeySpec key = deriveKey(password.toCharArray(), salt);
        Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
        cipher.init(Cipher.ENCRYPT_MODE, key, new GCMParameterSpec(128, iv));
        byte[] ciphertext = cipher.doFinal(plaintext.getBytes(java.nio.charset.StandardCharsets.UTF_8));

        byte[] packed = new byte[SALT_BYTES + IV_BYTES + ciphertext.length];
        System.arraycopy(salt, 0, packed, 0, SALT_BYTES);
        System.arraycopy(iv, 0, packed, SALT_BYTES, IV_BYTES);
        System.arraycopy(ciphertext, 0, packed, SALT_BYTES + IV_BYTES, ciphertext.length);
        return Base64.getEncoder().encodeToString(packed);
    }

    /**
     * Decrypt a Base64 string produced by {@link #encryptText} back to plaintext.
     * Throws on empty input/password, invalid Base64, a payload too short to be
     * one of ours, or a GCM authentication failure (wrong password / tampered
     * data).
     */
    public static String decryptText(String ciphertext, String password) throws Exception {
        if (ciphertext.trim().isEmpty()) {
            throw new IllegalArgumentException("Nothing to decrypt: input is empty");
        }
        if (password.isEmpty()) {
            throw new IllegalArgumentException("Password must not be empty");
        }
        byte[] packed;
        try {
            packed = Base64.getDecoder().decode(ciphertext.replaceAll("\\s+", ""));
        } catch (IllegalArgumentException e) {
            throw new IllegalArgumentException("Invalid Base64: " + e.getMessage(), e);
        }
        if (packed.length < MIN_BYTES) {
            throw new IllegalArgumentException(
                    "Ciphertext too short - not a valid salt + IV + AES-GCM payload");
        }
        byte[] salt = java.util.Arrays.copyOfRange(packed, 0, SALT_BYTES);
        byte[] iv = java.util.Arrays.copyOfRange(packed, SALT_BYTES, SALT_BYTES + IV_BYTES);
        byte[] data = java.util.Arrays.copyOfRange(packed, SALT_BYTES + IV_BYTES, packed.length);

        SecretKeySpec key = deriveKey(password.toCharArray(), salt);
        Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
        cipher.init(Cipher.DECRYPT_MODE, key, new GCMParameterSpec(128, iv));
        try {
            byte[] plain = cipher.doFinal(data);
            return new String(plain, java.nio.charset.StandardCharsets.UTF_8);
        } catch (Exception e) {
            throw new IllegalArgumentException(
                    "Decryption failed - wrong password or corrupted ciphertext", 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 →