src/bcrypt

Search:
Group by:
Source   Edit  

bcryptrocks is a wrapper over Solar Designer's crypt_blowfish library, this wrapper provides three procedures you can use for generating salts, hasing passwords and comparing them.

This module is compatible with the original bcryptnim wrapper by @runvnc, you should be able to simply change a single package dependency line as this is meant to be a drop-in replacement.

Procs

proc compare(s1, s2: string): bool {....raises: [], tags: [], forbids: [].}

This is a constant-time string comparator.

You might not wish to use this, this implementation is provided as a best effort and is most likely not actually constant-time. There's also nothing stopping the Nim (or C) compiler from optimizing this down into variable time instructions.

In other words, implement your own check in assembly if you're serious about security.

Example:

assert compare("a", "b") == false
Source   Edit  
proc genSalt(rounds: int = 12; prefix: string = "$2b$"): string {.
    ...raises: [OSError, CatchableError], tags: [], forbids: [].}

This generates a salt, a random value that can be used alongside password hashing to prevent rainbow table attacks. Salting your passwords is standard security practice.

You can set the number of rounds to a number from 4 to 31, invalid values will make the number fallback to 12.

Note: If you're having weird problems with bcryptnim compatability, then it might help to set the prefix parameter to "$2a$", otherwise keep it as "$2b$" or you risk using a flawed salt generation algorithm.

Example:

let rounds = 12

echo "Your salt is: ", genSalt(rounds)
Source   Edit  
proc hash(key, salt: string): string {....raises: [CatchableError], tags: [],
                                       forbids: [].}

This procedure takes two string and returns the bcrypt hash for them.

Note: It's best that you use a salt generated with the genSalt() procedure, you could run into undefined behavior if not.

Example:

var
  pass = "SOMETHING_SECRET"
  salt = genSalt(12)

echo "Your hash is: ", hash(pass, salt)
Source   Edit