Docs/Building applications

Hashing & passwords

Hash content, store passwords safely, and generate random tokens.

On this page

valk.crypto provides hashes, password hashing, random bytes, and encodings such as hex and Base64.

Hash text#

Valk
use valk.crypto

fn main() {
    let digest = crypto.sha256_hex("Valk")
    println(digest)
}

sha256_hex produces a hexadecimal SHA-256 digest. md5_hex, sha1_hex, sha384_hex and sha512_hex work the same way. A content hash like this is fast; it is not the right tool for passwords.

Store a password#

Valk
use valk.crypto

fn main() {
    let hash = crypto.bcrypt_hash("correct horse") ! {
        println("Could not hash the password")
        return
    }
    println(crypto.bcrypt_verify("correct horse", hash)) // true
    println(crypto.bcrypt_verify("wrong", hash))         // false
}

bcrypt_hash returns a string that contains its own salt, so store it as it is. bcrypt_verify checks a password against that stored hash. Bcrypt is deliberately slow, which is what makes guessing passwords expensive.

Random bytes and encodings#

Valk
use valk.crypto

fn main() {
    let token = crypto.random_bytes(16)
    println(crypto.hex_encode(token).length) // 32
    println(crypto.base64_encode("Valk"))    // VmFsaw==
}

random_bytes returns bytes from the operating system's secure random source, suitable for session tokens and keys. hex_encode and base64_encode turn bytes into text; hex_decode and base64_decode reverse them and fail on malformed input.