mailcycle 0.8.0

Rust email API client: create addresses that receive email, read and decrypt messages on your machine, send email, verify webhooks and stream events.
Documentation
//! The primitives, borrowed rather than written again.
//!
//! The app implements SHA-256, HMAC, PBKDF2, ChaCha20 and X25519 in its own
//! JavaScript because React Native has no WebCrypto. Rust does not have that
//! problem: the RustCrypto crates are the same primitives, better tested and
//! faster. What is written here is only what is specific to Mailcycle.
//!
//! The one thing worth spelling out is ChaCha20. Mailcycle's counter starts at
//! zero, as RFC 8439 and `src/crypto/chacha20.ts` do, which is what the
//! `chacha20` crate's `ChaCha20` with a 12-byte nonce gives.

use chacha20::cipher::{KeyIvInit, StreamCipher};
use chacha20::ChaCha20;
use hmac::{Hmac, Mac};
use sha2::{Digest, Sha256};
use subtle::ConstantTimeEq;
use x25519_dalek::{PublicKey, StaticSecret};

pub const NONCE_BYTES: usize = 12;
pub const KEY_BYTES: usize = 32;

type HmacSha256 = Hmac<Sha256>;

pub fn sha256(data: &[u8]) -> [u8; 32] {
    Sha256::digest(data).into()
}

pub fn hmac_sha256(key: &[u8], message: &[u8]) -> [u8; 32] {
    let mut mac = <HmacSha256 as Mac>::new_from_slice(key).expect("HMAC takes a key of any length");
    mac.update(message);
    mac.finalize().into_bytes().into()
}

pub fn pbkdf2_sha256(password: &[u8], salt: &[u8], iterations: u32, length: usize) -> Vec<u8> {
    let mut out = vec![0u8; length];
    pbkdf2::pbkdf2_hmac::<Sha256>(password, salt, iterations, &mut out);
    out
}

pub fn constant_time_equal(a: &[u8], b: &[u8]) -> bool {
    a.ct_eq(b).into()
}

/// RFC 8439 ChaCha20, counter from zero. The same call decrypts.
pub fn chacha20(key: &[u8], nonce: &[u8], data: &[u8]) -> Vec<u8> {
    assert_eq!(key.len(), KEY_BYTES, "ChaCha20 key must be 32 bytes");
    assert_eq!(nonce.len(), NONCE_BYTES, "ChaCha20 nonce must be 12 bytes");
    let mut cipher = ChaCha20::new(key.into(), nonce.into());
    let mut out = data.to_vec();
    cipher.apply_keystream(&mut out);
    out
}

/// The X25519 public half. The scalar is clamped, so any 32 bytes work.
pub fn public_key_from(private_key: &[u8]) -> [u8; 32] {
    let mut scalar = [0u8; 32];
    scalar.copy_from_slice(private_key);
    PublicKey::from(&StaticSecret::from(scalar)).to_bytes()
}

/// X25519.
///
/// Returns all zeroes where the public key had small order and contributed
/// nothing. Every caller here checks the result before using it, because
/// encrypting under a shared secret the other side already knows is the
/// difference between encrypting and appearing to.
pub fn shared_secret(private_key: &[u8], public_key: &[u8]) -> [u8; 32] {
    let mut scalar = [0u8; 32];
    scalar.copy_from_slice(private_key);
    let mut peer = [0u8; 32];
    peer.copy_from_slice(public_key);
    StaticSecret::from(scalar).diffie_hellman(&PublicKey::from(peer)).to_bytes()
}

pub fn is_all_zero(data: &[u8]) -> bool {
    data.iter().all(|byte| *byte == 0)
}

/// Bytes from the operating system's CSPRNG.
///
/// A failure here is not recoverable and must never be papered over with a
/// weaker source: a predictable nonce or ephemeral key would break the
/// encryption while leaving it looking like it worked.
pub fn random_bytes(length: usize) -> Vec<u8> {
    let mut out = vec![0u8; length];
    getrandom::getrandom(&mut out).expect("the operating system has no random source");
    out
}