about summary refs log tree commit diff
path: root/knowing/src/id.rs
blob: e990c76d8146bc9ed6daac0e0480086bbfde473f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
use smallrand::{ChaCha12, DefaultEntropy, Rng};
use somethings::auth::Base58Id;

const BASE58: &'static [u8] = b"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";

pub trait RandomId {
	fn rand() -> Self;
}

impl<const N: usize> RandomId for Base58Id<N> {
	fn rand() -> Self {
		unsafe { Self::new_unchecked(random_base58()) }
	}
}

/// Random Base58 string, `count` characters long, using OsRng which is assumed
/// to be secure
/// > assumed that system always provides high-quality cryptographically secure random data
fn random_base58<const N: usize>() -> [u8; N] {
	let mut buffer = [0u8; N];

	// Explicitly using ChaCha12 here because StdRng is not garunteed to be
	// cryptographically secure
	let mut entropy = DefaultEntropy::new();
	let mut rng = ChaCha12::from_entropy(&mut entropy);
	buffer
		.iter_mut()
		.for_each(|b| *b = BASE58[rng.range(0..BASE58.len())]);

	buffer
}