How to hash and verify passwords in Ktor?

Viewed 4650

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?
2 Answers

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

I use this one: https://github.com/patrickfav/bcrypt

How i use:

get("/auth") {
        val password = "pardonme"
        val hashPassword = BCrypt.withDefaults().hashToString(12, password.toCharArray())
        val result = BCrypt.verifyer().verify(password.toCharArray(), hashPassword)
        // print it out and copy it, in case you want to test
        call.respondText("HashPassword: $hashPassword\nResult: $result")
}

and then you can test:

get("/auth") {
        val password = "pardonme"
        val hashPassword = "ur previous hashPassword"
        val result = BCrypt.verifyer().verify(password.toCharArray(), hashPassword)
        call.respondText("Result: $result")
}

you can check more information via link above!

Related