How to generate an AES key in Java

Generate a cryptographically random AES key in Java for encrypting data at rest or in transit. Use the browser AES Key Generator to create AES-128/192/256 keys as hex or Base64, then encrypt with javax.crypto KeyGenerator (prefer AES-GCM). AES keys are not JWT signing secrets — use the JWT Secret Generator for HS256.

Last updated August 26, 2026

Steps

  1. 1

    Open the AES Key Generator and select AES-256 (recommended for new apps).

  2. 2

    Generate and copy the hex or Base64 key — all randomness stays in your browser.

  3. 3

    In Java, load that key (or create one with javax.crypto KeyGenerator) and encrypt with an AEAD mode such as AES-256-GCM.

  4. 4

    Persist the key in a secrets manager; never hardcode it in source or mobile apps.

  5. 5

    Rotate keys on a schedule and keep nonces/IVs unique per encryption.

Code Example

Java
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.GCMParameterSpec;
import java.security.SecureRandom;
import java.util.Base64;

KeyGenerator kg = KeyGenerator.getInstance("AES");
kg.init(256);
SecretKey key = kg.generateKey();

byte[] iv = new byte[12];
new SecureRandom().nextBytes(iv);
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
cipher.init(Cipher.ENCRYPT_MODE, key, new GCMParameterSpec(128, iv));
byte[] ciphertext = cipher.doFinal("secret data".getBytes());

System.out.println(Base64.getEncoder().encodeToString(key.getEncoded()));
Open AES Key Generator

Other languages

Related Articles

Frequently Asked Questions

Which AES key size should I use?

AES-256 is recommended for new systems. AES-128 remains secure for many workloads, but 256-bit gives a larger long-term margin.

How do I encrypt with an AES key in Java?

Use javax.crypto KeyGenerator with an AEAD mode (AES-GCM). Generate a fresh nonce/IV per message, keep the key secret, and authenticate associated data when your protocol needs it.

Is AES the same as JWT signing?

No. JWT HS256/RS256 signs tokens; AES encrypts payloads or stored data. Encrypted JWTs use JWE, which is a separate format from typical signed JWTs.

Hex or Base64 for storing AES keys?

Either works. Hex is easy to diff in configs; Base64 is more compact. Prefer a secrets manager over plain env files when possible.