ya_rand/encoding.rs
1/// Specifies parameters for encoding random data into a valid utf-8 `String`.
2///
3/// All provided implementations list their minimum secure length
4/// in the documentation of their unit struct.
5///
6/// # Safety
7///
8/// The `CHARSET` field must only contain valid ascii characters.
9/// Meaning that all u8 values must be in the interval [0, 128).
10/// Failure to uphold this condition will result in `text` methods
11/// returning invalid `Strings`'s.
12///
13/// The `MIN_LEN` field must be at least ceil(log<sub>`base`</sub>(2<sup>128</sup>)),
14/// where `base` is the length of the `CHARSET` field. Failure to uphold
15/// this condition will result in poor security of generated `String`'s.
16pub unsafe trait Encoder {
17 /// The character set of the encoder implementation.
18 ///
19 /// See trait-level docs for safety comments.
20 const CHARSET: &[u8];
21
22 /// Shortest length `String` that will contain at least 128 bits
23 /// of randomness.
24 ///
25 /// See trait-level docs for safety comments.
26 const MIN_LEN: usize;
27}
28
29/// Base64 encoding, as specified by RFC 4648.
30///
31/// Minimum secure length is 22.
32pub struct Base64;
33unsafe impl Encoder for Base64 {
34 const CHARSET: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
35
36 const MIN_LEN: usize = 22;
37}
38
39/// Base64 encoding for URLs and filenames, as specified by RFC 4648.
40///
41/// Minimum secure length is 22.
42pub struct Base64URL;
43unsafe impl Encoder for Base64URL {
44 const CHARSET: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
45
46 const MIN_LEN: usize = 22;
47}
48
49/// Base62 (alphanumeric) encoding.
50///
51/// Minimum secure length is 22.
52pub struct Base62;
53unsafe impl Encoder for Base62 {
54 const CHARSET: &[u8] = crate::rng::ALPHANUMERIC;
55
56 const MIN_LEN: usize = 22;
57}
58
59/// Base32 encoding, as specified by RFC 4648.
60///
61/// Minimum secure length is 26.
62pub struct Base32;
63unsafe impl Encoder for Base32 {
64 const CHARSET: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
65
66 const MIN_LEN: usize = 26;
67}
68
69/// Base32 encoding using extended hex, as specified by RFC 4648.
70///
71/// Minimum secure length is 26.
72pub struct Base32Hex;
73unsafe impl Encoder for Base32Hex {
74 const CHARSET: &[u8] = b"0123456789ABCDEFGHIJKLMNOPQRSTUV";
75
76 const MIN_LEN: usize = 26;
77}
78
79/// Base16 (hexidecimal) encoding, as specified by RFC 4648.
80///
81/// Minimum secure length is 32.
82pub struct Base16;
83unsafe impl Encoder for Base16 {
84 const CHARSET: &[u8] = b"0123456789ABCDEF";
85
86 const MIN_LEN: usize = 32;
87}
88
89/// Base16 (lowercase hexidecimal) encoding.
90///
91/// Minimum secure length is 32.
92pub struct Base16Lowercase;
93unsafe impl Encoder for Base16Lowercase {
94 const CHARSET: &[u8] = b"0123456789abcdef";
95
96 const MIN_LEN: usize = 32;
97}