From f2156e21b830ebc3cfd0f9eab4e7e01112e023b4 Mon Sep 17 00:00:00 2001 From: Katharina Fey Date: Mon, 2 Jul 2018 18:37:15 +0200 Subject: Refactoring crypto module, moving `auth` into `users` module --- lockchain-core/src/crypto/random.rs | 46 +++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 lockchain-core/src/crypto/random.rs (limited to 'lockchain-core/src/crypto/random.rs') diff --git a/lockchain-core/src/crypto/random.rs b/lockchain-core/src/crypto/random.rs new file mode 100644 index 0000000..7d31992 --- /dev/null +++ b/lockchain-core/src/crypto/random.rs @@ -0,0 +1,46 @@ +//! A small convenience wrapper around `rand` + +use rand::{thread_rng, Rng}; + +/// Generate a random number with an upper bound +pub fn number(bound: u64) -> u64 { + return thread_rng().next_u64() % bound; +} + +/// Generate a sequence of random bytes that are returned +/// as a vector. +/// +/// Can at most allocate 2048 bytes at a time +/// FIXME: That shouldn't have a limit! +pub fn bytes(length: usize) -> Vec { + let mut vec: Vec = Vec::new(); + + if length > 2048 { + return vec; + } + + let mut random_data = [0u8; 2048]; + thread_rng().fill_bytes(&mut random_data); + + for i in 0..length { + vec.push(random_data[i]); + } + + return vec; +} + +/// A small utility wraper around bcrypt to allow +/// easy password checking. +pub mod passwd { + use bcrypt::{self, DEFAULT_COST}; + + /// Create a new password, returning a hash + pub fn create(pw: &str) -> Option { + Some(bcrypt::hash(pw, DEFAULT_COST).ok()?) + } + + /// Verify a password against it's stored hash + pub fn verify(pw: &str, hash: &str) -> Option { + bcrypt::verify(pw, hash).ok() + } +} -- cgit v1.2.3