如何在 nim 中重建 django 的密码散列?

How do I re-build django's password hashing in nim?

我正在将我的网络应用程序从 Python (Django) 重写为 Nim (Prologue)。 到目前为止,我想继续使用它为我提供的 Django 数据库,但我正在努力如何重新构建 Django 加密密码的方式。 即根据Django's own documentation:

By default, Django uses the PBKDF2 algorithm with a SHA256 hash

我找到了 nimcrypto 库作为起点,但由于我缺乏密码学知识,其中的很多术语以及如何使用给定的过程完全让我头疼。如何使用它重建 Django 加密?

警告: 正如我所指出的,为此使用 nim-wrapper of libsodium 可能是更好的主意,因为它是更成熟的库。不过,您将如何做到这一点超出了我的范围,因为 libsodium 没有明显的“pbkdf2”功能。

在对这个主题进行了相当多的研究并检查了 django 存储库和 nimcrypto 库中的代码之后,我能够重现数据库中的哈希值。这里的关键是,nimcrypto 在同名模块中有一个 pbkdf2 proc,你需要传递一个 HMAC 类型,它包含 sha256 算法以及你的服务器的密钥。您还需要注意,作为字符串存储在数据库中的哈希值将附加迭代次数和加盐值。它们也将是哈希的 base64 编码版本。

import nimcrypto
import nimcrypto/pbkdf2
import base64

var hctx: HMAC[sha256]
let serverSecretKey = "YourServersSecretKeyInDjangoFromSettings"
hctx.init(serverSecretKey)

let password = "thePasswordToHash"
let salt = "asalt" #<-- You have to get this one from the passwords entry in your database
var output: array[32, byte] # <-- 256 bits stored in 32 bytes
let iterations = 180000 # <-- You have to get this one from the passwords entry in your database

discard pbkdf2(hctx, password, salt, iterations, output) #The output of pbkdf2 is irrelevant, you care of the hash in the `output` byte array aka the digest

let newHash = encode(output) # This turns the byte.array into a base64 encoded string. That string should be identical to the hash-string you have in your database.