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
use std::{fmt, error::Error, str};
const TABLE: &str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
#[derive(Debug, PartialEq, Eq, Clone)]
pub enum Base64Error {
InvalidDataLenght,
InvalidBase64Data,
}
impl Error for Base64Error {}
impl fmt::Display for Base64Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("Decoding error : ")?;
f.write_str(match self {
Base64Error::InvalidDataLenght => "Invalid input data length",
Base64Error::InvalidBase64Data => "Invalid base64 data",
})
}
}
impl From<std::string::FromUtf8Error> for Base64Error {
fn from(_e: std::string::FromUtf8Error) -> Base64Error {
Base64Error::InvalidBase64Data
}
}
pub trait Base64 {
fn encode(&self) -> String;
fn decode(&self) -> Result<String, Base64Error>;
}
impl Base64 for String {
fn encode(&self) -> String {
let a = self.as_bytes();
let mut octal = String::new();
let mut i = 0;
let inputlenmod = a.len() % 3;
let blockstoprocess = match inputlenmod {
0 => a.len(),
_ => a.len() - inputlenmod,
};
let padding = match inputlenmod {
0 => 0,
_ => 3 - (a.len() - blockstoprocess),
};
while i < blockstoprocess {
octal.push_str(
format!("{:o}", u32::from_be_bytes([0, a[i], a[i + 1], a[i + 2]])).as_str(),
);
i += 3;
}
match padding {
1 => {
octal
.push_str(format!("{:o}", u32::from_be_bytes([0, a[i], a[i + 1], 0])).as_str());
}
2 => {
octal.push_str(format!("{:o}", u32::from_be_bytes([0, a[i], 0, 0])).as_str());
}
_ => {}
};
let sextets = octal
.as_bytes()
.chunks(2)
.map(|s| usize::from_str_radix(str::from_utf8(s).unwrap(), 8).unwrap())
.collect::<Vec<usize>>();
#[cfg(debug_assertions)]
{
println!("Input as bytes : {:?}", a);
println!("Length of string to encode : {}", a.len());
println!("24 bits blocks to process : {}", blockstoprocess);
println!("Padding : {}", padding);
println!("Padded input as octal : {}", octal);
println!("Decimal encoded data : {:?}", sextets);
}
let mut result = String::new();
for i in 0..(sextets.len() - padding) {
result.push_str(&TABLE[sextets[i]..(sextets[i] + 1)]);
}
match padding {
1 => result.push_str("="),
2 => result.push_str("=="),
_ => {}
};
result
}
fn decode(&self) -> Result<String, Base64Error> {
let mut encoded_data = self.to_owned();
let padding = encoded_data.matches("=").count();
if encoded_data.len() % 4 != 0 {
return Err(Base64Error::InvalidDataLenght);
};
for _ in 0..padding {
encoded_data.pop();
}
for _ in 0..padding {
encoded_data.push_str("A");
}
let octal = encoded_data
.chars()
.map(|c| format!("{:02o}", TABLE.find(c).unwrap_or(65)))
.collect::<Vec<String>>();
let mut octalsextets = Vec::new();
let mut n = 0;
while n < encoded_data.len() {
let mut s = String::new();
for i in 0..4 {
if octal[n + i] == "101" { return Err(Base64Error::InvalidBase64Data) }
s.push_str(octal[n + i].as_str());
}
n += 4;
octalsextets.push(s);
}
let decimal = octalsextets
.iter()
.map(|s| usize::from_str_radix(s, 8).unwrap())
.collect::<Vec<usize>>();
let mut bytes: Vec<u8> = Vec::new();
for i in 0..decimal.len() {
let a = decimal[i].to_be_bytes();
bytes.push(a[5]);
bytes.push(a[6]);
bytes.push(a[7]);
}
for _ in 0..padding {
bytes.pop();
}
#[cfg(debug_assertions)]
{
println!("Encoded data length : {}", encoded_data.len());
println!("24 bits blocks to process : {}", encoded_data.len() / 4);
println!("Padding : {}", padding);
println!("Octal indexes of encoded characters : {:?}", octal);
println!("Gathering sextets 4 by 4 : {:?}", octalsextets);
println!("Decoded data (4 sextets to 3 bytes) : {:x?}", decimal);
println!("Decoded bytes : {:x?}", &bytes);
}
let result = String::from_utf8(bytes)?;
Ok(result)
}
}
#[cfg(test)]
mod tests {
use crate::Base64;
#[test]
fn encode_works() {
assert_eq!(
"SmUgdCdhaW1lIG1hIGNow6lyaWU=",
String::from("Je t'aime ma chérie").encode()
);
}
#[test]
fn decode_works() {
assert_eq!(
Ok(String::from("Joyeux anniversaire !")),
String::from("Sm95ZXV4IGFubml2ZXJzYWlyZSAh").decode()
);
}
#[test]
fn datalength_check() {
assert_eq!(
Err(crate::Base64Error::InvalidDataLenght),
String::from("TWF").decode()
);
}
#[test]
fn validb64data_check() {
assert_eq!(
Err(crate::Base64Error::InvalidBase64Data),
String::from("TWF$").decode()
);
}
}