dup_crypto/bases/
b64.rs

1//  Copyright (C) 2020 Éloïs SANCHEZ.
2//
3// This program is free software: you can redistribute it and/or modify
4// it under the terms of the GNU Affero General Public License as
5// published by the Free Software Foundation, either version 3 of the
6// License, or (at your option) any later version.
7//
8// This program is distributed in the hope that it will be useful,
9// but WITHOUT ANY WARRANTY; without even the implied warranty of
10// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11// GNU Affero General Public License for more details.
12//
13// You should have received a copy of the GNU Affero General Public License
14// along with this program.  If not, see <https://www.gnu.org/licenses/>.
15
16//! Provide base64 convertion tools
17
18use crate::bases::BaseConversionError;
19
20/// Create an array of 64 bytes from a Base64 string.
21pub fn str_base64_to64bytes(base64_data: &str) -> Result<[u8; 64], BaseConversionError> {
22    if base64_data.len() != 88 {
23        Err(BaseConversionError::InvalidBaseConverterLength)
24    } else if base64_data.ends_with("==") {
25        let mut u8_array = [0; 64];
26        let written_len =
27            base64::decode_config_slice(base64_data, base64::STANDARD, &mut u8_array)?;
28
29        if written_len == 64 {
30            Ok(u8_array)
31        } else {
32            Err(BaseConversionError::InvalidLength {
33                expected: 64,
34                found: written_len,
35            })
36        }
37    } else {
38        Err(BaseConversionError::InvalidCharacter {
39            character: base64_data.as_bytes()[86] as char,
40            offset: 86,
41        })
42    }
43}
44
45#[cfg(test)]
46mod tests {
47    use super::*;
48
49    #[test]
50    fn test_wrong_b64_str_do_not_panic() {
51        assert!(str_base64_to64bytes("42yQm4hGTJYWkPg39hQAUgP6S6EQ4vTfXdJuxKEHL1ih6YHiDL2hcwrFgBHjXLRgxRhj2VNVqqc6b4JayKqTE14r").is_err());
52    }
53}