Kotlin
PBKDF2
Learn password hashing with PBKDF2.
Password derivation with PBKDF2
PBKDF2 turns a password into a cryptographic key. SecretKeyFactory works with PBEKeySpec. Salt and iteration count add strength.
Example: val spec = PBEKeySpec("password".toCharArray(), "salt".toByteArray(), 1000, 256); val factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256"); val key = factory.generateSecret(spec).encoded. key.size returns 32. This pattern converts a password to a key safely; it protects against rainbow tables.
PBEKeySpec and iteration
PBEKeySpec takes the password, salt, iteration count and key length. A high iteration slows derivation; it makes brute-force attacks harder.
Example: PBEKeySpec(password, salt, 10000, 256). 10000 iterations slow each attempt by 10000 times. The salt must be unique per user; so the same password yields different derived keys. This pattern is essential for password-based encryption.
Exercise Print key size with PBKDF2
In main create val spec = PBEKeySpec("password".toCharArray(), "salt".toByteArray(), 1000, 256). Take val factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256"). Generate the key with val key = factory.generateSecret(spec).encoded and print println(key.size).
Show example solution
import javax.crypto.SecretKeyFactory
import javax.crypto.spec.PBEKeySpec
fun main() {
val spec = PBEKeySpec("password".toCharArray(), "salt".toByteArray(), 1000, 256)
val factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256")
val key = factory.generateSecret(spec).encoded
println(key.size)
}
Test yourself
-
Complete the SecretKeyFactory getInstance call
val factory = SecretKeyFactory.____("PBKDF2WithHmacSHA256")
Show answer
val factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256")
-
Match the PBKDF2 parts
- PBEKeySpec
- Derivation settings
- SecretKeyFactory
- Factory
- generateSecret
- Key generation
- 1000
- Iteration
-
Why is salt used in PBKDF2?
- To speed up
- To shorten the key
- To change the cipher type
- To protect against rainbow tables
Show answer
To protect against rainbow tables — Salt makes the same password yield different keys.
Next lesson: Summary - Security