Password hashing

suggest change

Never store user passwords as plaintext, and never store them encrypted either. Store a password hash: the output of a function that is one-way, salted and slow on purpose. When a user logs in, you hash the password they typed with the same parameters and compare the result to what you stored.

Your choices on the JVM, roughly from best to acceptable:

Algorithm Where it comes from Notes
Argon2id Bouncy Castle, Spring Security Current OWASP first choice. Memory-hard, so GPUs gain much less
bcrypt at.favre.lib:bcrypt, Spring Security Used for 25 years, still fine. Only the first 72 bytes of the password count
scrypt Bouncy Castle, Spring Security Memory-hard, less common
PBKDF2-HMAC-SHA256 Built into the JDK No dependencies, FIPS-approved. Needs a very high iteration count

This article covers password storage only. For general hashing, HMAC and encryption see Cryptography. For wiring login into a web server see Authentication.


Why SHA-256 is not a password hash

A general-purpose hash such as SHA-256 has two problems when used for passwords:

import java.security.MessageDigest

fun sha256Hex(s: String): String =
    MessageDigest.getInstance("SHA-256")
        .digest(s.toByteArray())
        .joinToString("") { "%02x".format(it) }

fun main() {
    // Two users who picked the same password get the same "hash"
    println("alice: " + sha256Hex("password123"))
    println("bob:   " + sha256Hex("password123"))

    // And it is extremely fast to compute, which helps attackers
    val md = MessageDigest.getInstance("SHA-256")
    val start = System.nanoTime()
    repeat(1_000_000) { md.digest("guess$it".toByteArray()) }
    val ms = (System.nanoTime() - start) / 1_000_000
    println("1,000,000 SHA-256 guesses took $ms ms")
}

Output:

alice: ef92b778bafe771e89245b89ecbc08a44a4e166c06659911881f383d4473e94f
bob:   ef92b778bafe771e89245b89ecbc08a44a4e166c06659911881f383d4473e94f
1,000,000 SHA-256 guesses took 255 ms
  1. No salt: the same password always gives the same hash. An attacker who steals your database can see which users share a password and look hashes up in precomputed tables.
  2. Too fast: a single JVM thread made 4 million guesses per second. A GPU makes billions. Every 8-character password gets cracked.

A password hash fixes both problems. It mixes in a random salt that is unique per user and stored next to the hash. It also has a work factor (iterations, cost or memory) that you tune so that one hash takes tens to hundreds of milliseconds. That's fine for a login and very expensive for someone trying billions of guesses.


PBKDF2 with the JDK only

PBKDF2WithHmacSHA256 is built into every JDK, so it needs no dependencies. OWASP recommends 600,000 iterations for PBKDF2-HMAC-SHA256.

The main design decision is the storage format. Store the algorithm, the parameters and the salt together with the hash in one string. Then you can raise the iteration count later without breaking existing hashes:

import java.security.MessageDigest
import java.security.SecureRandom
import java.util.Base64
import javax.crypto.SecretKeyFactory
import javax.crypto.spec.PBEKeySpec

object Pbkdf2 {
    private const val ALGORITHM = "PBKDF2WithHmacSHA256"
    private const val ITERATIONS = 600_000 // OWASP recommendation for PBKDF2-HMAC-SHA256
    private const val SALT_BYTES = 16
    private const val KEY_BITS = 256

    private val random = SecureRandom()
    private val b64e = Base64.getEncoder().withoutPadding()
    private val b64d = Base64.getDecoder()

    private fun derive(password: CharArray, salt: ByteArray, iterations: Int, bits: Int): ByteArray {
        val spec = PBEKeySpec(password, salt, iterations, bits)
        try {
            return SecretKeyFactory.getInstance(ALGORITHM).generateSecret(spec).encoded
        } finally {
            spec.clearPassword()
        }
    }

