2022-08-10 01:59:10 -04:00
|
|
|
# --==--==--==--==--==--==--==--==--==--==--==--==--==--==--==-- #
|
|
|
|
# Bruno Charest
|
|
|
|
# 2022-08-09
|
|
|
|
#
|
|
|
|
# __ DESCRIPTIONS __
|
|
|
|
# password_utils : procedure related password
|
|
|
|
#
|
|
|
|
# Inspiration of : https://ttj.dk/blog/2019/01/20/setup-a-website-with-nim
|
|
|
|
# Copyright 2019 - Thomas T. Jarløv
|
|
|
|
# --==--==--==--==--==--==--==--==--==--==--==--==--==--==--==-- #
|
|
|
|
import md5
|
|
|
|
import bcrypt
|
|
|
|
import random
|
2022-07-31 16:45:47 -04:00
|
|
|
randomize()
|
|
|
|
|
2022-08-10 12:02:02 -04:00
|
|
|
# --==--==--==--==--==--==--==--==--==--==-- #
|
|
|
|
# Let and VAR : for random
|
|
|
|
# --==--==--==--==--==--==--==--==--==--==-- #
|
2022-07-31 16:45:47 -04:00
|
|
|
var urandom: File
|
|
|
|
let useUrandom = urandom.open("/dev/urandom")
|
|
|
|
|
2022-08-10 12:02:02 -04:00
|
|
|
|
|
|
|
# --==--==--==--==--==--==--==--==--==--==--=--==--==--=--==--==--=--==--==-- #
|
|
|
|
# PROC : Make Salt
|
|
|
|
## : Generate random salt. Uses cryptographically secure /dev/urandom
|
|
|
|
## : on platforms where it is available, and Nim's random module in other cases.
|
|
|
|
# --==--==--==--==--==--==--==--==--==--==--=--==--==--=--==--==--=--==--==-- #
|
2022-10-27 13:10:16 -04:00
|
|
|
proc makeSalt*(): string =
|
2022-07-31 16:45:47 -04:00
|
|
|
result = ""
|
|
|
|
if useUrandom:
|
|
|
|
var randomBytes: array[0..127, char]
|
|
|
|
discard urandom.readBuffer(addr(randomBytes), 128)
|
|
|
|
for ch in randomBytes:
|
|
|
|
if ord(ch) in {32..126}:
|
|
|
|
result.add(ch)
|
|
|
|
else:
|
|
|
|
for i in 0..127:
|
|
|
|
result.add(chr(rand(94) + 32)) # Generate numbers from 32 to 94 + 32 = 126
|
|
|
|
|
2022-08-10 12:02:02 -04:00
|
|
|
|
|
|
|
# --==--==--==--==--==--==--==--==--==--==-- #
|
|
|
|
# PROC : Make session key
|
|
|
|
## Creates a random key to be used to authorize a session.
|
|
|
|
# --==--==--==--==--==--==--==--==--==--==-- #
|
2022-10-27 13:10:16 -04:00
|
|
|
proc makeSessionKey*(): string =
|
2022-07-31 16:45:47 -04:00
|
|
|
let random = makeSalt()
|
|
|
|
return bcrypt.hash(random, genSalt(8))
|
|
|
|
|
|
|
|
|
2022-08-10 12:02:02 -04:00
|
|
|
# --==--==--==--==--==--==--==--==--==--==-- #
|
|
|
|
# PROC : make password
|
|
|
|
## Creates an MD5 hash by combining password and salt
|
|
|
|
# --==--==--==--==--==--==--==--==--==--==-- #
|
2022-10-27 13:10:16 -04:00
|
|
|
proc makePassword*(password, salt: string, comparingTo = ""): string =
|
2022-07-31 16:45:47 -04:00
|
|
|
let bcryptSalt = if comparingTo != "": comparingTo else: genSalt(8)
|
2022-10-27 13:10:16 -04:00
|
|
|
result = hash(getMD5(salt & getMD5(password)), bcryptSalt)
|