Skip to main content

crypto_service_sdk/
encoding.rs

1// SPDX-License-Identifier: Apache-2.0 OR MIT
2//! Byte strings as the API carries them: lowercase hex or standard base64.
3//!
4//! The OpenAPI document gives each binary field one encoding, and these
5//! types follow it exactly. They only translate between bytes and text;
6//! no cryptography happens here.
7
8use std::fmt;
9use std::ops::Deref;
10
11use base64::engine::general_purpose::STANDARD;
12use base64::Engine as _;
13use serde::de::{self, Visitor};
14use serde::{Deserialize, Deserializer, Serialize, Serializer};
15
16/// Bytes the API carries as lowercase hex (`contentEncoding: base16`):
17/// public keys, signatures, digests, MACs, KEM ciphertexts and HPKE
18/// output. Serialises as lowercase hex and reads either case.
19#[derive(Clone, Default, PartialEq, Eq, Hash)]
20pub struct Hex(Vec<u8>);
21
22/// Bytes the API carries as standard base64 with padding
23/// (`contentEncoding: base64`): AEAD, secretbox, sealed-box, stream,
24/// password-encryption and AES key wrap output.
25#[derive(Clone, Default, PartialEq, Eq, Hash)]
26pub struct Base64(Vec<u8>);
27
28/// A string that is not valid hex or base64.
29#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
30#[error("not valid {0}")]
31pub struct EncodingError(&'static str);
32
33macro_rules! byte_string {
34    ($name:ident) => {
35        impl $name {
36            /// Wraps `bytes`.
37            pub fn new(bytes: impl Into<Vec<u8>>) -> Self {
38                Self(bytes.into())
39            }
40
41            /// The bytes.
42            #[must_use]
43            pub fn as_bytes(&self) -> &[u8] {
44                &self.0
45            }
46
47            /// The bytes, owned.
48            #[must_use]
49            pub fn into_vec(self) -> Vec<u8> {
50                self.0
51            }
52        }
53
54        impl Deref for $name {
55            type Target = [u8];
56
57            fn deref(&self) -> &[u8] {
58                &self.0
59            }
60        }
61
62        impl AsRef<[u8]> for $name {
63            fn as_ref(&self) -> &[u8] {
64                &self.0
65            }
66        }
67
68        impl From<Vec<u8>> for $name {
69            fn from(bytes: Vec<u8>) -> Self {
70                Self(bytes)
71            }
72        }
73
74        impl From<&[u8]> for $name {
75            fn from(bytes: &[u8]) -> Self {
76                Self(bytes.to_vec())
77            }
78        }
79
80        impl<const N: usize> From<[u8; N]> for $name {
81            fn from(bytes: [u8; N]) -> Self {
82                Self(bytes.to_vec())
83            }
84        }
85
86        impl Serialize for $name {
87            fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
88                serializer.serialize_str(&self.to_string())
89            }
90        }
91
92        impl<'de> Deserialize<'de> for $name {
93            fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
94                deserializer.deserialize_str(Text(Self::parse))
95            }
96        }
97    };
98}
99
100byte_string!(Hex);
101byte_string!(Base64);
102
103impl Hex {
104    /// Reads hex text, either case.
105    ///
106    /// # Errors
107    ///
108    /// [`EncodingError`] for an odd length or a non-hex character.
109    pub fn parse(text: &str) -> Result<Self, EncodingError> {
110        decode_hex(text).map(Self)
111    }
112}
113
114impl Base64 {
115    /// Reads standard base64 with padding.
116    ///
117    /// # Errors
118    ///
119    /// [`EncodingError`] for text that is not standard padded base64.
120    pub fn parse(text: &str) -> Result<Self, EncodingError> {
121        STANDARD
122            .decode(text)
123            .map(Self)
124            .map_err(|_| EncodingError("base64"))
125    }
126}
127
128impl fmt::Display for Hex {
129    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
130        f.write_str(&encode_hex(&self.0))
131    }
132}
133
134impl fmt::Debug for Hex {
135    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
136        write!(f, "Hex({self})")
137    }
138}
139
140impl fmt::Display for Base64 {
141    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
142        f.write_str(&STANDARD.encode(&self.0))
143    }
144}
145
146/// Shows the length only: a ciphertext is opaque, and long.
147impl fmt::Debug for Base64 {
148    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
149        write!(f, "Base64(<{} bytes>)", self.0.len())
150    }
151}
152
153/// Lowercase hex of `bytes`.
154pub(crate) fn encode_hex(bytes: &[u8]) -> String {
155    const DIGITS: &[u8; 16] = b"0123456789abcdef";
156    let mut out = String::with_capacity(bytes.len() * 2);
157    for byte in bytes {
158        out.push(char::from(DIGITS[usize::from(byte >> 4)]));
159        out.push(char::from(DIGITS[usize::from(byte & 0x0f)]));
160    }
161    out
162}
163
164/// The bytes of hex text, either case.
165pub(crate) fn decode_hex(text: &str) -> Result<Vec<u8>, EncodingError> {
166    let digits = text.as_bytes();
167    if digits.len() % 2 != 0 {
168        return Err(EncodingError("hex"));
169    }
170    digits
171        .chunks_exact(2)
172        .map(|pair| Ok(nibble(pair[0])? << 4 | nibble(pair[1])?))
173        .collect()
174}
175
176fn nibble(digit: u8) -> Result<u8, EncodingError> {
177    match digit {
178        b'0'..=b'9' => Ok(digit - b'0'),
179        b'a'..=b'f' => Ok(digit - b'a' + 10),
180        b'A'..=b'F' => Ok(digit - b'A' + 10),
181        _ => Err(EncodingError("hex")),
182    }
183}
184
185/// A serde visitor for a string, parsed by `.0`.
186pub(crate) struct Text<F>(pub(crate) F);
187
188impl<T, F> Visitor<'_> for Text<F>
189where
190    F: FnOnce(&str) -> Result<T, EncodingError>,
191{
192    type Value = T;
193
194    fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
195        f.write_str("an encoded byte string")
196    }
197
198    fn visit_str<E: de::Error>(self, text: &str) -> Result<T, E> {
199        (self.0)(text).map_err(E::custom)
200    }
201}
202
203#[cfg(test)]
204mod tests;