    /** Returns a self-describing string: pbkdf2-sha256$iterations$salt$hash */
    fun hash(password: CharArray): String {
        val salt = ByteArray(SALT_BYTES).also { random.nextBytes(it) }
        val dk = derive(password, salt, ITERATIONS, KEY_BITS)
        return "pbkdf2-sha256\$$ITERATIONS\$${b64e.encodeToString(salt)}\$${b64e.encodeToString(dk)}"
    }

    fun verify(password: CharArray, stored: String): Boolean {
        val parts = stored.split('$')
        if (parts.size != 4 || parts[0] != "pbkdf2-sha256") return false
        val iterations = parts[1].toInt()
        val salt = b64d.decode(parts[2])
        val expected = b64d.decode(parts[3])
        val actual = derive(password, salt, iterations, expected.size * 8)
        return MessageDigest.isEqual(expected, actual) // constant-time comparison
    }
}

fun main() {
    val h1 = Pbkdf2.hash("password123".toCharArray())
    val h2 = Pbkdf2.hash("password123".toCharArray())
    println(h1)
    println(h2)
    println("same password, same hash? ${h1 == h2}")
    println("correct password: ${Pbkdf2.verify("password123".toCharArray(), h1)}")
    println("wrong password:   ${Pbkdf2.verify("password124".toCharArray(), h1)}")
}

Output (the salts are random, so yours will differ):

pbkdf2-sha256$600000$pjJjvA9jsBwvPx0+dGB5gQ$SDGNgF4bekuPJ3fzxP/ss/Vq7sSsTLIOL+XaL6fKnGo
pbkdf2-sha256$600000$f0/srB9uttIaVlii0SxTZg$VpyB0dD9a1QSQhk/r86EM0uRBhf8SUZa5w6jVjt+79w
same password, same hash? false
correct password: true
wrong password:   false

Details that matter:


bcrypt

bcrypt puts everything in a standard 60-character string: $2a$ (version), 12$ (cost) and then 22 characters of salt followed by 31 characters of hash. Cost is a power of two, so each +1 doubles the work. Start at 12, or higher if your servers can spare the time.

The at.favre.lib bcrypt library is small and has no dependencies besides its own bytes helper:

// build.gradle.kts
dependencies {
    implementation("at.favre.lib:bcrypt:0.10.2")
}
import at.favre.lib.crypto.bcrypt.BCrypt

fun main() {
    val password = "correct horse battery staple".toCharArray()

    val hash: String = BCrypt.withDefaults().hashToString(12, password)
    println(hash)
    println("length: ${hash.length}")

    val ok = BCrypt.verifyer().verify(password, hash)
    println("verified: ${ok.verified}, cost: ${ok.details.cost}")

    val bad = BCrypt.verifyer().verify("Correct horse battery staple".toCharArray(), hash)
    println("wrong password verified: ${bad.verified}")

    // Malformed hashes don't throw, they report a format error
    val broken = BCrypt.verifyer().verify(password, "not-a-bcrypt-hash")
    println("broken: verified=${broken.verified}, validFormat=${broken.validFormat}")
    println("message: ${broken.formatErrorMessage}")
}

Output:

$2a$12$Gm2keOSy.ZKxehYKXSMgVeiFw0JG7p606nWw9Ri3vLYVBbUotlhwy
length: 60
verified: true, cost: 12
wrong password verified: false
broken: verified=false, validFormat=false
message: hash must start with $ - example of expected hash format: '$2a$06$If6bvum7DFjUnE9p2uDeDu0YHzrHM6tf.iqN8.yx.jNN1ILEf7h0i' which includes 16 bytes salt and 23 bytes hash value encoded in a base64 flavor

The 72-byte limit

bcrypt only uses the first 72 bytes of its input. Some libraries silently drop the rest, so two long passwords with the same 72-byte prefix are treated as equal. at.favre throws instead. If you want to allow long passphrases, use a strategy that pre-hashes them with SHA-512:

import at.favre.lib.crypto.bcrypt.BCrypt
import at.favre.lib.crypto.bcrypt.LongPasswordStrategies

