简体   繁体   English

如何在 Ktor 中散列和验证密码?

[英]How to hash and verify passwords in Ktor?

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.我是 Kotlin 和 Ktor 的新手,当我尝试为我的 Web 应用程序实施身份验证时,我需要为用户存储密码。 However, I can't seem to find a way either by Ktor Core or by external java dependencies to hash passwords and verify them.但是,我似乎无法通过 Ktor Core 或外部 java 依赖项找到一种方法来散列密码并验证它们。

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.我找到了一些关于如何使用 BCrypt 或 PBKDF2 进行散列的文章,但这些文章要求我自己进行散列实现,这似乎并不安全,因为我将不得不担心维护它。

  • Is there a way via Ktor where I can hash passwords and verify them?有没有办法通过 Ktor 散列密码并验证它们? (similar to PHP's password_hash() and password_verify() ) (类似于 PHP 的password_hash()password_verify()
  • If not, can you recommend a Gradle dependency that has a good reputation and is well maintained?如果没有,您能否推荐一个信誉良好且维护良好的 Gradle 依赖项?
  • Or how can I make a custom implementation and make sure it's safe?或者我如何进行自定义实现并确保它是安全的?

I have used jBCrypt like this:我曾经像这样使用过jBCrypt

build.gradle add: build.gradle 添加:

// 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.注意: jBCrypt salt 与密码哈希中的一些元数据一起保存。 Example:例子:

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

I use this one: https://github.com/patrickfav/bcrypt我用这个: 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!您可以通过上面的链接查看更多信息!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM