rscrypto 0.3.1

Pure Rust cryptography: RSA, Ed25519, X25519, SHA-2/3, BLAKE3, AES-GCM, ChaCha20-Poly1305, Argon2, HMAC/HKDF, CRC. no_std, WASM, hardware acceleration.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
#![allow(clippy::indexing_slicing)]
#![cfg_attr(
  not(any(
    feature = "aes-gcm",
    feature = "aes-gcm-siv",
    feature = "chacha20poly1305",
    feature = "xchacha20poly1305",
    feature = "aegis256",
    feature = "ascon-aead",
    feature = "ed25519",
    feature = "x25519"
  )),
  allow(dead_code, unused_macros)
)]

//! Internal hex encoding, decoding, and formatting utilities.
//!
//! Provides zero-allocation, `no_std`-compatible hex formatting through
//! `core::fmt::Write`. Secret key types use [`DisplaySecret`] for explicit
//! opt-in hex display.

use core::fmt;

/// Hex decoding error.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum InvalidHexError {
  /// Input length is not exactly twice the expected byte count.
  InvalidLength,
  /// A non-hex character was encountered.
  InvalidChar {
    /// The offending byte value.
    byte: u8,
    /// Zero-based position in the hex string.
    index: usize,
  },
}

impl fmt::Display for InvalidHexError {
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    match self {
      Self::InvalidLength => f.write_str("invalid hex length"),
      Self::InvalidChar { byte, index } => {
        write!(f, "invalid hex character 0x{byte:02x} at index {index}")
      }
    }
  }
}

impl core::error::Error for InvalidHexError {}

/// Decode a single hex character to its 4-bit value.
#[inline]
const fn decode_nibble(byte: u8) -> Option<u8> {
  match byte {
    b'0'..=b'9' => Some(byte - b'0'),
    b'a'..=b'f' => Some(byte - b'a' + 10),
    b'A'..=b'F' => Some(byte - b'A' + 10),
    _ => None,
  }
}

/// Decode a hex string into `out`. Accepts mixed case, no `0x` prefix.
///
/// Returns `InvalidHexError::InvalidLength` when `hex.len() != out.len() * 2`.
pub fn from_hex(hex: &str, out: &mut [u8]) -> Result<(), InvalidHexError> {
  let hex = hex.as_bytes();
  if hex.len() != out.len().strict_mul(2) {
    return Err(InvalidHexError::InvalidLength);
  }
  let mut i = 0;
  while i < out.len() {
    let hi_idx = i.strict_mul(2);
    let lo_idx = hi_idx.strict_add(1);
    let hi = match decode_nibble(hex[hi_idx]) {
      Some(v) => v,
      None => {
        return Err(InvalidHexError::InvalidChar {
          byte: hex[hi_idx],
          index: hi_idx,
        });
      }
    };
    let lo = match decode_nibble(hex[lo_idx]) {
      Some(v) => v,
      None => {
        return Err(InvalidHexError::InvalidChar {
          byte: hex[lo_idx],
          index: lo_idx,
        });
      }
    };
    out[i] = (hi << 4) | lo;
    i = i.strict_add(1);
  }
  Ok(())
}

/// Write each byte as two lowercase hex characters.
pub fn fmt_hex_lower(bytes: &[u8], f: &mut fmt::Formatter<'_>) -> fmt::Result {
  for &b in bytes {
    write!(f, "{b:02x}")?;
  }
  Ok(())
}

/// Write each byte as two uppercase hex characters.
pub fn fmt_hex_upper(bytes: &[u8], f: &mut fmt::Formatter<'_>) -> fmt::Result {
  for &b in bytes {
    write!(f, "{b:02X}")?;
  }
  Ok(())
}

/// Explicit opt-in wrapper for displaying secret key bytes as hex.
///
/// Returned by the `display_secret()` method on secret key types. Implements
/// [`Display`](fmt::Display) so you can `format!("{}", key.display_secret())`.
pub struct DisplaySecret<'a>(pub(crate) &'a [u8]);

impl fmt::Display for DisplaySecret<'_> {
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    fmt_hex_lower(self.0, f)
  }
}

impl fmt::Debug for DisplaySecret<'_> {
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    write!(f, "DisplaySecret(\"")?;
    fmt_hex_lower(self.0, f)?;
    write!(f, "\")")
  }
}

// ---------------------------------------------------------------------------
// Macros
// ---------------------------------------------------------------------------

