Skip to main content

wsts/
util.rs

1use aes_gcm::{aead::Aead, Aes256Gcm, KeyInit, Nonce};
2use elliptic_curve::{
3    hash2curve::{ExpandMsg, ExpandMsgXmd, Expander},
4    Error as EllipticCurveError,
5};
6use rand_core::{CryptoRng, OsRng, RngCore};
7use sha2::{Digest, Sha256};
8
9use crate::{
10    curve::{point::Point, scalar::Scalar},
11    errors::EncryptionError,
12};
13
14/// Size of the AES-GCM nonce
15pub const AES_GCM_NONCE_SIZE: usize = 12;
16
17/// Expands a message using the XMD (eXpandable Message Digest) method with SHA-256, and reduces
18/// the result modulo the curve order to produce a `Scalar`.
19///
20/// # Arguments
21/// - `msg`: The input message to be expanded.
22/// - `dst`: A domain separation tag (DST). Must be 255 bytes or fewer, as required by the
23///   hash-to-curve specification.
24///
25/// # Returns
26/// - `Ok(Scalar)`: A scalar derived by expanding and reducing the message.
27/// - `Err(EllipticCurveError)`: If `dst` is longer than 255 bytes
28pub fn expand_to_scalar(msg: &[u8], dst: &[u8]) -> Result<Scalar, EllipticCurveError> {
29    // The requested output length (32 bytes) means that the underlying hash function will not fail.
30    let mut buf = [0u8; 32];
31    // This will only fail if the dst exceeds 255 bytes.
32    ExpandMsgXmd::<Sha256>::expand_message(&[msg], &[dst], buf.len())?.fill_bytes(&mut buf);
33    Ok(Scalar::from(buf))
34}
35
36/// Digest the hasher to a Scalar
37pub fn hash_to_scalar(hasher: &mut Sha256) -> Scalar {
38    let h = hasher.clone();
39    let hash = h.finalize();
40    let mut hash_bytes: [u8; 32] = [0; 32];
41    hash_bytes.clone_from_slice(hash.as_slice());
42
43    Scalar::from(hash_bytes)
44}
45
46/// Do a Diffie-Hellman key exchange to create a shared secret from the passed private/public keys
47pub fn make_shared_secret(private_key: &Scalar, public_key: &Point) -> [u8; 32] {
48    let shared_key = private_key * public_key;
49
50    make_shared_secret_from_key(&shared_key)
51}
52
53/// Create a shared secret from the passed Diffie-Hellman shared key
54pub fn make_shared_secret_from_key(shared_key: &Point) -> [u8; 32] {
55    ansi_x963_derive_key(
56        shared_key.compress().as_bytes(),
57        "DH_SHARED_SECRET_KEY/".as_bytes(),
58    )
59}
60
61/// Derive a shared key using the ANSI-x963 standard
62/// <https://www.secg.org/sec1-v2.pdf> (section 3.6.1)
63pub fn ansi_x963_derive_key(shared_key: &[u8], shared_info: &[u8]) -> [u8; 32] {
64    let mut hasher = Sha256::new();
65    let counter = 1u32;
66
67    hasher.update(shared_key);
68    hasher.update(counter.to_be_bytes());
69    hasher.update(shared_info);
70
71    let hash = hasher.finalize();
72    let mut bytes = [0u8; 32];
73
74    bytes.clone_from_slice(hash.as_slice());
75    bytes
76}
77
78/// Encrypt the passed data using the key
79pub fn encrypt<RNG: RngCore + CryptoRng>(
80    key: &[u8; 32],
81    data: &[u8],
82    rng: &mut RNG,
83) -> Result<Vec<u8>, EncryptionError> {
84    let mut nonce_bytes = [0u8; AES_GCM_NONCE_SIZE];
85
86    rng.fill_bytes(&mut nonce_bytes);
87
88    let nonce_vec = nonce_bytes.to_vec();
89    let nonce = Nonce::from_slice(&nonce_vec);
90    let cipher = Aes256Gcm::new(key.into());
91    let cipher_vec = cipher.encrypt(nonce, data.to_vec().as_ref())?;
92    let mut bytes = Vec::new();
93
94    bytes.extend_from_slice(&nonce_vec);
95    bytes.extend_from_slice(&cipher_vec);
96
97    Ok(bytes)
98}
99
100/// Decrypt the passed data using the key
101pub fn decrypt(key: &[u8; 32], data: &[u8]) -> Result<Vec<u8>, EncryptionError> {
102    let Some(nonce_data) = data.get(..AES_GCM_NONCE_SIZE) else {
103        return Err(EncryptionError::MissingNonce);
104    };
105    let Some(cipher_data) = data.get(AES_GCM_NONCE_SIZE..) else {
106        return Err(EncryptionError::MissingData);
107    };
108    if cipher_data.is_empty() {
109        return Err(EncryptionError::MissingData);
110    }
111    let nonce = Nonce::from_slice(nonce_data);
112    let cipher = Aes256Gcm::new(key.into());
113
114    Ok(cipher.decrypt(nonce, cipher_data)?)
115}
116
117/// Creates a new random number generator.
118pub fn create_rng() -> impl RngCore + CryptoRng {
119    OsRng
120}
121
122#[cfg(test)]
123mod test {
124    use super::*;
125    use crate::curve::{point::Point, scalar::Scalar};
126
127    #[test]
128    #[allow(non_snake_case)]
129    fn test_shared_secret() {
130        let mut rng = create_rng();
131
132        let x = Scalar::random(&mut rng);
133        let y = Scalar::random(&mut rng);
134
135        let X = Point::from(x);
136        let Y = Point::from(y);
137
138        let xy = make_shared_secret(&x, &Y);
139        let yx = make_shared_secret(&y, &X);
140
141        assert_eq!(xy, yx);
142    }
143
144    #[test]
145    #[allow(non_snake_case)]
146    fn test_encrypt_decrypt() {
147        let mut rng = create_rng();
148        let msg = "It was many and many a year ago, in a kingdom by the sea...";
149
150        let x = Scalar::random(&mut rng);
151        let y = Scalar::random(&mut rng);
152
153        let X = Point::from(x);
154        let Y = Point::from(y);
155
156        let xy = make_shared_secret(&x, &Y);
157        let yx = make_shared_secret(&y, &X);
158
159        let cipher = encrypt(&xy, msg.as_bytes(), &mut rng).unwrap();
160        let plain = decrypt(&yx, &cipher).unwrap();
161
162        assert_eq!(msg.as_bytes(), &plain);
163
164        let missing_nonce = &cipher[..AES_GCM_NONCE_SIZE - 1];
165        match decrypt(&yx, missing_nonce) {
166            Err(EncryptionError::MissingNonce) => {}
167            Err(e) => panic!("expected MissingNonce got Err({e})"),
168            Ok(_) => panic!("expected MissingNonce got Ok()"),
169        }
170
171        let missing_data = &cipher[..AES_GCM_NONCE_SIZE];
172        match decrypt(&yx, missing_data) {
173            Err(EncryptionError::MissingData) => (),
174            Err(e) => panic!("expected MissingData got Err({e})"),
175            Ok(_) => panic!("expected MissingData got Ok()"),
176        }
177
178        let small_data = &cipher[..AES_GCM_NONCE_SIZE + 1];
179        match decrypt(&yx, small_data) {
180            Err(EncryptionError::AesGcm(_)) => (),
181            Err(e) => panic!("expected EncryptionError(AesGcm) got Err({e:?})"),
182            Ok(_) => panic!("expected EncryptionError(AesGcm) got Ok()"),
183        }
184    }
185}