fun main() {
    val long = "x".repeat(100).toCharArray()

    try {
        BCrypt.withDefaults().hashToString(12, long)
    } catch (e: IllegalArgumentException) {
        println("default: ${e.message}")
    }

    // Pre-hash long passwords with SHA-512 so every byte counts
    val strategy = LongPasswordStrategies.hashSha512(BCrypt.Version.VERSION_2A)
    val hasher = BCrypt.with(strategy)
    val verifier = BCrypt.verifyer(BCrypt.Version.VERSION_2A, strategy)

    val hash = hasher.hashToString(12, long)
    val almost = ("x".repeat(99) + "y").toCharArray()
    println("same long password: ${verifier.verify(long, hash).verified}")
    println("differs at char 100: ${verifier.verify(almost, hash).verified}")
}

Output:

default: password must not be longer than 72 bytes plus null terminator encoded in utf-8, was 100
same long password: true
differs at char 100: false

The strategy only applies to passwords that are over the limit, so hashes of short passwords stay standard bcrypt. Hashing and verifying must use the same strategy.


Argon2id with Bouncy Castle

Argon2id won the Password Hashing Competition and is what OWASP recommends today. Its main parameter is memory: each hash needs that much RAM, which makes large-scale cracking on GPUs and ASICs much more expensive. OWASP's minimum is m=19 MiB, t=2, p=1. Any of the equivalent settings work, for example m=46 MiB, t=1.

Bouncy Castle has the raw Argon2 function:

// build.gradle.kts
dependencies {
    implementation("org.bouncycastle:bcprov-jdk18on:1.86")
}

The standard text form is the PHC string $argon2id$v=19$m=...,t=...,p=...$salt$hash, with unpadded Base64. libsodium, Python's argon2-cffi, PHP's password_hash and Spring Security all read and write it, so you can move hashes between stacks:

import org.bouncycastle.crypto.generators.Argon2BytesGenerator
import org.bouncycastle.crypto.params.Argon2Parameters
import java.security.MessageDigest
import java.security.SecureRandom
import java.util.Base64

data class Argon2Config(
    val memoryKiB: Int = 19 * 1024, // 19 MiB
    val iterations: Int = 2,
    val parallelism: Int = 1,
    val saltBytes: Int = 16,
    val hashBytes: Int = 32,
)

class Argon2Hasher(private val cfg: Argon2Config = Argon2Config()) {
    private val random = SecureRandom()
    private val b64e = Base64.getEncoder().withoutPadding()
    private val b64d = Base64.getDecoder()

    private fun raw(password: CharArray, salt: ByteArray, m: Int, t: Int, p: Int, len: Int): ByteArray {
        val params = Argon2Parameters.Builder(Argon2Parameters.ARGON2_id)
            .withVersion(Argon2Parameters.ARGON2_VERSION_13)
            .withMemoryAsKB(m)
            .withIterations(t)
            .withParallelism(p)
            .withSalt(salt)
            .build()
        val gen = Argon2BytesGenerator()
        gen.init(params)
        val out = ByteArray(len)
        gen.generateBytes(password, out) // encodes the chars as UTF-8
        return out
    }

    private fun prefix() =
        "\$argon2id\$v=19\$m=${cfg.memoryKiB},t=${cfg.iterations},p=${cfg.parallelism}\$"

    /** PHC string format, the same one libsodium, argon2-cffi and PHP use. */
    fun hash(password: CharArray): String {
        val salt = ByteArray(cfg.saltBytes).also { random.nextBytes(it) }
        val h = raw(password, salt, cfg.memoryKiB, cfg.iterations, cfg.parallelism, cfg.hashBytes)
        return prefix() + b64e.encodeToString(salt) + "\$" + b64e.encodeToString(h)
    }

