kevy_crypto/lib.rs
1//! The primitives of `Noise_*_25519_ChaChaPoly_BLAKE2s`, in pure Rust with
2//! no dependencies: ChaCha20-Poly1305 (RFC 8439), X25519 (RFC 7748),
3//! BLAKE2s (RFC 7693), and HMAC/HKDF over BLAKE2s as the Noise Protocol
4//! Framework defines them.
5//!
6//! No branch and no memory index depends on a key, a scalar or a tag. That
7//! is how the code is written, and statistical timing checks on x86_64 and
8//! aarch64 found no dependence; a compiler does not promise it, and the
9//! crate has not been audited by a third party.
10//!
11//! ```
12//! use kevy_crypto::{aead, blake2s, x25519};
13//!
14//! // two parties agree on a key...
15//! let (a, b) = ([3u8; 32], [5u8; 32]);
16//! let shared = x25519::x25519(&a, &x25519::x25519(&b, &x25519::BASEPOINT));
17//! let key = blake2s::hash(&shared);
18//!
19//! // ...and use it to seal a message
20//! let mut msg = *b"attack at dawn";
21//! let tag = aead::seal(&key, &[0; 12], b"", &mut msg);
22//! aead::open(&key, &[0; 12], b"", &mut msg, &tag).unwrap();
23//! assert_eq!(&msg, b"attack at dawn");
24//! ```
25
26#![cfg_attr(not(test), no_std)]
27#![forbid(unsafe_code)]
28#![warn(missing_docs)]
29
30pub mod aead;
31pub mod blake2s;
32mod chacha20;
33mod fe25519;
34pub mod hkdf;
35mod poly1305;
36pub mod x25519;
37
38// Send and Sync are part of the public contract: a change that loses
39// either fails to compile here rather than in a caller.
40const _: () = {
41 const fn send_sync<T: Send + Sync>() {}
42 send_sync::<aead::AuthError>();
43 send_sync::<blake2s::Blake2s>();
44};
45
46#[cfg(test)]
47mod tests;
48
49/// Equality of two byte strings in time that depends only on their
50/// lengths, never on where they first differ.
51///
52/// ```
53/// assert!(kevy_crypto::ct_eq(b"tag", b"tag"));
54/// assert!(!kevy_crypto::ct_eq(b"tag", b"taG"));
55/// ```
56pub fn ct_eq(a: &[u8], b: &[u8]) -> bool {
57 if a.len() != b.len() {
58 return false;
59 }
60 let mut diff = 0u8;
61 for (x, y) in a.iter().zip(b) {
62 diff |= x ^ y;
63 }
64 core::hint::black_box(diff) == 0
65}