//! Cryptographic kernels over `ring` (already linked for TLS, ADR 0038): //! SHA-256, HMAC-SHA-256 and PBKDF2-HMAC-SHA-256 — what PostgreSQL's //! SCRAM-SHA-256 authentication (RFC 5802, RFC 7677) needs — Ed25519 //! signatures (RFC 8032, ADR 0067), and ChaCha20-Poly1305 with HKDF for //! encryption at rest (RFC 8439, RFC 5869, ADR 0071). //! //! Both back ends call these, so a hash can never drift between them; the //! FIPS 180-4, RFC 2202, RFC 8032, RFC 8439 and RFC 5869 vectors below pin //! them down anyway. use ring::aead::{Aad, CHACHA20_POLY1305, LessSafeKey, Nonce, UnboundKey}; use ring::signature::{ED25519, Ed25519KeyPair, KeyPair, UnparsedPublicKey}; use ring::{digest, hkdf, hmac, pbkdf2}; use std::num::NonZeroU32; /// SHA-256 of `data`. pub fn sha256(data: &[u8]) -> [u8; 32] { let mut out = [0u8; 32]; out.copy_from_slice(digest::digest(&digest::SHA256, data).as_ref()); out } /// HMAC-SHA-256 of `message` under `key` (RFC 2104). pub fn hmac_sha256(key: &[u8], message: &[u8]) -> [u8; 32] { let mut out = [0u8; 32]; out.copy_from_slice(hmac::sign(&hmac::Key::new(hmac::HMAC_SHA256, key), message).as_ref()); out } /// PBKDF2-HMAC-SHA-256 of `password` with `salt` and `iterations` /// (saturated to at least 1), `length` output bytes. pub fn pbkdf2_hmac_sha256(password: &[u8], salt: &[u8], iterations: i64, length: usize) -> Vec { let iterations = NonZeroU32::new(iterations.clamp(1, u32::MAX as i64) as u32) .expect("clamped to at least 1"); let mut out = vec![0u8; length]; pbkdf2::derive( pbkdf2::PBKDF2_HMAC_SHA256, iterations, salt, password, &mut out, ); out } /// Whether `signature` is the Ed25519 signature of `message` under /// `public_key` (RFC 8032). A key that is not 32 bytes or a signature that /// is not 64 is no signature: `false`. pub fn ed25519_verify(public_key: &[u8], message: &[u8], signature: &[u8]) -> bool { UnparsedPublicKey::new(&ED25519, public_key) .verify(message, signature) .is_ok() } /// The Ed25519 public key of a 32-byte `seed` (RFC 8032's private key). /// A seed of another length is refused, with the message both back ends /// panic with. pub fn ed25519_public_key(seed: &[u8]) -> Result<[u8; 32], String> { let pair = key_pair(seed)?; let mut out = [0u8; 32]; out.copy_from_slice(pair.public_key().as_ref()); Ok(out) } /// The Ed25519 signature of `message` under the key pair of a 32-byte /// `seed`, refused like [`ed25519_public_key`]'s. pub fn ed25519_sign(seed: &[u8], message: &[u8]) -> Result<[u8; 64], String> { let pair = key_pair(seed)?; let mut out = [0u8; 64]; out.copy_from_slice(pair.sign(message).as_ref()); Ok(out) } fn key_pair(seed: &[u8]) -> Result { Ed25519KeyPair::from_seed_unchecked(seed) .map_err(|_| format!("crypto: an Ed25519 seed is 32 bytes, not {}", seed.len())) } /// The ChaCha20-Poly1305 sealing of `plaintext` under a 32-byte `key` and a /// 12-byte `nonce`, authenticating `aad` too (RFC 8439): the ciphertext /// followed by the 16-byte tag. A key or nonce of another length is /// refused, with the message both back ends panic with. pub fn chacha20_poly1305_seal( key: &[u8], nonce: &[u8], plaintext: &[u8], aad: &[u8], ) -> Result, String> { let (key, nonce) = (aead_key(key)?, aead_nonce(nonce)?); let mut sealed = plaintext.to_vec(); key.seal_in_place_append_tag(nonce, Aad::from(aad), &mut sealed) .map_err(|_| "crypto: a ChaCha20-Poly1305 message is at most 256 GiB".to_string())?; Ok(sealed) } /// What `open` answers when a message does not authenticate. pub const NOT_AUTHENTIC: &str = "crypto: the sealed message does not authenticate under this key, nonce and associated data"; /// The plaintext of `sealed`, if it authenticates under `key`, `nonce` and /// `aad`; `None` if it does not (a changed byte, a wrong key, nonce or /// `aad`, or fewer than 16 bytes). A key or nonce of another length is /// refused like [`chacha20_poly1305_seal`]'s. pub fn chacha20_poly1305_open( key: &[u8], nonce: &[u8], sealed: &[u8], aad: &[u8], ) -> Result>, String> { let (key, nonce) = (aead_key(key)?, aead_nonce(nonce)?); let mut buffer = sealed.to_vec(); Ok(key .open_in_place(nonce, Aad::from(aad), &mut buffer) .ok() .map(|plaintext| plaintext.to_vec())) } fn aead_key(key: &[u8]) -> Result { UnboundKey::new(&CHACHA20_POLY1305, key) .map(LessSafeKey::new) .map_err(|_| { format!( "crypto: a ChaCha20-Poly1305 key is 32 bytes, not {}", key.len() ) }) } fn aead_nonce(nonce: &[u8]) -> Result { Nonce::try_assume_unique_for_key(nonce).map_err(|_| { format!( "crypto: a ChaCha20-Poly1305 nonce is 12 bytes, not {}", nonce.len() ) }) } /// The most HKDF-SHA-256 can derive: 255 blocks of 32 bytes (RFC 5869). pub const HKDF_SHA256_MAX: usize = 255 * 32; /// HKDF-SHA-256 (RFC 5869), extract then expand: `length` bytes derived /// from `secret` with `salt` (empty means a zero salt) and `info`. A length /// outside `0..=8160` is refused, with the message both back ends panic /// with. pub fn hkdf_sha256( secret: &[u8], salt: &[u8], info: &[u8], length: i64, ) -> Result, String> { let length = usize::try_from(length) .ok() .filter(|n| *n <= HKDF_SHA256_MAX) .ok_or_else(|| format!("crypto: HKDF-SHA-256 derives 0 to 8160 bytes, not {length}"))?; let mut out = vec![0u8; length]; hkdf::Salt::new(hkdf::HKDF_SHA256, salt) .extract(secret) .expand(&[info], Length(length)) .and_then(|okm| okm.fill(&mut out)) .expect("the length is checked above"); Ok(out) } struct Length(usize); impl hkdf::KeyType for Length { fn len(&self) -> usize { self.0 } } #[cfg(test)] mod tests { use super::*; fn hex(bytes: &[u8]) -> String { bytes.iter().map(|b| format!("{b:02x}")).collect() } #[test] fn sha256_vectors() { // FIPS 180-4 examples. assert_eq!( hex(&sha256(b"abc")), "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad" ); assert_eq!( hex(&sha256(b"")), "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" ); } #[test] fn hmac_sha256_vectors() { // RFC 2202, cases 1 and 2. let key = [0x0b; 20]; assert_eq!( hex(&hmac_sha256(&key, b"Hi There")), "b0344c61d8db38535ca8afceaf0bf12b881dc200c9833da726e9376c2e32cff7" ); assert_eq!( hex(&hmac_sha256(b"Jefe", b"what do ya want for nothing?")), "5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843" ); } #[test] fn pbkdf2_vectors() { // RFC 7914-style vectors for PBKDF2-HMAC-SHA256 (from RFC 7677's // SCRAM example is covered end to end in the postgres package). assert_eq!( hex(&pbkdf2_hmac_sha256(b"password", b"salt", 1, 32)), "120fb6cffcf8b32c43e7225256c4f837a86548c92ccc35480805987cb70be17b" ); assert_eq!( hex(&pbkdf2_hmac_sha256(b"password", b"salt", 2, 32)), "ae4d0c95af6b46d32d0adff928f06dd02a303f8ef3c251dfd6e2d85a95474c43" ); // A zero iteration count is clamped to 1, not a crash. assert_eq!(pbkdf2_hmac_sha256(b"p", b"s", 0, 32).len(), 32); } fn unhex(text: &str) -> Vec { (0..text.len()) .step_by(2) .map(|i| u8::from_str_radix(&text[i..i + 2], 16).unwrap()) .collect() } #[test] fn ed25519_vectors() { // RFC 8032 §7.1, TEST 2: a one-byte message. let seed = unhex("4ccd089b28ff96da9db6c346ec114e0f5b8a319f35aba624da8cf6ed4fb8a6fb"); let public = unhex("3d4017c3e843895a92b70aa74d1b7ebc9c982ccf2ec4968cc0cd55f12af4660c"); let signature = unhex( "92a009a9f0d4cab8720e820b5f642540a2b27b5416503f8fb3762223ebdb69da\ 085ac1e43e15996e458f3613d0f11d8c387b2eaeb4302aeeb00d291612bb0c00", ); assert_eq!(ed25519_public_key(&seed).unwrap().to_vec(), public); assert_eq!(ed25519_sign(&seed, &[0x72]).unwrap().to_vec(), signature); assert!(ed25519_verify(&public, &[0x72], &signature)); assert!(!ed25519_verify(&public, &[0x73], &signature)); // Wrong lengths are no signature, and no seed. assert!(!ed25519_verify(&public[..31], &[0x72], &signature)); assert!(!ed25519_verify(&public, &[0x72], &signature[..63])); assert_eq!( ed25519_public_key(&seed[..31]), Err("crypto: an Ed25519 seed is 32 bytes, not 31".to_string()) ); assert!(ed25519_sign(&[], b"m").is_err()); } const SUNSCREEN: &[u8] = b"Ladies and Gentlemen of the class of '99: If I could offer you only one tip for the future, sunscreen would be it."; #[test] fn chacha20_poly1305_vectors() { // RFC 8439 §2.8.2. let key: Vec = (0x80..=0x9f).collect(); let nonce = unhex("070000004041424344454647"); let aad = unhex("50515253c0c1c2c3c4c5c6c7"); let sealed = chacha20_poly1305_seal(&key, &nonce, SUNSCREEN, &aad).unwrap(); assert_eq!( hex(&sealed), "d31a8d34648e60db7b86afbc53ef7ec2a4aded51296e08fea9e2b5a736ee62d6\ 3dbea45e8ca9671282fafb69da92728b1a71de0a9e060b2905d6a5b67ecd3b36\ 92ddbd7f2d778b8c9803aee328091b58fab324e4fad675945585808b4831d7bc\ 3ff4def08e4b7a9de576d26586cec64b6116\ 1ae10b594f09e26a7e902ecbd0600691" ); assert_eq!( chacha20_poly1305_open(&key, &nonce, &sealed, &aad).unwrap(), Some(SUNSCREEN.to_vec()) ); } #[test] fn chacha20_poly1305_refuses_what_does_not_authenticate() { let (key, nonce) = ([7u8; 32], [9u8; 12]); let sealed = chacha20_poly1305_seal(&key, &nonce, b"secret", b"stream-1").unwrap(); assert_eq!(sealed.len(), 6 + 16); let open = |key: &[u8], nonce: &[u8], sealed: &[u8], aad: &[u8]| { chacha20_poly1305_open(key, nonce, sealed, aad).unwrap() }; assert_eq!( open(&key, &nonce, &sealed, b"stream-1"), Some(b"secret".to_vec()) ); assert_eq!(open(&key, &nonce, &sealed, b"stream-2"), None); assert_eq!(open(&[8u8; 32], &nonce, &sealed, b"stream-1"), None); assert_eq!(open(&key, &[0u8; 12], &sealed, b"stream-1"), None); let mut flipped = sealed.clone(); flipped[0] ^= 1; assert_eq!(open(&key, &nonce, &flipped, b"stream-1"), None); assert_eq!(open(&key, &nonce, &sealed[..15], b"stream-1"), None); assert_eq!(open(&key, &nonce, &[], b""), None); let empty = chacha20_poly1305_seal(&key, &nonce, b"", b"").unwrap(); assert_eq!(open(&key, &nonce, &empty, b""), Some(Vec::new())); } #[test] fn chacha20_poly1305_refuses_wrong_lengths() { assert_eq!( chacha20_poly1305_seal(&[0u8; 31], &[0u8; 12], b"m", b""), Err("crypto: a ChaCha20-Poly1305 key is 32 bytes, not 31".to_string()) ); assert_eq!( chacha20_poly1305_open(&[0u8; 32], &[0u8; 24], b"m", b""), Err("crypto: a ChaCha20-Poly1305 nonce is 12 bytes, not 24".to_string()) ); } #[test] fn hkdf_sha256_vectors() { // RFC 5869, test cases 1 and 3 (no salt, no info). let secret = [0x0b; 22]; assert_eq!( hex(&hkdf_sha256( &secret, &unhex("000102030405060708090a0b0c"), &unhex("f0f1f2f3f4f5f6f7f8f9"), 42 ) .unwrap()), "3cb25f25faacd57a90434f64d0362f2a2d2d0a90cf1a5a4c5db02d56ecc4c5bf34007208d5b887185865" ); assert_eq!( hex(&hkdf_sha256(&secret, &[], &[], 42).unwrap()), "8da4e775a563c18f715f802a063c5a31b8a11f5c5ee1879ec3454e5f3c738d2d9d201395faa4b61a96c8" ); assert_eq!(hkdf_sha256(b"k", b"", b"", 0).unwrap(), Vec::::new()); assert_eq!(hkdf_sha256(b"k", b"", b"", 8160).unwrap().len(), 8160); assert_eq!( hkdf_sha256(b"k", b"", b"", 8161), Err("crypto: HKDF-SHA-256 derives 0 to 8160 bytes, not 8161".to_string()) ); assert!(hkdf_sha256(b"k", b"", b"", -1).is_err()); } }