TransWikia.com

How to hash and verify passwords in Ktor?

Stack Overflow Asked by Emad Omar on February 5, 2021

I’m new to Kotlin and Ktor and as I try to implement authentication for my web app, I need to store passwords for users. However, I can’t seem to find a way either by Ktor Core or by external java dependencies to hash passwords and verify them.

I found some articles on how to hash using BCrypt or PBKDF2, but these require me to do the hashing implementation myself which doesn’t seem safe as I will have to worry about maintaining it.

  • Is there a way via Ktor where I can hash passwords and verify them? (similar to PHP’s password_hash() and password_verify())
  • If not, can you recommend a Gradle dependency that has a good reputation and is well maintained?
  • Or how can I make a custom implementation and make sure it’s safe?

One Answer

I have used jBCrypt like this:

build.gradle add:

// current jbcrypt_version is 0.4
compile group: 'org.mindrot', name: 'jbcrypt', version: jbcrypt_version

hen creating your User database record save password hash like this:

import org.mindrot.jbcrypt.BCrypt
...
fun setPassword(user: User) {
   user.passwordHash = BCrypt.hashpw(password, BCrypt.gensalt())
}

when checking password:

user = findUserByUsername(username=usernameToCheck)
if (!user)
    return ...
if (!BCrypt.checkpw(user.passwordHash, passwordToCheck))
    return ...
// user/password validated

NOTE: jBCrypt salt is saved along with some metadata in password hash. Example:

salt=$2a$10$e9kAuRN/PARzXnNdnghiSO
hash=$2a$10$e9kAuRN/PARzXnNdnghiSOjfShrH9rrGQtfrAIj06LZ7ZW1MW7bEy

Answered by Robert Lujo on February 5, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP