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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
use std::error::Error;
use std::fmt;
const BASE64_ENCODE_TABLE: &[u8; 64] =
b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
const BASE64_DECODE_TABLE: &[Option<u8>; 256] = &decode_table();
const PADDING_SENTINEL: u8 = 0xFF;
const fn encode_table_index_of(i: usize) -> Option<u8> {
let mut index = 0;
while index < BASE64_ENCODE_TABLE.len() {
if BASE64_ENCODE_TABLE[index] as usize == i {
return Some(index as u8);
}
index += 1;
}
None
}
const fn decode_table() -> [Option<u8>; 256] {
let mut output = [None; 256];
let mut i = 0;
while i < 256 {
if i == 61 {
output[i] = Some(PADDING_SENTINEL);
} else {
output[i] = encode_table_index_of(i);
}
i += 1;
}
output
}
pub fn encode<T: AsRef<[u8]>>(input: T) -> String {
encode_inner(input.as_ref())
}
fn encode_inner(inp: &[u8]) -> String {
let char_ct = ((inp.len() + 2) / 3) * 4;
let mut output = String::with_capacity(char_ct);
for chunk in inp.chunks(3) {
let mut block: i32 = 0;
for (idx, chunk) in chunk.iter().enumerate() {
block |= (*chunk as i32) << ((3 - idx) * 8);
}
let num_sextets = ((chunk.len() * 8) + 5) / 6;
for idx in 0..num_sextets {
let slice = block >> (26 - (6 * idx));
let idx = (slice as u8) & 0b0011_1111;
output.push(BASE64_ENCODE_TABLE[idx as usize] as char);
}
for _ in 0..(4 - num_sextets) {
output.push('=');
}
}
debug_assert_eq!(output.capacity(), char_ct);
output
}
pub fn decode<T: AsRef<str>>(input: T) -> Result<Vec<u8>, DecodeError> {
decode_inner(input.as_ref())
}
#[derive(Debug, Clone, Eq, PartialEq)]
#[non_exhaustive]
pub enum DecodeError {
InvalidByte,
InvalidPadding,
InvalidLength,
}
impl Error for DecodeError {}
impl fmt::Display for DecodeError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
use DecodeError::*;
match self {
InvalidByte => write!(f, "invalid byte"),
InvalidPadding => write!(f, "invalid padding"),
InvalidLength => write!(f, "invalid length"),
}
}
}
fn decode_inner(inp: &str) -> Result<Vec<u8>, DecodeError> {
if inp.len() == 1 {
return Err(DecodeError::InvalidLength);
}
let mut ret = Vec::with_capacity((inp.len() + 3) / 4 * 3);
let chunks = inp.as_bytes().chunks(4);
let mut padding = 0;
for chunk in chunks {
if padding != 0 {
return Err(DecodeError::InvalidPadding);
}
let mut block = 0_i32;
for (idx, chunk) in chunk.iter().enumerate() {
let bits = BASE64_DECODE_TABLE[*chunk as usize].ok_or(DecodeError::InvalidByte)?;
if bits == 0xFF {
padding += 1;
} else if padding > 0 {
return Err(DecodeError::InvalidPadding);
}
block |= (bits as i32) << (18 - (idx * 6));
}
let missing_chars = 4 - chunk.len();
for i in (padding + missing_chars..3).rev() {
let byte = ((block >> (i * 8)) & 0xFF) as u8;
ret.push(byte)
}
}
debug_assert!(ret.capacity() - ret.len() < 4);
Ok(ret)
}
#[cfg(test)]
mod test {
use crate::base64::{decode, encode, DecodeError, BASE64_DECODE_TABLE, BASE64_ENCODE_TABLE};
use proptest::prelude::*;
proptest! {
#[test]
fn doesnt_crash_encode(v in any::<Vec<u8>>()) {
encode(v);
}
#[test]
fn doesnt_crash_decode(v in any::<String>()) {
let us = decode(&v);
let correct = ::base64::decode(&v);
if correct.is_ok() {
us.expect("we should be able to read all base64 the oracle can");
}
}
#[test]
fn round_trip(v in any::<Vec<u8>>()) {
let as_b64 = encode(v.as_slice());
let decoded = decode(as_b64).unwrap();
assert_eq!(v, decoded);
}
#[test]
fn vs_oracle(v in any::<Vec<u8>>()) {
let correct = ::base64::encode(v.as_slice());
let ours = encode(v.as_slice());
assert_eq!(ours, correct);
}
}
#[test]
fn test_base64() {
assert_eq!(encode("abc"), "YWJj");
assert_eq!(decode("YWJj").unwrap(), b"abc");
assert_eq!(decode("YQ==").unwrap(), b"a");
assert_eq!(encode("anything you want."), "YW55dGhpbmcgeW91IHdhbnQu");
assert_eq!(encode("anything you want"), "YW55dGhpbmcgeW91IHdhbnQ=");
assert_eq!(encode("anything you wan"), "YW55dGhpbmcgeW91IHdhbg==");
}
#[test]
fn test_invalid_padding() {
assert_eq!(decode("ab=d"), Err(DecodeError::InvalidPadding));
assert_eq!(decode("abcd====="), Err(DecodeError::InvalidPadding));
assert_eq!(decode("abc=defg"), Err(DecodeError::InvalidPadding));
assert_eq!(decode("YQ").unwrap(), b"a");
assert_eq!(decode("a"), Err(DecodeError::InvalidLength));
assert_eq!(decode("====").unwrap(), b"");
}
#[test]
fn test_base64_long() {
let decoded = "Alas, eleventy-one years is far too short a time to live among such excellent and admirable hobbits. I don't know half of you half as well as I should like, and I like less than half of you half as well as you deserve.";
let encoded = "QWxhcywgZWxldmVudHktb25lIHllYXJzIGlzIGZhciB0b28gc2hvcnQgYSB0aW1lIHRvIGxpdmUgYW1vbmcgc3VjaCBleGNlbGxlbnQgYW5kIGFkbWlyYWJsZSBob2JiaXRzLiBJIGRvbid0IGtub3cgaGFsZiBvZiB5b3UgaGFsZiBhcyB3ZWxsIGFzIEkgc2hvdWxkIGxpa2UsIGFuZCBJIGxpa2UgbGVzcyB0aGFuIGhhbGYgb2YgeW91IGhhbGYgYXMgd2VsbCBhcyB5b3UgZGVzZXJ2ZS4=";
assert_eq!(encode(decoded), encoded);
assert_eq!(decode(encoded).unwrap(), decoded.as_bytes());
}
#[test]
fn test_base64_utf8() {
let decoded = "ユニコードとはか?";
let encoded = "44Om44OL44Kz44O844OJ44Go44Gv44GL77yf";
assert_eq!(encode(decoded), encoded);
assert_eq!(decode(encoded).unwrap(), decoded.as_bytes());
}
#[test]
fn test_base64_control_chars() {
let decoded = "hello\tworld\n";
let encoded = "aGVsbG8Jd29ybGQK";
assert_eq!(encode(decoded), encoded);
}
#[test]
fn test_decode_table() {
assert_eq!(BASE64_DECODE_TABLE[0], None);
assert_eq!(BASE64_DECODE_TABLE['A' as usize], Some(0));
assert_eq!(BASE64_DECODE_TABLE['B' as usize], Some(1));
for i in 0..64 {
let encoded = BASE64_ENCODE_TABLE[i];
let decoded = BASE64_DECODE_TABLE[encoded as usize];
assert_eq!(decoded, Some(i as u8))
}
}
}