Provide sources for the EC math and use a faster double algorithm
[dnssec-prover] / src / base32.rs
1 // This is a modification of base32 from https://crates.io/crates/base32(v0.4.0),
2 // copied from rust-lightning.
3 // The original portions of this software are Copyright (c) 2015 The base32 Developers
4 // The remainder is copyright rust-lightning developers, as viewable in version control at
5 // https://github.com/lightningdevkit/rust-lightning/
6
7 // This file is licensed under either of
8 // Apache License, Version 2.0, (LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0) or
9 // MIT license (LICENSE-MIT or http://opensource.org/licenses/MIT) at your option.
10
11 use alloc::vec::Vec;
12
13 /// RFC4648 "extended hex" encoding table
14 #[cfg(test)]
15 const RFC4648_ALPHABET: &'static [u8] = b"0123456789ABCDEFGHIJKLMNOPQRSTUV";
16
17 /// RFC4648 "extended hex" decoding table
18 const RFC4648_INV_ALPHABET: [i8; 39] = [
19         0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, -1, -1, -1, 10, 11, 12, 13,
20         14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31,
21 ];
22
23 /// Encode bytes into a base32 string.
24 #[cfg(test)]
25 pub fn encode(data: &[u8]) -> alloc::string::String {
26         // output_length is calculated as follows:
27         // / 5 divides the data length by the number of bits per chunk (5),
28         // * 8 multiplies the result by the number of characters per chunk (8).
29         // + 4 rounds up to the nearest character.
30         let output_length = (data.len() * 8 + 4) / 5;
31         let mut ret = encode_data(data, RFC4648_ALPHABET);
32         ret.truncate(output_length);
33
34         #[cfg(fuzzing)]
35         assert_eq!(ret.capacity(), (data.len() + 4) / 5 * 8);
36
37         alloc::string::String::from_utf8(ret).expect("Invalid UTF-8")
38 }
39
40 /// Decode a base32 string into a byte vector.
41 pub fn decode(data: &str) -> Result<Vec<u8>, ()> {
42         let data = data.as_bytes();
43         // If the string has more characters than are required to alphabet_encode the number of bytes
44         // decodable, treat the string as invalid.
45         match data.len() % 8 { 1|3|6 => return Err(()), _ => {} }
46         Ok(decode_data(data, RFC4648_INV_ALPHABET)?)
47 }
48
49 /// Encode a byte slice into a base32 string.
50 #[cfg(test)]
51 fn encode_data(data: &[u8], alphabet: &'static [u8]) -> Vec<u8> {
52         // cap is calculated as follows:
53         // / 5 divides the data length by the number of bits per chunk (5),
54         // * 8 multiplies the result by the number of characters per chunk (8).
55         // + 4 rounds up to the nearest character.
56         let cap = (data.len() + 4) / 5 * 8;
57         let mut ret = Vec::with_capacity(cap);
58         for chunk in data.chunks(5) {
59                 let mut buf = [0u8; 5];
60                 for (i, &b) in chunk.iter().enumerate() {
61                         buf[i] = b;
62                 }
63                 ret.push(alphabet[((buf[0] & 0xF8) >> 3) as usize]);
64                 ret.push(alphabet[(((buf[0] & 0x07) << 2) | ((buf[1] & 0xC0) >> 6)) as usize]);
65                 ret.push(alphabet[((buf[1] & 0x3E) >> 1) as usize]);
66                 ret.push(alphabet[(((buf[1] & 0x01) << 4) | ((buf[2] & 0xF0) >> 4)) as usize]);
67                 ret.push(alphabet[(((buf[2] & 0x0F) << 1) | (buf[3] >> 7)) as usize]);
68                 ret.push(alphabet[((buf[3] & 0x7C) >> 2) as usize]);
69                 ret.push(alphabet[(((buf[3] & 0x03) << 3) | ((buf[4] & 0xE0) >> 5)) as usize]);
70                 ret.push(alphabet[(buf[4] & 0x1F) as usize]);
71         }
72         #[cfg(fuzzing)]
73         assert_eq!(ret.capacity(), cap);
74
75         ret
76 }
77
78 fn decode_data(data: &[u8], alphabet: [i8; 39]) -> Result<Vec<u8>, ()> {
79         // cap is calculated as follows:
80         // / 8 divides the data length by the number of characters per chunk (8),
81         // * 5 multiplies the result by the number of bits per chunk (5),
82         // + 7 rounds up to the nearest byte.
83         let cap = (data.len() + 7) / 8 * 5;
84         let mut ret = Vec::with_capacity(cap);
85         for chunk in data.chunks(8) {
86                 let mut buf = [0u8; 8];
87                 for (i, &c) in chunk.iter().enumerate() {
88                         match alphabet.get(c.to_ascii_uppercase().wrapping_sub(b'0') as usize) {
89                                 Some(&-1) | None => return Err(()),
90                                 Some(&value) => buf[i] = value as u8,
91                         };
92                 }
93                 ret.push((buf[0] << 3) | (buf[1] >> 2));
94                 ret.push((buf[1] << 6) | (buf[2] << 1) | (buf[3] >> 4));
95                 ret.push((buf[3] << 4) | (buf[4] >> 1));
96                 ret.push((buf[4] << 7) | (buf[5] << 2) | (buf[6] >> 3));
97                 ret.push((buf[6] << 5) | buf[7]);
98         }
99         let output_length = data.len() * 5 / 8;
100         for c in ret.drain(output_length..) {
101                 if c != 0 {
102                         // If the original string had any bits set at positions outside of the encoded data,
103                         // treat the string as invalid.
104                         return Err(());
105                 }
106         }
107
108         // Check that our capacity calculation doesn't under-shoot in fuzzing
109         #[cfg(fuzzing)]
110         assert_eq!(ret.capacity(), cap);
111         Ok(ret)
112 }
113
114 #[cfg(test)]
115 mod tests {
116         use super::*;
117
118         #[test]
119         fn test_encode_decode() {
120                 let mut bytes = [0u8; 256 * 5];
121                 for i in 0..=255 {
122                         bytes[i as usize + 256*0] = i;
123                         bytes[i as usize + 256*1] = i.wrapping_add(1);
124                         bytes[i as usize + 256*2] = i.wrapping_add(2);
125                         bytes[i as usize + 256*3] = i.wrapping_add(3);
126                         bytes[i as usize + 256*4] = i.wrapping_add(4);
127                 }
128                 assert_eq!(decode(&encode(&bytes)).unwrap(), bytes);
129         }
130 }