encodex 0.2.0

Implementation of and cryptanalysis tool for legacy and modern codes, ciphers and hashes.
Documentation
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
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
// Copyright (C) 2022,2023  Fabian Moos
// This file is part of encodex.
//
// encodex is free software: you can redistribute it and/or modify it under the terms of the GNU
// General Public License as published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// encodex is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
// even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// General Public License for more details.
//
// You should have received a copy of the GNU General Public License along with encodex. If not,
// see <https://www.gnu.org/licenses/>.
//

//! En-/Decoder for `Base64`, `Base64Url`, `Base32`, `Base32Hex` and `Base16` encodings as
//! defined by **`RFC 4648`**.
//!
//! A detailed description of every code can be found on the respective documentation page.

#[cfg(any(
feature = "base16",
feature = "hex"
))]
mod base16;
#[cfg(feature = "base32")]
mod base32;
#[cfg(feature = "base32hex")]
mod base32hex;
#[cfg(feature = "base64")]
mod base64;
#[cfg(feature = "base64url")]
mod base64url;



////////////////////////////////////////////////////////////////////////////////////////////////////
////////// PUBLIC INTERFACE OF MODULE base_encoding ////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////
#[cfg(any(
feature = "base16",
feature = "hex"
))]
pub use base16::Base16Context;
#[cfg(feature = "base32")]
pub use base32::Base32Context;
#[cfg(feature = "base32hex")]
pub use base32hex::Base32HexContext;
#[cfg(feature = "base64")]
pub use base64::Base64Context;
#[cfg(feature = "base64url")]
pub use base64url::Base64UrlContext;
////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////

#[cfg(any(
feature = "base32",
feature = "base32hex",
feature = "base64",
feature = "base64url"
))]
use std::collections::HashMap;



/// This is one of the valid padding patterns of the `base32` and `base32hex` ciphertexts.
#[cfg(any(
feature = "base32",
feature = "base32hex"
))]
const ZERO_PADDING_BYTES_BIT_STRING: u64 = 0x0;
/// This is one of the valid padding patterns of the `base32` and `base32hex` ciphertexts.
#[cfg(any(
feature = "base32",
feature = "base32hex"
))]
const ONE_PADDING_BYTE_BIT_STRING: u64 = 0x3d;
/// This is one of the valid padding patterns of the `base32` and `base32hex` ciphertexts.
#[cfg(any(
feature = "base32",
feature = "base32hex"
))]
const THREE_PADDING_BYTE_BIT_STRING: u64 = 0x3d_3d3d;
/// This is one of the valid padding patterns of the `base32` and `base32hex` ciphertexts.
#[cfg(any(
feature = "base32",
feature = "base32hex"
))]
const FOUR_PADDING_BYTE_BIT_STRING: u64 = 0x3d3d_3d3d;
/// This is one of the valid padding patterns of the `base32` and `base32hex` ciphertexts.
#[cfg(any(
feature = "base32",
feature = "base32hex"
))]
const SIX_PADDING_BYTE_BIT_STRING: u64 = 0x3d3d_3d3d_3d3d;



/// Generic function for decoding ***base32*** ciphertexts.
///
/// The only difference between `base32` and `base32hex` is the alphabet. The decode algorithm is
/// the same for both variants. This function implements the generic decode algorithm and is called
/// by the respective [`decode`](crate::code::Decode::decode) method of both [`CryptographicAtom`]s
/// with their respective alphabets.
///
/// This function does not validate the ciphertext. The validation must be performed by the caller.
#[cfg(any(
feature = "base32",
feature = "base32hex"
))]
fn base32_decode(
    ciphertext: &Vec<u8>,
    alphabet: HashMap<u8, u64>,
) -> Vec<u8> {
    let mut plaintext = Vec::new();
    let mut iter = ciphertext.iter();
    let mut maybe_next = iter.next();

    while maybe_next != None {
        let mut block: u64 = 0;
        // Get first character of block.
        let mut byte = maybe_next.unwrap();
        let mut character = *alphabet.get(byte).unwrap();
        // 0x0000'0000 0000'0000 0000'0000 0000'0000 0000'0000
        block |= character << 35;

        // Get second character of block.
        byte = iter.next().unwrap();
        character = *alphabet.get(byte).unwrap();
        block |= character << 30;
        // Add first byte of block to the plaintext because all of its bits have been acquired.
        plaintext.push((block >> 32) as u8);

        // Get third character of block.
        byte = iter.next().unwrap();
        character = *alphabet.get(byte).unwrap();
        if character != 32 {
            block |= character << 25;
        } else {
            break;
        }

        // Get fourth character of block.
        byte = iter.next().unwrap();
        character = *alphabet.get(byte).unwrap();
        block |= character << 20;
        // Add second byte of block to the plaintext because all of its bits have been acquired.
        plaintext.push((block >> 24) as u8);

        // Get fifth character of block
        byte = iter.next().unwrap();
        character = *alphabet.get(byte).unwrap();
        if character != 32 {
            block |= character << 15;
            // Add third byte of block to the plaintext because all of its bits have been acquired.
            plaintext.push((block >> 16) as u8);
        }

        // Get sixth character of block
        byte = iter.next().unwrap();
        character = *alphabet.get(byte).unwrap();
        if character != 32 {
            block |= character << 10;
        } else {
            break;
        }

        // Get seventh character of block
        byte = iter.next().unwrap();
        character = *alphabet.get(byte).unwrap();
        block |= character << 5;
        // Add fourth byte of block to the plaintext because all of its bits have been acquired.
        plaintext.push((block >> 8) as u8);

        // Get eighth character of block.
        byte = iter.next().unwrap();
        character = *alphabet.get(byte).unwrap();
        if character != 32 {
            block |= character;
            // Add fifth byte of block to the plaintext because all of its bits have been acquired.
            plaintext.push(block as u8);
        }

        // Maybe get next byte.
        maybe_next = iter.next();
    }

    plaintext
}

