Skip to main content

ostrya_core/
base64.rs

1//! Standard base64 (RFC 4648) for byte strings of any length.
2//!
3//! [`encode`] writes padded base64, and [`decode`] reads it. The codecs of
4//! [`Checksum`](crate::Checksum) accept 32-byte digests only.
5
6use crate::error::{Error, Result};
7
8const ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
9
10/// Encodes `input` as standard base64 with `=` padding.
11pub fn encode(input: &[u8]) -> String {
12    let mut out = String::with_capacity(input.len().div_ceil(3) * 4);
13    for chunk in input.chunks(3) {
14        let b0 = chunk[0];
15        out.push(ALPHABET[(b0 >> 2) as usize] as char);
16        match chunk.len() {
17            1 => {
18                out.push(ALPHABET[((b0 & 0x03) << 4) as usize] as char);
19                out.push_str("==");
20            }
21            2 => {
22                let b1 = chunk[1];
23                out.push(ALPHABET[(((b0 & 0x03) << 4) | (b1 >> 4)) as usize] as char);
24                out.push(ALPHABET[((b1 & 0x0f) << 2) as usize] as char);
25                out.push('=');
26            }
27            _ => {
28                let (b1, b2) = (chunk[1], chunk[2]);
29                out.push(ALPHABET[(((b0 & 0x03) << 4) | (b1 >> 4)) as usize] as char);
30                out.push(ALPHABET[(((b1 & 0x0f) << 2) | (b2 >> 6)) as usize] as char);
31                out.push(ALPHABET[(b2 & 0x3f) as usize] as char);
32            }
33        }
34    }
35    out
36}
37
38/// Decodes standard base64.
39///
40/// The function removes all trailing `=` characters before the decode, so the
41/// padding is optional. It does not check the unused low bits of the last
42/// character.
43///
44/// # Errors
45///
46/// - [`Error::InvalidBase64`] with the reason `truncated base64 group` if one
47///   character is left after the last full group of four characters. The
48///   function counts the characters after it removes the trailing `=`.
49/// - [`Error::InvalidBase64`] with the reason `invalid base64 character` if a
50///   character is outside the standard alphabet `A`-`Z`, `a`-`z`, `0`-`9`, `+`,
51///   and `/`. This includes white space, the URL-safe characters `-` and `_`,
52///   and an `=` that is not at the end.
53pub fn decode(s: &str) -> Result<Vec<u8>> {
54    let bytes = s.trim_end_matches('=').as_bytes();
55    let full = bytes.len() / 4;
56    let rem = bytes.len() % 4;
57    if rem == 1 {
58        return Err(Error::InvalidBase64("truncated base64 group"));
59    }
60    let mut out = Vec::with_capacity(full * 3 + rem.saturating_sub(1));
61    let mut i = 0;
62    for _ in 0..full {
63        let s0 = val(bytes[i])?;
64        let s1 = val(bytes[i + 1])?;
65        let s2 = val(bytes[i + 2])?;
66        let s3 = val(bytes[i + 3])?;
67        out.push((s0 << 2) | (s1 >> 4));
68        out.push((s1 << 4) | (s2 >> 2));
69        out.push((s2 << 6) | s3);
70        i += 4;
71    }
72    match rem {
73        2 => {
74            let s0 = val(bytes[i])?;
75            let s1 = val(bytes[i + 1])?;
76            out.push((s0 << 2) | (s1 >> 4));
77        }
78        3 => {
79            let s0 = val(bytes[i])?;
80            let s1 = val(bytes[i + 1])?;
81            let s2 = val(bytes[i + 2])?;
82            out.push((s0 << 2) | (s1 >> 4));
83            out.push((s1 << 4) | (s2 >> 2));
84        }
85        _ => {}
86    }
87    Ok(out)
88}
89
90/// Maps one base64 character to its 6-bit value.
91fn val(c: u8) -> Result<u8> {
92    match c {
93        b'A'..=b'Z' => Ok(c - b'A'),
94        b'a'..=b'z' => Ok(c - b'a' + 26),
95        b'0'..=b'9' => Ok(c - b'0' + 52),
96        b'+' => Ok(62),
97        b'/' => Ok(63),
98        _ => Err(Error::InvalidBase64("invalid base64 character")),
99    }
100}
101
102#[cfg(test)]
103mod tests {
104    use super::*;
105
106    #[test]
107    fn rfc4648_vectors() {
108        // The RFC 4648 section 10 test vectors.
109        assert_eq!(encode(b""), "");
110        assert_eq!(encode(b"f"), "Zg==");
111        assert_eq!(encode(b"fo"), "Zm8=");
112        assert_eq!(encode(b"foo"), "Zm9v");
113        assert_eq!(encode(b"foob"), "Zm9vYg==");
114        assert_eq!(encode(b"fooba"), "Zm9vYmE=");
115        assert_eq!(encode(b"foobar"), "Zm9vYmFy");
116    }
117
118    #[test]
119    fn decode_matches_encode() {
120        for input in [
121            b"".as_slice(),
122            b"f",
123            b"fo",
124            b"foo",
125            b"foob",
126            b"fooba",
127            b"foobar",
128        ] {
129            let encoded = encode(input);
130            assert_eq!(decode(&encoded).unwrap(), input);
131        }
132    }
133
134    #[test]
135    fn decode_accepts_unpadded() {
136        assert_eq!(decode("Zg").unwrap(), b"f");
137        assert_eq!(decode("Zm8").unwrap(), b"fo");
138        assert_eq!(decode("Zm9vYg").unwrap(), b"foob");
139    }
140
141    #[test]
142    fn decode_round_trips_binary() {
143        let data: Vec<u8> = (0u16..=255).map(|b| b as u8).collect();
144        assert_eq!(decode(&encode(&data)).unwrap(), data);
145    }
146
147    #[test]
148    fn decode_rejects_bad_input() {
149        assert!(decode("Z").is_err()); // one leftover character
150        assert!(decode("Zg=Z").is_err()); // stray character after padding strip
151        assert!(decode("Zm9 v").is_err()); // internal whitespace
152        assert!(decode("Zm9_").is_err()); // modified-alphabet glyph rejected
153    }
154}