reachable_node/server/
memory.rs

1// SPDX-FileCopyrightText: 2023—2024 eaon <eaon@posteo.net>
2// SPDX-License-Identifier: EUPL-1.2
3
4use chacha20poly1305::aead::Aead;
5use rand_core::CryptoRngCore;
6
7use reach_aliases::*;
8use reach_core::{
9    ProstEncode, error,
10    memory::HintedEnvelopeId,
11    wire::{EnvelopeId, Salts, SharedPublicKeys},
12};
13use reach_encryption::{Decryptable, PublicKeyEncryptedFromParts, cipher_and_material_for};
14
15pub fn rng() -> Result<ReachRng, rand_core::Error> {
16    reach_core::memory::rng::<8192>()
17}
18
19pub trait Sealable<S> {
20    fn seal(
21        &self,
22        shared_public_keys: &SharedPublicKeys,
23        salts: &Salts,
24        csprng: &mut impl CryptoRngCore,
25    ) -> Result<S, error::CryptError>
26    where
27        S: PublicKeyEncryptedFromParts,
28        Self: ProstEncode + Decryptable<S>,
29    {
30        let (cipher, _, nonce, ec_public_key, pq_ciphertext) = cipher_and_material_for(
31            &shared_public_keys.ec_public_key,
32            &shared_public_keys.pq_public_key,
33            &salts.shared_secret,
34            None,
35            csprng,
36        );
37
38        Ok(S::from_parts(
39            ec_public_key,
40            pq_ciphertext,
41            cipher.encrypt(&nonce, self.encode_to_vec().as_ref())?,
42        ))
43    }
44}
45
46pub fn hint_envelope_id(
47    envelope_id: EnvelopeId,
48    hint_removal_token: OneSix,
49    blinded_public_key: &BlindedPublicKey,
50    salts: &Salts,
51    csprng: &mut impl CryptoRngCore,
52) -> Result<EnvelopeIdHint, error::CryptError> {
53    use ecdh_omr::Hinting;
54
55    let hinted_envelope_id = HintedEnvelopeId {
56        envelope_id,
57        hint_removal_token,
58    };
59
60    let message = hinted_envelope_id
61        .encode_to_vec()
62        .as_slice()
63        .try_into()
64        .expect("TODO");
65
66    Ok(EnvelopeIdHint::new(
67        blinded_public_key,
68        &message,
69        &salts.shared_secret,
70        csprng,
71    )?)
72}