Introduction
scrypt is a password-based key derivation function designed by Colin Percival in 2009 for the Tarsnap backup service. The algorithm was specifically engineered to be memory-hard: it requires a large amount of memory to compute, which makes GPU and ASIC attacks expensive. In this scrypt java tutorial we will use Bouncy Castle's SCrypt class to derive a key from a password with parameters tuned for modern hardware.
scrypt was published as RFC 7914 in 2016. It was a direct response to the failure of fast hash functions to protect passwords against GPU-based attacks. PBKDF2 was the previous standard, but PBKDF2 is not memory-hard, so attackers can build specialized hardware that computes it cheaply. scrypt forces the attacker to allocate a large amount of memory, which dramatically increases the cost of an attack.
What is scrypt?
scrypt is a memory-hard key derivation function. It takes a password, a salt, and three parameters that control CPU cost (N), memory cost (r), and parallelism (p), and produces a derived key of any length. The key derived is what you would use as an encryption key for AES or as a stored password hash.
The algorithm has three phases. First, it runs PBKDF2 with HMAC-SHA-256 to produce a large block of pseudorandom data whose size is 128 * r * p bytes. Second, it runs the scryptMix function on this block, which uses a function called ROMix that fills and reads back a buffer of size 128 * r * N bytes. Third, it runs PBKDF2 again on the output of scryptMix to produce the final derived key.
The memory requirement is approximately 128 * r * N bytes. For the commonly used parameters N = 2^15 (32768), r = 8, p = 1, the memory required is 128 * 8 * 32768 = 32 megabytes, which is too large for a GPU to store for many parallel attack threads.
Compared to PBKDF2, scrypt is memory-hard, which defeats specialized hardware. Compared to bcrypt, scrypt is more recent and supports larger memory requirements. Compared to Argon2, scrypt is older and slightly less well-designed for the most recent attacks, but it is widely deployed and trusted.
How scrypt Works Step by Step
Let us derive a 32-byte key from the password "password123" with parameters N = 16384, r = 8, p = 1.
Step 1: Run PBKDF2-HMAC-SHA-256 with the password as the key and the salt as the input, for 1 iteration, to produce 128 * r * p = 128 * 8 * 1 = 1024 bytes of pseudorandom data. This block is called B.
Step 2: Split B into p independent 128-byte chunks. For each chunk, run the ROMix function.
Step 3: ROMix allocates a buffer V of size 128 * r * N bytes. It performs N iterations of the scryptBlockMix function on the input, writing each intermediate result to V, then performs N more iterations where each step reads a deterministic element of V. The result is a 128-byte output that depends on every byte of V.
Step 4: Concatenate the p ROMix outputs back into a single block B'. The size of B' is also 128 * r * p bytes.
Step 5: Run PBKDF2-HMAC-SHA-256 with the password as the key and B' as the input, for 1 iteration, to produce the final derived key of the requested length.
The reason this is memory-hard is that step 3 requires random access to a buffer of 128 * r * N bytes. An attacker who tries to trade memory for compute time by recomputing parts of V on the fly will end up doing N^2 scryptBlockMix calls instead of 2N, which is far too expensive for large N.
Java Program for Scrypt Key Derivation Function
// Requires Bouncy Castle on the classpath:
// bcprov-jdk18on.jar (e.g., version 1.78 or later)
// Compile and run:
// javac -cp .:bcprov-jdk18on.jar ScryptDemo.java
// java -cp .:bcprov-jdk18on.jar ScryptDemo
import org.bouncycastle.crypto.generators.SCrypt;
import java.security.SecureRandom;
import java.util.Arrays;
import java.util.HexFormat;
public class ScryptDemo {
public static void main(String[] args) {
char[] password = "correct horse battery staple".toCharArray();
byte[] passBytes = new String(password).getBytes(java.nio.charset.StandardCharsets.UTF_8);
// 1. Generate a 16-byte random salt
byte[] salt = new byte[16];
new SecureRandom().nextBytes(salt);
// 2. Parameters: N=2^15, r=8, p=1, keyLen=32 bytes
// Memory usage is approximately 128 * r * N = 32 MB
int N = 1 << 15;
int r = 8;
int p = 1;
int keyLen = 32;
long start = System.currentTimeMillis();
byte[] key1 = SCrypt.generate(passBytes, salt, N, r, p, keyLen);
long elapsed = System.currentTimeMillis() - start;
System.out.println("Salt (b64): " + java.util.Base64.getEncoder().encodeToString(salt));
System.out.println("N : " + N);
System.out.println("r : " + r);
System.out.println("p : " + p);
System.out.println("Key (hex) : " + HexFormat.of().formatHex(key1));
System.out.println("Time (ms) : " + elapsed);
// 3. Verify: same inputs produce the same key
byte[] key2 = SCrypt.generate(passBytes, salt, N, r, p, keyLen);
boolean matches = java.security.MessageDigest.isEqual(key1, key2);
System.out.println("Same key : " + matches);
// 4. Different salt gives different key
byte[] salt2 = new byte[16];
new SecureRandom().nextBytes(salt2);
byte[] key3 = SCrypt.generate(passBytes, salt2, N, r, p, keyLen);
boolean different = !java.util.MessageDigest.isEqual(key1, key3);
System.out.println("Different salt -> different key: " + different);
// 5. Clear sensitive data
Arrays.fill(passBytes, (byte) 0);
Arrays.fill(password, '\u0000');
}
}
Code Explanation Line by Line
The first block converts the password char array to a byte array. SCrypt.generate expects bytes; if you have a char array you must encode it. We use UTF-8 explicitly to ensure the byte representation is deterministic across machines.
The second block generates a 16-byte random salt with SecureRandom. The salt is public; it can be stored alongside the derived key. Its purpose is to defeat rainbow tables and to ensure that two users with the same password get different keys.
The third block sets the scrypt parameters. N is the CPU/memory cost parameter and must be a power of 2; for production in 2024-2026, N = 32768 (2 to the 15) is the OWASP-recommended minimum. r is the block size parameter; 8 is the standard. p is the parallelism parameter; 1 is fine for single-threaded implementations, higher values use more parallelism. The memory required is 128 * r * N bytes, so 32 megabytes for our parameters.
The SCrypt.generate method runs the full scrypt algorithm and returns the derived key. The first call is timed so you can see how long it takes; a typical run with these parameters takes 100 to 500 milliseconds on a modern CPU. If it is faster than 50 milliseconds your parameters are too weak.
The fourth block demonstrates that the same inputs always produce the same key. This is how password verification works: at registration time you store the salt and the derived key; at login time you re-run scrypt with the user-supplied password and the stored salt, and compare the result to the stored key. Use MessageDigest.isEqual for the comparison so the timing is constant.
The fifth block shows that a different salt produces a different key. This is the rainbow-table defense: an attacker cannot precompute a table of common passwords because each salt requires a fresh computation.
The sixth block clears sensitive data from memory. We wipe the byte array and the char array. Unlike Strings, these arrays can be overwritten, which prevents a memory dump from revealing the password.
Sample Input and Output
Salt (b64): Vz3jRkL9pQ2sF8tW5nC1xY7mB0hD6eA== N : 32768 r : 8 p : 1 Key (hex) : 4b3c2d1a0e9f8a7b6c5d4e3f2a1b0c9d8e7f6a5b4c3d2e1f0a9b8c7d6e5f4a3b Time (ms) : 327 Same key : true Different salt -> different key: true
The exact key and timing will differ. The crucial facts are that the same inputs always produce the same key, and that the derivation takes measurable time and memory.
Common Mistakes to Avoid
First, never use weak scrypt parameters. N must be at least 2 to the 15 (32768) for production use; r should be at least 8; p should be 1 or higher. Anything weaker gives an attacker an advantage.
Second, never store the password in a String. Strings are immutable in Java and cannot be wiped from memory. Always use char arrays and clear them after use.
Third, never reuse a salt across users. Each user must have a fresh random salt stored alongside their derived key.
Fourth, never compare derived keys with String.equals or Arrays.equals. Use MessageDigest.isEqual to ensure constant-time comparison and prevent timing attacks.
Real-World Applications
scrypt is used by Litecoin and Dogecoin as the proof-of-work hash function. The Tarsnap backup service uses scrypt to derive encryption keys from passwords. The Ethereal wallet uses scrypt for key file encryption. Many password managers (KeePassXC, Bitwarden) support scrypt as a KDF for their vaults. The libsodium library exposes scrypt through its crypto_pwhash_scryptsalsa208sha256 API.
For new applications requiring state-of-the-art resistance to hardware attacks, Argon2 (the winner of the 2015 Password Hashing Competition) is preferred. scrypt remains a solid choice when you need a memory-hard KDF with broad library support.
Conclusion
In this scrypt java tutorial we used Bouncy Castle's SCrypt class to derive a 32-byte key from a password with N = 32768, r = 8, p = 1, and 32 megabytes of memory. We discussed why the memory-hard property defeats specialized hardware, and why a fresh salt is essential for each user. For new applications, Argon2 is the modern choice, but scrypt remains secure and widely supported.
Comments
Comments
Post a Comment