/// Generic function for encoding ***base32*** ciphertexts.
///
/// The only difference between `base32` and `base32hex` is the alphabet. The algorithm is the same
/// for both variants. This function implements the generic encode algorithm and is called by the
/// respective [`encode`](crate::code::Encode::encode) method of both [`CryptographicAtom`]s with
/// their respective alphabets.
#[cfg(any(
feature = "base32",
feature = "base32hex"
))]
fn base32_encode(
    plaintext: &Vec<u8>,
    alphabet: [u8; 33],
) -> Vec<u8> {
    let mut ciphertext = Vec::new();
    let mut iter = plaintext.iter();
    let mut byte = iter.next();
    while byte != None {
        let mut block: u64 = 0;

        // Get and prepare bytes for next character.
        for count in 1..=5 {
            if let Some(byte) = byte {
                let value = byte.clone();
                match count {
                    1 => {
                        // 0b*111'1100 0000'0000 0000'0000 0000'0000 0000'0000 0000'0000
                        block |= ((value & 0b1111_1000) as u64) << 39;
                        // 0b*---'--*1 1100'0000 0000'0000 0000'0000 0000'0000 0000'0000
                        block |= ((value & 0b0000_0111) as u64) << 38;
                    }
                    2 => {
                        // 0b*---'--*- --11'*000 0000'0000 0000'0000 0000'0000 0000'0000
                        block |= ((value & 0b1100_0000) as u64) << 30;
                        // 0b*---'--*- ----'*111 11*0'0000 0000'0000 0000'0000 0000'0000
                        block |= ((value & 0b0011_1110) as u64) << 29;
                        // 0b*---'--*- ----'*--- --*1'0000 0000'0000 0000'0000 0000'0000
                        block |= ((value & 0b0000_0001) as u64) << 28;
                    }
                    3 => {
                        // 0b*---'--*- ----'*--- --*-'1111 *000'0000 0000'0000 0000'0000
                        block |= ((value & 0b1111_0000) as u64) << 20;
                        // 0b*---'--*- ----'*--- --*-'---- *111'1000 0000'0000 0000'0000
                        block |= ((value & 0b0000_1111) as u64) << 19;
                    }
                    4 => {
                        // 0b*---'--*- ----'*--- --*-'---- *---'-1*0 0000'0000 0000'0000
                        block |= ((value & 0b1000_0000) as u64) << 11;
                        // 0b*---'--*- ----'*--- --*-'---- *---'--*1 1111'*000 0000'0000
                        block |= ((value & 0b0111_1100) as u64) << 10;
                        // 0b*---'--*- ----'*--- --*-'---- *---'--*- ----'*110 0000'0000
                        block |= ((value & 0b0000_0011) as u64) << 9;
                    }
                    _ => {
                        // 0b*---'--*- ----'*--- --*-'---- *---'--*- ----'*--1 11*0'0000
                        block |= ((value & 0b1110_0000) as u64) << 1;
                        // 0b*---'--*- ----'*--- --*-'---- *---'--*- ----'*--- --*1'1111
                        block |= (value & 0b0001_1111) as u64;
                    }
                }
            } else {
                match count {
                    2 => {
                        block |= 0b1_000_0000_0000_0000_0000_0000_0000_0000_0000;
                        block |= 0b10_0000_0000_0000_0000_0000_0000_0000;
                    }
                    3 => {
                        block |= 0b1000_0000_0000_0000_0000_0000;
                    }
                    4 => {
                        block |= 0b10_0000_0000_0000_0000;
                        block |= 0b1000_0000_0000;
                    }
                    _ => {
                        block |= 0b10_0000;
                    }
                }
            }
            byte = iter.next();
        }

        // Create Base64 characters from prepared u32 block
        let bits_per_ciphertext_value = 6;
        for pos in (0_u64..8_u64).rev() {
            // 0b*---'--*- ----'*--- --*-'---- *---'--*- ----'*--- --*-'----
            ciphertext.push(
                alphabet[((block >> (pos * bits_per_ciphertext_value)) & 0b11_1111) as usize]
            );
        }
    }
    ciphertext
}

