1 /*
2  * Copyright (c) 2023 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  * http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 //! base64 decode
17 use crate::ffi;
18 
19 #[allow(unused)]
get_b64_decode_len(in_data: &[u8]) -> Result<(usize, usize), String>20 pub fn get_b64_decode_len(in_data: &[u8]) -> Result<(usize, usize), String>
21 {
22     let len = in_data.len();
23     if len == 0 || len % 4 != 0 { // base64 content len must be a multiple of 4
24         return Err("indata is not an valid base64 data".to_string());
25     }
26     let mut padding = 0usize;
27     if in_data[len - 1] == b'=' {
28         padding += 1;
29     }
30     if in_data[len - 2] == b'=' {
31         padding += 1;
32     }
33     Ok(((len >> 2) * 3, padding)) // 3 binary format bytes => 24bits => 4 base64 format character
34 }
35 
36 #[allow(unused)]
evp_decode_block(in_data: &[u8]) -> Result<Vec<u8>, String>37 pub fn evp_decode_block(in_data: &[u8]) -> Result<Vec<u8>, String>
38 {
39     let (out_len, padding) = get_b64_decode_len(in_data)?;
40     let mut out_data = Vec::<u8>::new();
41     out_data.resize(out_len, 0);
42     if unsafe { ffi::EVP_DecodeBlock(out_data.as_mut_ptr(), in_data.as_ptr(), in_data.len() as i32) } <= 0 {
43         return Err("evp decode failed".to_string());
44     }
45     out_data.truncate(out_len - padding);
46     Ok(out_data)
47 }
48