1
0
mirror of https://github.com/dani-garcia/vaultwarden.git synced 2024-11-09 20:42:36 +01:00

Generate tokens more simply and uniformly

This commit is contained in:
Jeremy Lin 2020-08-22 16:07:53 -07:00
parent eba22c2d94
commit d9684bef6b
3 changed files with 13 additions and 7 deletions

1
Cargo.lock generated
View File

@ -153,6 +153,7 @@ dependencies = [
"once_cell", "once_cell",
"openssl", "openssl",
"percent-encoding 2.1.0", "percent-encoding 2.1.0",
"rand 0.7.3",
"regex", "regex",
"reqwest", "reqwest",
"ring", "ring",

View File

@ -60,7 +60,8 @@ diesel_migrations = "1.4.0"
# Bundled SQLite # Bundled SQLite
libsqlite3-sys = { version = "0.18.0", features = ["bundled"], optional = true } libsqlite3-sys = { version = "0.18.0", features = ["bundled"], optional = true }
# Crypto library # Crypto-related libraries
rand = "0.7.3"
ring = "0.16.15" ring = "0.16.15"
# UUID generation # UUID generation

View File

@ -55,17 +55,21 @@ pub fn get_random(mut array: Vec<u8>) -> Vec<u8> {
} }
pub fn generate_token(token_size: u32) -> Result<String, Error> { pub fn generate_token(token_size: u32) -> Result<String, Error> {
// A u64 can represent all whole numbers up to 19 digits long.
if token_size > 19 { if token_size > 19 {
err!("Generating token failed") err!("Token size is limited to 19 digits")
} }
// 8 bytes to create an u64 for up to 19 token digits let low: u64 = 0;
let bytes = get_random(vec![0; 8]); let high: u64 = 10u64.pow(token_size);
let mut bytes_array = [0u8; 8];
bytes_array.copy_from_slice(&bytes);
let number = u64::from_be_bytes(bytes_array) % 10u64.pow(token_size); // Generate a random number in the range [low, high), then format it as a
// token of fixed width, left-padding with 0 as needed.
use rand::{thread_rng, Rng};
let mut rng = thread_rng();
let number: u64 = rng.gen_range(low, high);
let token = format!("{:0size$}", number, size = token_size as usize); let token = format!("{:0size$}", number, size = token_size as usize);
Ok(token) Ok(token)
} }