/// Implement `LowerHex`, `UpperHex`, `Display`, `Debug`, and `FromStr` for
/// a public byte-array newtype that has `as_bytes()`, `from_bytes()`, and
/// `LENGTH`.
macro_rules! impl_hex_fmt {
  ($type:ty) => {
    impl core::fmt::LowerHex for $type {
      fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        crate::hex::fmt_hex_lower(self.as_bytes(), f)
      }
    }

    impl core::fmt::UpperHex for $type {
      fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        crate::hex::fmt_hex_upper(self.as_bytes(), f)
      }
    }

    impl core::fmt::Display for $type {
      fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        core::fmt::LowerHex::fmt(self, f)
      }
    }

    impl core::str::FromStr for $type {
      type Err = crate::hex::InvalidHexError;

      fn from_str(s: &str) -> Result<Self, Self::Err> {
        let mut buf = [0u8; Self::LENGTH];
        crate::hex::from_hex(s, &mut buf)?;
        Ok(Self::from_bytes(buf))
      }
    }
  };
}

/// Implement masked `Debug`, `FromStr`, and `display_secret()` for a secret
/// key newtype. Does **not** implement `Display`, `LowerHex`, or `UpperHex`
/// to prevent accidental logging of key material.
macro_rules! impl_hex_fmt_secret {
  ($type:ty) => {
    impl core::str::FromStr for $type {
      type Err = crate::hex::InvalidHexError;

      fn from_str(s: &str) -> Result<Self, Self::Err> {
        let mut buf = [0u8; Self::LENGTH];
        crate::hex::from_hex(s, &mut buf)?;
        Ok(Self::from_bytes(buf))
      }
    }

    impl $type {
      /// Returns a wrapper that displays the key bytes as lowercase hex.
      ///
      /// This is an explicit opt-in for showing secret key material.
      /// The wrapper implements [`Display`](core::fmt::Display).
      #[must_use]
      pub fn display_secret(&self) -> crate::hex::DisplaySecret<'_> {
        crate::hex::DisplaySecret(self.as_bytes())
      }
    }
  };
}

/// Implement `serde::Serialize` and `serde::Deserialize` for a byte-array
/// newtype with `as_bytes() -> &[u8; N]`, `from_bytes([u8; N]) -> Self`,
/// and `LENGTH`.
#[cfg(feature = "serde")]
macro_rules! impl_serde_bytes_inner {
  ($type:ty, $feature:literal) => {
    #[cfg_attr(docsrs, doc(cfg(feature = $feature)))]
    impl serde::Serialize for $type {
      fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.serialize_bytes(self.as_bytes())
      }
    }

    #[cfg_attr(docsrs, doc(cfg(feature = $feature)))]
    impl<'de> serde::Deserialize<'de> for $type {
      fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        struct ByteVisitor;

        impl<'de> serde::de::Visitor<'de> for ByteVisitor {
          type Value = $type;

          fn expecting(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
            write!(f, "{} bytes", <$type>::LENGTH)
          }

          fn visit_bytes<E: serde::de::Error>(self, v: &[u8]) -> Result<Self::Value, E> {
            let arr: [u8; <$type>::LENGTH] = v.try_into().map_err(|_| E::invalid_length(v.len(), &self))?;
            Ok(<$type>::from_bytes(arr))
          }

          fn visit_seq<A: serde::de::SeqAccess<'de>>(self, mut seq: A) -> Result<Self::Value, A::Error> {
            let mut arr = [0u8; <$type>::LENGTH];
            for (i, byte) in arr.iter_mut().enumerate() {
              *byte = seq
                .next_element()?
                .ok_or_else(|| serde::de::Error::invalid_length(i, &self))?;
            }
            Ok(<$type>::from_bytes(arr))
          }
        }

        deserializer.deserialize_bytes(ByteVisitor)
      }
    }
  };
}

#[cfg(feature = "serde")]
macro_rules! impl_serde_bytes {
  ($type:ty) => {
    impl_serde_bytes_inner!($type, "serde");
  };
}

// No-op when serde feature is disabled.
#[cfg(not(feature = "serde"))]
macro_rules! impl_serde_bytes {
  ($type:ty) => {};
}

/// Implement `serde` for secret material behind the explicit `serde-secrets`
/// feature. This keeps broad DTO serialization from silently exporting keys.
#[cfg(feature = "serde-secrets")]
macro_rules! impl_serde_secret_bytes {
  ($type:ty) => {
    impl_serde_bytes_inner!($type, "serde-secrets");
  };
}

