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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
use base64;
use rand::rngs::EntropyRng;
use rand::RngCore;
use {Error, ErrorKind};
pub fn generate_random_bytes(len: u32) -> Result<Vec<u8>, Error> {
let mut rng = EntropyRng::new();
let mut bytes = vec![0u8; len as usize];
rng.try_fill_bytes(&mut bytes)
.map_err(|e| Error::new(ErrorKind::OsRngError).add_context(format!("{}", e)))?;
Ok(bytes)
}
pub fn generate_random_base64_encoded_string(len: u32) -> Result<String, Error> {
let mut rng = EntropyRng::new();
let mut bytes = vec![0u8; len as usize];
rng.try_fill_bytes(&mut bytes)
.map_err(|e| Error::new(ErrorKind::OsRngError).add_context(format!("{}", e)))?;
let output = base64::encode_config(&bytes, base64::STANDARD);
Ok(output)
}
pub fn generate_random_base64_encoded_string_config(
len: u32,
config: base64::Config,
) -> Result<String, Error> {
let mut rng = EntropyRng::new();
let mut bytes = vec![0u8; len as usize];
rng.try_fill_bytes(&mut bytes)
.map_err(|e| Error::new(ErrorKind::OsRngError).add_context(format!("{}", e)))?;
let output = base64::encode_config(&bytes, config);
Ok(output)
}