    fun verify(password: CharArray, phc: String): Boolean {
        // "", "argon2id", "v=19", "m=..,t=..,p=..", salt, hash
        val parts = phc.split('$')
        if (parts.size != 6 || parts[1] != "argon2id" || parts[2] != "v=19") return false
        val p = parts[3].split(',').associate {
            it.substringBefore('=') to it.substringAfter('=').toInt()
        }
        val salt = b64d.decode(parts[4])
        val expected = b64d.decode(parts[5])
        val actual = raw(password, salt, p.getValue("m"), p.getValue("t"), p.getValue("p"), expected.size)
        return MessageDigest.isEqual(expected, actual)
    }

    /** True if the stored hash was made with different settings than the current config. */
    fun needsRehash(phc: String): Boolean = !phc.startsWith(prefix())
}

fun main() {
    val hasher = Argon2Hasher()
    val start = System.nanoTime()
    val stored = hasher.hash("hunter2".toCharArray())
    println("hash took ${(System.nanoTime() - start) / 1_000_000} ms")
    println(stored)
    println("correct: ${hasher.verify("hunter2".toCharArray(), stored)}")
    println("wrong:   ${hasher.verify("hunter3".toCharArray(), stored)}")
    println("needs rehash: ${hasher.needsRehash(stored)}")

    val stronger = Argon2Hasher(Argon2Config(memoryKiB = 46 * 1024, iterations = 1))
    println("needs rehash with new config: ${stronger.needsRehash(stored)}")
    // Old hashes still verify: the parameters come from the stored string
    println("new hasher verifies old hash: ${stronger.verify("hunter2".toCharArray(), stored)}")
}

Output:

hash took 448 ms
$argon2id$v=19$m=19456,t=2,p=1$n4fQ5WCTVjF8lWWd8rJ4+g$jaFrekvWezbZn97E+3ZVVANFmNSRFQ+Gq+gQ/Fbkzko
correct: true
wrong:   false
needs rehash: false
needs rehash with new config: true
new hasher verifies old hash: true

The first call includes JIT warm-up and class loading. Later calls are noticeably faster. Measure on your production hardware and pick settings that take something like 100-500 ms.

Memory cost is per concurrent hash: 50 simultaneous logins at 19 MiB each need about 1 GB of heap. Limit concurrency (see below) or size the heap with that in mind.


Spring Security's PasswordEncoder

If you already use Spring, spring-security-crypto has encoders for bcrypt, Argon2, scrypt and PBKDF2. It also has DelegatingPasswordEncoder, which prefixes each hash with an {id} naming the algorithm. New hashes use the current default (bcrypt), while hashes made with older algorithms keep verifying:

// build.gradle.kts (spring-core is already there in a Spring Boot app)
dependencies {
    implementation("org.springframework.security:spring-security-crypto:7.1.1")
    implementation("org.springframework:spring-core:7.0.9")
}
import org.springframework.security.crypto.factory.PasswordEncoderFactories
import org.springframework.security.crypto.password.PasswordEncoder
import org.springframework.security.crypto.password.Pbkdf2PasswordEncoder

fun main() {
    val encoder: PasswordEncoder = PasswordEncoderFactories.createDelegatingPasswordEncoder()

    val hash = encoder.encode("s3cret!")!!
    println(hash)
    println("matches: ${encoder.matches("s3cret!", hash)}")

    // A hash created by an older encoder keeps working thanks to its {id} prefix
    val legacy = "{pbkdf2@SpringSecurity_v5_8}" +
        Pbkdf2PasswordEncoder.defaultsForSpringSecurity_v5_8().encode("s3cret!")
    println(legacy)
    println("legacy matches: ${encoder.matches("s3cret!", legacy)}")
    println("legacy needs upgrade: ${encoder.upgradeEncoding(legacy)}")
    println("bcrypt needs upgrade: ${encoder.upgradeEncoding(hash)}")
}

Output:

{bcrypt}$2a$10$rSwdetHxp3SLINDUgc/Ptuq2mkN/ciUw/Osnm1RSHkydqjrjQvUvG
matches: true
{pbkdf2@SpringSecurity_v5_8}3d5f22aef8f81220fa019846f5306773d9eb28add17bf677f0bbb95dbfdef4ad252d8b270b5ed3ebb57237ca68213127
legacy matches: true
legacy needs upgrade: true
bcrypt needs upgrade: false