#[cfg(not(feature = "serde-secrets"))]
macro_rules! impl_serde_secret_bytes {
  ($type:ty) => {};
}

/// Implement [`ConstantTimeEq`](crate::traits::ConstantTimeEq) for a type
/// whose secret material lives in a single byte-array field.
///
/// Default form uses the tuple field `.0`; pass a field name for named structs.
macro_rules! impl_ct_eq {
  ($type:ty) => {
    impl crate::traits::ConstantTimeEq for $type {
      #[inline]
      fn ct_eq(&self, other: &Self) -> bool {
        crate::traits::ct::constant_time_eq(&self.0, &other.0)
      }
    }
  };
  ($type:ty, $field:ident) => {
    impl crate::traits::ConstantTimeEq for $type {
      #[inline]
      fn ct_eq(&self, other: &Self) -> bool {
        crate::traits::ct::constant_time_eq(&self.$field, &other.$field)
      }
    }
  };
}

/// Generate a `random()` constructor that fills `Self::LENGTH` bytes from
/// the operating system CSPRNG via `getrandom`.
///
/// Invoke inside an `impl` block for a tuple-struct with `LENGTH` and
/// `from_bytes`.
macro_rules! impl_getrandom {
  () => {
    /// Generate a random instance using the operating system's CSPRNG.
    ///
    /// # Panics
    ///
    /// Panics if the platform entropy source is unavailable.
    #[cfg(feature = "getrandom")]
    #[cfg_attr(docsrs, doc(cfg(feature = "getrandom")))]
    #[inline]
    #[must_use]
    pub fn random() -> Self {
      match Self::try_random() {
        Ok(value) => value,
        Err(e) => panic!("getrandom failed: {e}"),
      }
    }

    /// Try to generate a random instance from the platform entropy source.
    ///
    /// # Errors
    ///
    /// Returns a getrandom error if the platform entropy source is unavailable.
    #[cfg(feature = "getrandom")]
    #[cfg_attr(docsrs, doc(cfg(feature = "getrandom")))]
    #[inline]
    pub fn try_random() -> Result<Self, getrandom::Error> {
      let mut bytes = [0u8; Self::LENGTH];
      getrandom::fill(&mut bytes).map(|()| Self(bytes))
    }
  };
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
  use super::*;

  #[test]
  fn hex_lower_round_trip() {
    let bytes = [0xde, 0xad, 0xbe, 0xef];
    let hex = alloc::format!("{}", DisplaySecret(&bytes));
    assert_eq!(hex, "deadbeef");

    let mut out = [0u8; 4];
    from_hex(&hex, &mut out).unwrap();
    assert_eq!(out, bytes);
  }

  #[test]
  fn hex_upper() {
    struct W([u8; 2]);
    impl fmt::Display for W {
      fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt_hex_upper(&self.0, f)
      }
    }
    assert_eq!(alloc::format!("{}", W([0xab, 0xcd])), "ABCD");
  }

  #[test]
  fn from_hex_mixed_case() {
    let mut out = [0u8; 3];
    from_hex("aAbBcC", &mut out).unwrap();
    assert_eq!(out, [0xaa, 0xbb, 0xcc]);
  }

  #[test]
  fn from_hex_invalid_length() {
    let mut out = [0u8; 2];
    assert_eq!(from_hex("abc", &mut out), Err(InvalidHexError::InvalidLength));
  }

  #[test]
  fn from_hex_invalid_char() {
    let mut out = [0u8; 2];
    let err = from_hex("abzz", &mut out).unwrap_err();
    assert_eq!(err, InvalidHexError::InvalidChar { byte: b'z', index: 2 });
  }

  #[test]
  fn display_secret_debug() {
    let bytes = [0x42; 4];
    let d = DisplaySecret(&bytes);
    assert_eq!(alloc::format!("{d:?}"), "DisplaySecret(\"42424242\")");
  }

  #[test]
  fn error_display() {
    assert_eq!(
      alloc::format!("{}", InvalidHexError::InvalidLength),
      "invalid hex length"
    );
    assert_eq!(
      alloc::format!("{}", InvalidHexError::InvalidChar { byte: b'z', index: 5 }),
      "invalid hex character 0x7a at index 5"
    );
  }
}