codec_base64/decode.rs
1// SPDX-FileCopyrightText: Copyright © 2026 ReallyMe LLC. All rights reserved
2//
3// SPDX-License-Identifier: MIT OR Apache-2.0
4
5use base64::{decoded_len_estimate, engine::general_purpose::STANDARD, Engine as _};
6use zeroize::Zeroizing;
7
8use crate::error::Base64Error;
9
10/// Decode standard padded Base64 from RFC 4648.
11pub fn base64_to_bytes(input: &str) -> Result<Vec<u8>, Base64Error> {
12 // A late alphabet or padding error may follow successfully decoded secret
13 // bytes. Keep ownership here so the partial output is wiped on failure.
14 let mut output = Zeroizing::new(vec![0_u8; decoded_len_estimate(input.len())]);
15 let length = STANDARD
16 .decode_slice(input.as_bytes(), output.as_mut_slice())
17 .map_err(|_| Base64Error::Invalid)?;
18 output.truncate(length);
19 Ok(core::mem::take(&mut *output))
20}