sos_core/crypto/
mod.rs

1//! Cryptographic routines and types.
2use crate::csprng;
3use rand::Rng;
4use serde::{Deserialize, Serialize};
5use serde_with::{base64::Base64, serde_as};
6
7#[doc(hidden)]
8pub mod cipher;
9mod key_derivation;
10mod private_key;
11
12pub use cipher::Cipher;
13pub(crate) use cipher::{AES_GCM_256, X25519, X_CHACHA20_POLY1305};
14
15#[doc(hidden)]
16pub use key_derivation::Deriver;
17pub(crate) use key_derivation::{ARGON_2_ID, BALLOON_HASH};
18
19pub use key_derivation::{KeyDerivation, Seed};
20pub use private_key::{AccessKey, DerivedPrivateKey, PrivateKey};
21
22/// Enumeration of the sizes for nonces.
23#[serde_as]
24#[derive(Serialize, Deserialize, Debug, Eq, PartialEq, Clone)]
25#[serde(rename_all = "lowercase")]
26pub enum Nonce {
27    /// Standard 12 byte nonce used by AES-GCM.
28    Nonce12(#[serde_as(as = "Base64")] [u8; 12]),
29    /// Extended 24 byte nonce used by XChaCha20Poly1305.
30    Nonce24(#[serde_as(as = "Base64")] [u8; 24]),
31}
32
33impl Nonce {
34    /// Generate a new random 12 byte nonce.
35    pub fn new_random_12() -> Nonce {
36        let val: [u8; 12] = csprng().gen();
37        Nonce::Nonce12(val)
38    }
39
40    /// Generate a new random 24 byte nonce.
41    pub fn new_random_24() -> Nonce {
42        let val: [u8; 24] = csprng().gen();
43        Nonce::Nonce24(val)
44    }
45}
46
47impl Default for Nonce {
48    fn default() -> Self {
49        Nonce::Nonce24([0; 24])
50    }
51}
52
53impl AsRef<[u8]> for Nonce {
54    fn as_ref(&self) -> &[u8] {
55        match self {
56            Nonce::Nonce12(ref val) => val,
57            Nonce::Nonce24(ref val) => val,
58        }
59    }
60}
61
62/// Encrypted data with the nonce.
63#[serde_as]
64#[derive(Serialize, Deserialize, Default, Debug, Eq, PartialEq, Clone)]
65pub struct AeadPack {
66    /// Number once value.
67    pub nonce: Nonce,
68    /// Encrypted cipher text.
69    #[serde_as(as = "Base64")]
70    pub ciphertext: Vec<u8>,
71}