Skip to main content

codec_base64url/
decode.rs

1// SPDX-FileCopyrightText: Copyright © 2026 ReallyMe LLC. All rights reserved
2//
3// SPDX-License-Identifier: Apache-2.0
4
5use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _};
6
7use crate::Base64UrlError;
8
9/// Decode RFC 4648 section 5 Base64URL without padding.
10pub fn base64url_to_bytes(s: &str) -> Result<Vec<u8>, Base64UrlError> {
11    base64url_bytes_to_bytes(s.as_bytes())
12}
13
14/// Decode RFC 4648 section 5 Base64URL bytes without padding.
15///
16/// This is useful for compact JWT/JWS/JWE segments that have already been
17/// split as bytes. It avoids requiring callers to first prove UTF-8 just to
18/// decode an ASCII Base64URL alphabet.
19pub fn base64url_bytes_to_bytes(bytes: &[u8]) -> Result<Vec<u8>, Base64UrlError> {
20    URL_SAFE_NO_PAD
21        .decode(bytes)
22        .map_err(|_| Base64UrlError::Invalid)
23}