PBKDF2
- Kotlin course
- Advanced
- Lesson 77/83
- 5 min
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.
Practice 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).
Starter code
import javax.crypto.SecretKeyFactory
import javax.crypto.spec.PBEKeySpec
// in main build PBEKeySpec with password, salt, iteration, size
// generate the key via SecretKeyFactory and print its sizeSample 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)
}Expected output
32
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the SecretKeyFactory getInstance call
val factory = SecretKeyFactory.____("PBKDF2WithHmacSHA256")
val factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256")
Explanation: getInstance selects the algorithm.
2 Match the PBKDF2 parts
| Term | Meaning |
|---|---|
PBEKeySpec |
Derivation settings |
SecretKeyFactory |
Factory |
generateSecret |
Key generation |
1000 |
Iteration |
3 Why is salt used in PBKDF2?
- To speed up
- To shorten the key
- To change the cipher type
- To protect against rainbow tables Correct answer
Explanation: Salt makes the same password yield different keys.