/// Generic function for decoding ***base64*** ciphertexts.
///
/// The only difference between `base64` and `base64url` is the alphabet. The decode algorithm is
/// the same for both variants. This function implements the generic decode algorithm and is called
/// by the respective [`decode`](crate::code::Decode::decode) method of both [`CryptographicAtom`]s
/// with their respective alphabets.
///
/// This function does not validate the ciphertext. The validation must be performed by the caller.
#[cfg(any(
feature = "base64",
feature = "base64url"
))]
fn base64_decode(
    ciphertext: &Vec<u8>,
    alphabet: HashMap<u8, u32>,
) -> Vec<u8> {
    let mut plaintext = Vec::new();
    let mut iter = ciphertext.iter();
    let mut maybe_next = iter.next();

    while maybe_next != None {
        let mut block: u32 = 0;
        // Get first character of block.
        let mut byte = maybe_next.unwrap();
        let mut character = *alphabet.get(byte).unwrap();
        block |= character << 18;

        // Get second character of block.
        byte = iter.next().unwrap();
        character = *alphabet.get(byte).unwrap();
        block |= character << 12;
        // Add first byte of block to the plaintext because all of its bits have been
        // acquired.
        plaintext.push((block >> 16) as u8);

        // Get third character of block.
        byte = iter.next().unwrap();
        character = *alphabet.get(byte).unwrap();
        if character != 64 {
            block |= character << 6;
            // Add second byte of block to the plaintext because all of its bits have been
            // acquired.
            plaintext.push((block >> 8) as u8);
        }

        // Get fourth character of block.
        byte = iter.next().unwrap();
        character = *alphabet.get(byte).unwrap();
        if character != 64 {
            block |= character;
            // Add last byte of block to the plaintext because all bits of the block have
            // been acquired.
            plaintext.push(block as u8);
        }

        // Maybe get next byte.
        maybe_next = iter.next();
    }
    plaintext
}

/// Generic function for encoding ***base64*** ciphertexts.
///
/// The only difference between `base64` and `base64url` is the alphabet. The algorithm is the same
/// for both variants. This function implements the generic encode algorithm and is called by the
/// respective [`encode`](crate::code::Encode::encode) method of both [`CryptographicAtom`]s with
/// their respective alphabets.
#[cfg(any(
feature = "base64",
feature = "base64url"
))]
fn base64_encode(
    plaintext: &Vec<u8>,
    alphabet: [u8; 65],
) -> Vec<u8> {
    let mut ciphertext = Vec::new();
    let mut iter = plaintext.iter();
    let mut byte = iter.next();
    while byte != None {
        let mut block: u32 = 0;

        // Get and prepare bytes for next character.
        for count in 1..=3 {
            if let Some(byte) = byte {
                let value = byte.clone();
                match count {
                    1 => {
                        // 0b0000'*111 111*'0000 0000'0000 0000'0000
                        block |= ((value & 0b1111_1100) as u32) << 19;
                        // 0b0000'*--- ---*'1100 0000'0000 0000'0000
                        block |= ((value & 0b0000_0011) as u32) << 18;
                    }
                    2 => {
                        // 0b0000'*--- ---*'--11 11*0'0000 0000'0000
                        block |= ((value & 0b1111_0000) as u32) << 10;
                        // 0b0000'*--- ---*'---- --*1'1110 0000'0000
                        block |= ((value & 0b0000_1111) as u32) << 9;
                    }
                    _ => {
                        // 0b0000'*--- ---*'---- --*-'---1 1*00'0000
                        block |= ((value & 0b1100_0000) as u32) << 1;
                        // 0b0000'*--- ---*'---- --*-'---- -*11'1111
                        block |= (value & 0b0011_1111) as u32;
                    }
                }
            } else {
                match count {
                    2 => { block |= 0b10_0000_0000_0000; }
                    _ => { block |= 0b100_0000; }
                }
            }
            byte = iter.next();
        }

        // Create Base64 characters from prepared u32 block
        for pos in (0_u32..4_u32).rev() {
            // 0b0000'*--- ---*'---- --*-'---- -*--'----
            ciphertext.push(alphabet[((block >> (pos * 7)) & 0b111_1111) as usize]);
        }
    }
    ciphertext
}