Skip to content

Password Hashing

Tony Arcieri edited this page May 23, 2014 · 17 revisions

Password hashing functions are specifically designed for password storage and/or deriving encryption keys. Unlike normal hash functions, which are designed to be as fast as possible (so e.g. sha256sum myfile completes as quickly as possible), password hashing functions are specifically designed to be slow to resist brute force attacks against people's passwords by those who recover the hashes.

scrypt

RbNaCl (with libsodium >= 0.5.0) supports an algorithm known as scrypt which is useful for both deriving encryption keys from a user's password and also or for storing digests of passwords in such a way that they cannot easily be reversed back into a user's original password. In addition, scrypt has a property called "sequential memory hardness", which adds a memory cost to the algorithm to make it even harder to brute force.

Code Example

# Get the password somehow
password = ...

# Generate a random salt (libsodium enforces 32-byte salts)
salt = RbNaCl::Random.random_bytes(RbNaCl::PasswordHash::SCrypt::SALT_BYTES)

# scrypt CPU and memory cost parameters
opslimit = 2**20
memlimit = 2**24

# Size of digest to compute in bytes (default 64)
digest_size = 64

digest = RbNaCl::PasswordHash.scrypt(password, salt, opslimit, memlimit, digest_size)
Clone this wiki locally