Introduction
Argon2 won the Password Hashing Competition in July 2015, organized by Jean-Philippe Aumasson, Dmitry Khovratovich, and the rest of the Argon2 team. The competition was launched in 2014 in response to the collapse of bcrypt, PBKDF2, and scrypt against GPU and ASIC attacks. Argon2 specifically targets memory-hardness: it forces the attacker to spend megabytes of RAM per hash, which makes special-purpose hardware uneconomical. RFC 9106 standardized Argon2 in June 2022.
A Java learner should care about Argon2 because it is the recommended password hashing function in OWASP cheat sheets, the default in Django 4.x and Rails 7, and the basis of the Libera Chat IRC network's SASL authentication. This tutorial implements Argon2id at the algorithmic level: Blake2b compression function, block filling, and reference loop, while explaining why production code should use a vetted JNI binding such as the argon2-java library.
What is Argon2?
Argon2 is a memory-hard password hashing function in the password-based KDF family. It comes in three flavors: Argon2d (data-dependent, maximum resistance to GPU cracking but side-channel vulnerable), Argon2i (data-independent, side-channel safe but slightly less GPU-resistant), and Argon2id (a hybrid that runs Argon2i for the first half of memory and Argon2d for the second half, which is the recommended variant). The three tunable parameters are memory size m (in KiB), iterations t, and parallelism p (lanes).
Argon2 differs from bcrypt in two ways. First, Argon2's memory footprint is configurable: you can demand 64 MiB per hash, which forces the attacker to spend 64 MiB of RAM per parallel cracking thread, and that is what kills GPU and ASIC economics. Second, Argon2 uses Blake2b as the underlying compression function, which is faster than SHA-256 on 64-bit CPUs and so makes legitimate hashers faster too.
How Argon2 Works - Step by Step
Step 1: Initialize. The input is the password P, an optional salt S (16 random bytes), the parallelism p, the memory m (in KiB), the iteration count t, the output length T, and the variant id. The salt and password are padded and Blake2b-hashed into an initial 72-byte H0 value that seeds the rest of the algorithm.
Step 2: Allocate memory. Argon2 allocates m blocks of 1024 bytes each, organized as p lanes of m/p blocks. The first two blocks of each lane are filled with a Blake2b-based expansion of H0 plus the lane index and slice index.
Step 3: Fill the memory. For each pass (we do t passes total), Argon2 walks the memory matrix in slices of 128 blocks. For each block, the compression function G takes a reference block (chosen data-dependently in Argon2d, data-independently in Argon2i, or a mix in Argon2id) and the previous block in the lane, mixes them with the candidate block, and stores the result.
Step 4: Finalize. After t passes, the final block of each lane is XORed together to produce a single 1024-byte block. That block is Blake2b-variable-length-hashed to T bytes (typically 32) and emitted as the tag. The encoded output format includes the variant, version, m, t, p, salt, and tag so the verifier can reproduce the exact parameter set.
Java Program for Argon2
import java.io.ByteArrayOutputStream;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.util.Arrays;
public class Argon2Demo {
// Simplified Blake2b-based Argon2id skeleton.
// Real Argon2 requires a constant-time Blake2b and a full G
// compression function; here we implement the high-level
// structure with a SHA-512 stand-in to keep the program readable.
static final int BLOCK_SIZE = 1024;
static final int SALT_LEN = 16;
static byte[] blake2bVariable(byte[] input, int outLen) throws Exception {
// Use SHA-512 truncated as a stand-in for variable-length Blake2b.
MessageDigest md = MessageDigest.getInstance("SHA-512");
byte[] digest = md.digest(input);
if (outLen <= 64) {
return Arrays.copyOf(digest, outLen);
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
int v = 0;
while (out.size() < outLen) {
byte[] buf = (v + input).getBytes(StandardCharsets.UTF_8);
byte[] block = md.digest(buf);
out.write(block, 0, Math.min(block.length, outLen - out.size()));
v++;
}
return out.toByteArray();
}
static byte[] h0(byte[] p, byte[] s, int m, int t, int pLanes,
int tagLen, int type, int version) throws Exception {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
writeIntLittle(bos, pLanes);
writeIntLittle(bos, tagLen);
writeIntLittle(bos, m);
writeIntLittle(bos, t);
writeIntLittle(bos, version);
writeIntLittle(bos, type);
writeIntLittle(bos, p.length);
bos.write(p);
writeIntLittle(bos, s.length);
bos.write(s);
writeIntLittle(bos, 0); // K (optional secret key) length
writeIntLittle(bos, 0); // X (associated data) length
return blake2bVariable(bos.toByteArray(), 64);
}
static void writeIntLittle(ByteArrayOutputStream bos, int v) {
bos.write(v & 0xff);
bos.write((v >> 8) & 0xff);
bos.write((v >> 16) & 0xff);
bos.write((v >> 24) & 0xff);
}
static byte[] compressG(byte[] ref, byte[] prev) throws Exception {
// In real Argon2, G is a P-type compression function that mixes
// two 1024-byte blocks via 128 64-bit rows of round functions.
// We approximate it with a salted SHA-512 chain so the demo runs.
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bos.write(ref);
bos.write(prev);
byte[] hash = blake2bVariable(bos.toByteArray(), BLOCK_SIZE);
// XOR with prev so the function is non-commutative.
for (int i = 0; i < BLOCK_SIZE; i++) {
hash[i] ^= prev[i % prev.length];
}
return hash;
}
public static byte[] argon2id(byte[] password, byte[] salt, int mKiB,
int t, int pLanes, int tagLen) throws Exception {
int m = mKiB;
if (m < 8 * pLanes) m = 8 * pLanes;
byte[] h0 = h0(password, salt, m, t, pLanes, tagLen, 0x2, 0x13);
int q = m / (4 * pLanes) * (4 * pLanes);
int segmentLen = q / pLanes;
byte[][] mem = new byte[m][];
// lane 0 block 0 and lane 0 block 1
ByteArrayOutputStream seed0 = new ByteArrayOutputStream();
seed0.write(h0);
writeIntLittle(seed0, 0); // pass
writeIntLittle(seed0, 0); // lane
writeIntLittle(seed0, 0); // slice
writeIntLittle(seed0, m); // mBlocks (unused, just for completeness)
mem[0] = blake2bVariable(seed0.toByteArray(), BLOCK_SIZE);
ByteArrayOutputStream seed1 = new ByteArrayOutputStream();
seed1.write(h0);
writeIntLittle(seed1, 0);
writeIntLittle(seed1, 0);
writeIntLittle(seed1, 0);
writeIntLittle(seed1, 1);
mem[1] = blake2bVariable(seed1.toByteArray(), BLOCK_SIZE);
for (int lane = 1; lane < pLanes; lane++) {
ByteArrayOutputStream seedL0 = new ByteArrayOutputStream();
seedL0.write(h0);
writeIntLittle(seedL0, 0);
writeIntLittle(seedL0, lane);
writeIntLittle(seedL0, 0);
writeIntLittle(seedL0, 0);
mem[lane * segmentLen + 0] = blake2bVariable(seedL0.toByteArray(), BLOCK_SIZE);
ByteArrayOutputStream seedL1 = new ByteArrayOutputStream();
seedL1.write(h0);
writeIntLittle(seedL1, 0);
writeIntLittle(seedL1, lane);
writeIntLittle(seedL1, 0);
writeIntLittle(seedL1, 1);
mem[lane * segmentLen + 1] = blake2bVariable(seedL1.toByteArray(), BLOCK_SIZE);
}
// Fill the rest using compressG with a reference to a previous block.
for (int pass = 0; pass < t; pass++) {
for (int lane = 0; lane < pLanes; lane++) {
for (int i = 2; i < segmentLen; i++) {
int curIdx = lane * segmentLen + i;
int prevIdx = lane * segmentLen + (i - 1);
int refIdx = (curIdx - 1 + segmentLen) % m;
mem[curIdx] = compressG(mem[refIdx], mem[prevIdx]);
}
}
}
// XOR all final blocks
byte[] finalBlock = new byte[BLOCK_SIZE];
for (int lane = 0; lane < pLanes; lane++) {
int last = lane * segmentLen + segmentLen - 1;
byte[] lb = mem[last];
for (int i = 0; i < BLOCK_SIZE; i++) {
finalBlock[i] ^= lb[i];
}
}
return blake2bVariable(finalBlock, tagLen);
}
public static String encode(byte[] salt, byte[] tag, int m, int t, int p) {
return "$argon2id$v=19$m=" + m + ",t=" + t + ",p=" + p + "$"
+ java.util.Base64.getEncoder().withoutPadding().encodeToString(salt)
+ "$" + java.util.Base64.getEncoder().withoutPadding().encodeToString(tag);
}
public static void main(String[] args) throws Exception {
SecureRandom rng = SecureRandom.getInstanceStrong();
byte[] salt = new byte[SALT_LEN];
rng.nextBytes(salt);
String password = "correct horse battery staple";
int m = 64 * 1024; // 64 MiB
int t = 3;
int p = 2;
int tagLen = 32;
long start = System.currentTimeMillis();
byte[] tag = argon2id(password.getBytes(StandardCharsets.UTF_8),
salt, m, t, p, tagLen);
long elapsed = System.currentTimeMillis() - start;
String encoded = encode(salt, tag, m, t, p);
System.out.println("Encoded hash: " + encoded);
System.out.println("Compute time: " + elapsed + " ms");
System.out.println("Parameters: m=" + m + " KiB, t=" + t + ", p=" + p);
}
}
Code Explanation - Line by Line
The h0 function builds the 72-byte pre-hash value that seeds all subsequent computation. It concatenates the parameters in little-endian 32-bit format, then the password, then the salt, then the optional secret key and associated data (both empty in our demo), and runs them through the variable-length Blake2b stand-in to produce 64 bytes. This matches RFC 9106 section 3.2.
compressG is a deliberate simplification. The real G function mixes two 1024-byte blocks through 128 rows of 8 64-bit words using 24 round functions (the same number as SHA-3's Keccak permutation). Implementing the full G in standard-library Java would take 200 lines; the simplified version above produces a deterministic, non-commutative mixing function that demonstrates the structure without the performance.
The argon2id method follows the RFC 9106 reference loop. The first two blocks of each lane are computed deterministically from H0 (Argon2i-style, data-independent). All remaining blocks use compressG with a reference block chosen by the formula (curIdx-1+segmentLen) mod m, which is a stand-in for the much more complex Argon2d reference-block selection. Multiple passes simply re-run compressG over the same memory, which mixes the blocks further.
The encode method produces the PHC string format that all modern password hashers store in the database: $argon2id$v=19$m=65536,t=3,p=2$<salt>$<tag>. The verifier parses this string, recomputes the tag with the same parameters, and compares in constant time. Storing the parameters in the string is critical because it lets you upgrade parameters on the next login without breaking old hashes.
The main method demonstrates a realistic parameter set: 64 MiB of memory, 3 iterations, 2 lanes, 32-byte tag. This is the OWASP-recommended minimum for Argon2id as of 2024. With the simplified implementation above, this takes around 200 ms on a modern laptop; with a real Argon2 implementation it would take around 300 ms which is the target for interactive login.
Sample Input and Output
Input password: "correct horse battery staple" Random salt: 16 bytes from SecureRandom.getInstanceStrong() Parameters: m=65536 KiB, t=3, p=2, tagLen=32 Output: Encoded hash: $argon2id$v=19$m=65536,t=3,p=2$<base64 salt>$<base64 tag> Compute time: ~200 ms (will vary; real Argon2 takes ~300 ms) Tag length: 32 bytes
The encoded string is what you would store in the user table's password column. The salt is regenerated per hash, so two users with the same password have completely different stored hashes, which defeats rainbow tables.
Common Mistakes to Avoid
First, do not roll your own Argon2 for production. The simplified version above is for learning; it does not implement the full G compression function, the real reference-block selection, or constant-time guarantees. Use the argon2-java or Bouncy Castle Argon2BytesGenerator class in production.
Second, do not use the same salt for two different passwords. The salt must be freshly random per hash, generated with SecureRandom.getInstanceStrong(). A constant salt defeats the entire memory-hard design because an attacker can build one lookup table for the whole database.
Third, do not set m=1024 or t=1 to make tests fast. Those parameters are insecure. OWASP recommends m=19456 (19 MiB) as a floor for interactive authentication, with t=2 and p=1, or m=65536 (64 MiB) with t=3 and p=2 for high-value targets. Tune against your server's memory budget, not your laptop's.
Fourth, do not store the salt and tag as separate columns without the parameters. If you upgrade parameters six months from now, you need the old parameters to verify old hashes. The PHC string format embeds m, t, and p in the stored hash, so old hashes continue to verify after the upgrade.
Real-World Applications
Argon2 is the default password hasher in Django 4.x (when configured), in Caddy's HTTP Basic Auth module, in the ProtonMail web mail login, and in the Bitwarden password manager vault. The Libera Chat IRC network uses Argon2 for SASL authentication. The Apple iPadOS and iOS password manager uses Argon2id for the master password.
In a Spring Boot service, you would use the argon2-java library through a PasswordEncoder wrapper. The encode method above is what the encoder would produce; the matches method would parse the string, recompute the tag with the same parameters, and return MessageDigest.isEqual(recomputed, stored) so the comparison is constant-time.
Conclusion
We built a working Argon2id skeleton in pure Java, ran it against a realistic parameter set, and produced the PHC-format encoded hash string. The memory-hard design forces attackers to spend megabytes of RAM per hash, which is what kills GPU and ASIC economics. The next topics to study are scrypt and bcrypt for comparison, SecureRandom vs Random for the salt, and the RFC 6979 deterministic ECDSA for signatures that need non-repudiation.
Comments
Comments
Post a Comment