Skip to main content

json_digest/
nonce.rs

1use alloc::string::String;
2#[cfg(feature = "std")]
3use rand::{Rng, rng};
4use serde::{Deserialize, Serialize};
5
6/// Multibase-encoded random content, e.g. "urvU8F6HmEol5zOmHh_nnS1RiX5r3T2t9U_d_kQY7ZC-I"
7///
8/// The amount of entropy is chosen as 264 bits to end up with full digits in the base64
9/// encoding used.
10#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
11#[serde(transparent)]
12pub struct Nonce264(pub String);
13
14impl Nonce264 {
15    /// Generates a new [`Nonce264`]. Uses the `getrandom` crate to find the best source of entropy on the platform.
16    /// In JavaScript tests you might need to refer to <https://github.com/jsdom/jsdom/issues/1612> for
17    /// how to fix phantom browsers to comply with HTML5 specs.
18    #[cfg(feature = "std")]
19    pub fn generate() -> Self {
20        let mut arr = [0u8; 33];
21        rng().fill_bytes(&mut arr[..]);
22        let encoded = multibase::encode(multibase::Base::Base64Url, &arr[..]);
23        Self(encoded)
24    }
25}