Skip to main content

simploxide_client/crypto/
mod.rs

1//! Crypto primitives and traits to implement SimpleX-Chat cryptography in a way compatible with
2//! simploxide.
3
4pub mod fs;
5
6#[cfg(feature = "native_crypto")]
7pub mod native;
8
9pub type XSalsa20Key = [u8; 32];
10pub type XSalsa20Nonce = [u8; 24];
11pub type Poly1305Tag = [u8; 16];
12
13pub trait SimplexSecretBox {
14    /// Return a properly initialized SimpleX `secretbox`.
15    ///
16    /// Beware that SimpleX uses a non-standard initialization like this:
17    ///
18    /// intermediate = hsalsa20(xsalsa20_key, [0u8; 16]);
19    /// xsalsa20 = xsalsa20_init(intermediate, xsalsa20_nonce);
20    /// poly1305_key = (first 32 bytes of xsalsa20 cipherstream);
21    fn init(key: &XSalsa20Key, nonce: &XSalsa20Nonce) -> Self;
22
23    /// Write a ciphertext into a `buf`. Update poly1305 but do not authenticate the chunk, the
24    /// auth tag must be put only at the end of the whole message.
25    fn encrypt_chunk(&mut self, chunk: impl AsRef<[u8]>, buf: impl AsMut<[u8]>);
26
27    /// Write a plaintext into a `buf`. `chunk` is always pure ciphertext, `simploxide` utilities
28    /// guarantee that `auth_tag` won't appear in the input chunk.
29    fn decrypt_chunk(&mut self, chunk: impl AsRef<[u8]>, buf: impl AsMut<[u8]>);
30
31    fn auth_tag(&mut self) -> Poly1305Tag;
32
33    fn verify_tag(&mut self, tag_to_verify: &Poly1305Tag) -> bool;
34}
35
36#[derive(Debug, Clone, Copy)]
37pub struct InvalidAuthTag;
38
39impl InvalidAuthTag {
40    pub fn io_error() -> std::io::Error {
41        std::io::Error::new(std::io::ErrorKind::InvalidData, InvalidAuthTag)
42    }
43}
44
45impl From<InvalidAuthTag> for ::std::io::Error {
46    fn from(_: InvalidAuthTag) -> Self {
47        InvalidAuthTag::io_error()
48    }
49}
50
51impl std::fmt::Display for InvalidAuthTag {
52    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
53        write!(f, "Invalid poly1305 auth tag")
54    }
55}
56
57impl std::error::Error for InvalidAuthTag {}
58
59#[derive(Debug, Clone, Copy)]
60pub struct InvalidCryptoArgs;
61
62impl InvalidCryptoArgs {
63    pub fn io_error() -> std::io::Error {
64        std::io::Error::new(std::io::ErrorKind::InvalidData, InvalidCryptoArgs)
65    }
66}
67
68impl From<InvalidCryptoArgs> for ::std::io::Error {
69    fn from(_: InvalidCryptoArgs) -> Self {
70        InvalidCryptoArgs::io_error()
71    }
72}
73
74impl std::fmt::Display for InvalidCryptoArgs {
75    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
76        write!(f, "Invalid file crypto args")
77    }
78}
79
80impl std::error::Error for InvalidCryptoArgs {}