The default bcrypt cost here is 10. To get a higher cost or Argon2 for new hashes, build a DelegatingPasswordEncoder("argon2@SpringSecurity_v5_8", mapOf(...)) yourself. Spring's Argon2PasswordEncoder also needs Bouncy Castle on the classpath.


A complete login flow

Hashing correctly is only part of the job. A login service also has to:

import at.favre.lib.crypto.bcrypt.BCrypt
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withContext
import java.util.concurrent.ConcurrentHashMap

class UserService(private val cost: Int) {
    private val users = ConcurrentHashMap<String, String>() // username -> bcrypt hash

    // Verified against when the user doesn't exist, so the response takes as long
    // as for a real user and doesn't reveal which usernames are registered.
    private val dummyHash = BCrypt.withDefaults().hashToString(cost, "dummy".toCharArray())

    // Hashing is CPU-bound and slow on purpose: keep it off request/UI threads
    private suspend fun hash(pw: CharArray): String = withContext(Dispatchers.Default) {
        BCrypt.withDefaults().hashToString(cost, pw)
    }

    private suspend fun check(pw: CharArray, hash: String) = withContext(Dispatchers.Default) {
        BCrypt.verifyer().verify(pw, hash)
    }

    suspend fun register(username: String, password: CharArray) {
        try {
            users[username] = hash(password)
        } finally {
            password.fill(Char(0)) // wipe the plaintext from memory
        }
    }

    fun storedHash(username: String) = users[username]

    // Lets the example store a hash made with an older, weaker cost
    fun importHash(username: String, hash: String) { users[username] = hash }

    suspend fun login(username: String, password: CharArray): Boolean {
        try {
            val stored = users[username]
            val result = check(password, stored ?: dummyHash)
            if (stored == null || !result.verified) return false

            // Transparent upgrade: we have the plaintext now, so rehash with the current cost
            if (result.details.cost < cost) {
                users[username] = hash(password)
                println("  upgraded $username from cost ${result.details.cost} to $cost")
            }
            return true
        } finally {
            password.fill(Char(0))
        }
    }
}

fun main() = runBlocking {
    val service = UserService(cost = 12)
    service.register("alice", "wonderland".toCharArray())
    service.importHash("bob", BCrypt.withDefaults().hashToString(10, "builder".toCharArray()))

    println("alice ok:    ${service.login("alice", "wonderland".toCharArray())}")
    println("alice wrong: ${service.login("alice", "Wonderland".toCharArray())}")
    println("nobody:      ${service.login("nobody", "whatever".toCharArray())}")
    println("bob before:  ${service.storedHash("bob")!!.take(7)}")
    println("bob ok:      ${service.login("bob", "builder".toCharArray())}")
    println("bob after:   ${service.storedHash("bob")!!.take(7)}")
}

Output:

alice ok:    true
alice wrong: false
nobody:      false
bob before:  $2a$10$
  upgraded bob from cost 10 to 12
bob ok:      true
bob after:   $2a$12$

Dispatchers.Default has as many threads as there are CPU cores (at least two), so it also caps how many hashes run at the same time. With Argon2 that keeps memory use predictable. If you need a stricter limit, use a Semaphore from kotlinx.coroutines.sync or Dispatchers.Default.limitedParallelism(n).


Migrating from a weak legacy hash

If your database already holds unsalted MD5 or SHA-1 hashes, you don't have to wait for every user to log in. Wrap them right away: store argon2id(sha1(password)) with a marker such as legacy-sha1: in front. When checking such a hash, compute sha1 of the typed password first, then verify it with Argon2. The next time the user logs in successfully, replace it with a plain argon2id(password) hash. This way the weak hashes are gone from your database immediately, not months later.


Best practices

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents