diff --git a/Cargo.toml b/Cargo.toml index b31813db..607f9762 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -28,10 +28,12 @@ bouncycastle-core-test-framework = { path = "./crypto/core-test-framework" } bouncycastle-ec = { path = "./crypto/ec" } bouncycastle-eccdh = { path = "./crypto/eccdh" } bouncycastle-ecdsa = { path = "./crypto/ecdsa" } +bouncycastle-ed = { path = "crypto/ed" } bouncycastle-factory = { path = "./crypto/factory" } bouncycastle-hex = { path = "./crypto/hex" } bouncycastle-hkdf = { path = "./crypto/hkdf" } bouncycastle-hmac = { path = "./crypto/hmac" } +bouncycastle-hpke = { path = "./crypto/hpke" } bouncycastle-mlkem = { path = "./crypto/mlkem" } bouncycastle-mlkem-common = { path = "./crypto/mlkem-common" } bouncycastle-mlkem-lowmemory = { path = "./crypto/mlkem-lowmemory" } @@ -89,10 +91,12 @@ bouncycastle-core.workspace = true bouncycastle-ec.workspace = true bouncycastle-eccdh.workspace = true bouncycastle-ecdsa.workspace = true +bouncycastle-ed.workspace = true bouncycastle-factory.workspace = true bouncycastle-hex.workspace = true bouncycastle-hkdf.workspace = true bouncycastle-hmac.workspace = true +bouncycastle-hpke.workspace = true bouncycastle-mldsa.workspace = true bouncycastle-mldsa-lowmemory.workspace = true bouncycastle-mlkem.workspace = true diff --git a/QUALITY_AND_STYLE.md b/QUALITY_AND_STYLE.md index ccc5c084..db8b5402 100644 --- a/QUALITY_AND_STYLE.md +++ b/QUALITY_AND_STYLE.md @@ -40,7 +40,7 @@ meant to be held as `dyn` -- the hash, XOF, cipher, MAC, KEM and signature worke ## Tests -All crates must have tests in `src/tests`. Part of writing code that treats future maintainers as malicious is that all +All crates must have tests in `tests/`. Part of writing code that treats future maintainers as malicious is that all functions that form part of the public interface should have their expected behaviour fully constrained with tests. In other words, any behaviour change of the library that could cause a change in a calling application should also cause a test in bc-rust to fail. An excellent tool for achieving this is `cargo mutants` which must be run on every crate and @@ -125,7 +125,8 @@ subsequent calls can be made to this object (as opposed to the usual pattern of `do_update(&self, ...)`). These tricks go a long way to reducing fallibility since now in general there is no (or very very little) object state to track and return errors about. -Any struct that holds sensitive data must impl the `core::Secret` trait and all associated super-traits. +Any struct that holds sensitive data must keep it in a `bouncycastle_utils::secret::Secret` field (or in a +`KeyMaterial`, which is built on it), so that it is zeroized on drop and redacted from `Debug` and `Display`. A primitive whose safe use depends on the caller composing it correctly -- a raw block permutation, a raw keystream -- lives under a `hazmat` module in its crate or sub-module, never at the crate root or next to the safe API; diff --git a/alpha_0.1.4_release_notes.md b/alpha_0.1.4_release_notes.md index c1ef81d4..e8e16cab 100644 --- a/alpha_0.1.4_release_notes.md +++ b/alpha_0.1.4_release_notes.md @@ -31,6 +31,14 @@ * `bouncycastle-ec` -- the constant-time, fixed-width curve arithmetic under both: per-curve field, scalar and Jacobian-point arithmetic, SEC 1 codec and comb, wNAF and variable-base multipliers, all under `hazmat`, with the generic limb arithmetic (`nat`, `montgomery`, `barrett`, `inverse_vartime`) at the crate root. +* X25519 -- `bouncycastle-ed`, the Diffie-Hellman function of RFC 7748 over Curve25519, on the key agreement + roles: `X25519PrivateKey` implements `AgreementKey` over `()` for the raw shared secret and over + `KdfParams, LEN>` for a derived key (`X25519_HKDF_SHA256`), and with `X25519PublicKey` the KEM roles + as DHKEM(X25519, HKDF-SHA256) of RFC 9180 Section 4.1 (`DHKEM_X25519_HKDF_SHA256`), through the new + `bouncycastle-hpke` crate's generic DHKEM; + `keygen` draws the key from the caller's RNG; checked against RFC 7748's vectors, RFC 9180 Appendix A.1.1, A.1.2, A.2.1, A.2.2, A.7.1 and A.7.2, and + Wycheproof's X25519 set; the `x25519` CLI subcommand covers keygen, pk-from-sk, check-consistency, agree, encaps + and decaps. ## Minor features / bug fixes @@ -173,7 +181,7 @@ * `bouncycastle-eccdh`: ECC CDH (SP 800-56A Rev. 3 Section 5.7.1.2) over P-256, P-384, P-521, secp256k1, brainpoolP256r1, brainpoolP384r1 and brainpoolP512r1, with its own key types per curve (full public-key validation at decode, key generation by extra random bits), the markers `ECCDHP256` and friends on the - `AgreementKey` role over `()`, and `ECCDHP256_HKDF_SHA256` over `KdfParams` on the P-256 keys; + `AgreementKey` role over `()`, and `ECCDHP256_HKDF_SHA256` over `KdfParams, LEN>` on the P-256 keys; tested against the CAVP ECC CDH primitive vectors, RFC 7027 Appendix A and the Wycheproof ECDH sets. * `bouncycastle-x963kdf`: the ANSI X9.63 KDF of SEC 1 v2 Section 3.6.1 over SHA-224, SHA-256, SHA-384 and SHA-512, on the `KDF` trait and in `KDFFactory` (`X963KDF-SHA256` and so on) and as the `x963kdf-sha*` CLI diff --git a/cli/src/helpers/mod.rs b/cli/src/helpers/mod.rs index 409727d9..05b16bb0 100644 --- a/cli/src/helpers/mod.rs +++ b/cli/src/helpers/mod.rs @@ -22,6 +22,7 @@ use bouncycastle::core::key_material::{KeyMaterial, KeyMaterialTrait, KeyType}; use bouncycastle::core::security_strength::SecurityStrength; use bouncycastle::core::traits::{Hash, XOF, XOFSqueezer}; use bouncycastle::hex; +use bouncycastle_utils::secret::Secret; use std::fs::File; use std::io; use std::io::{Read, Write}; @@ -368,6 +369,30 @@ pub(crate) fn write_bytes_or_hex(bytes: &[u8], output_hex: bool) { } } +/// [`write_bytes_or_hex`] for a secret (a private key, a shared secret): the hex form is built +/// in a stack buffer that is wiped, 32 bytes at a time, rather than in a heap `String` that is +/// freed as it stands, and each digit is computed, not looked up by the secret nibble. +pub(crate) fn write_secret_bytes_or_hex(bytes: &[u8], output_hex: bool) { + if !output_hex { + write_stdout(bytes); + return; + } + let mut hex = Secret::<[u8; 64]>::new(); + for chunk in bytes.chunks(32) { + for (i, b) in chunk.iter().enumerate() { + hex[2 * i] = hex_digit(b >> 4); + hex[2 * i + 1] = hex_digit(b & 0x0f); + } + write_stdout(&hex[..2 * chunk.len()]); + } +} + +/// The lower-case hex digit of the nibble `n`, with no branch or table on its value: '0'..'9' +/// is `48 + n` and 'a'..'f' is `48 + n + 39`, and the mask is all ones exactly when `n > 9`. +fn hex_digit(n: u8) -> u8 { + b'0' + n + ((((9i16 - n as i16) >> 8) as u8) & 39) +} + /// Writes `bytes`, raw or as hex, to a new file `filename`; a failure names the path. pub(crate) fn write_bytes_or_hex_to_file(bytes: &[u8], filename: &str, output_hex: bool) { let result = File::create(filename).and_then(|mut file| { @@ -472,3 +497,15 @@ pub(crate) fn squeeze_to_stdout( } write_stdout(b"\n"); } + +#[cfg(test)] +mod tests { + use super::hex_digit; + + #[test] + fn hex_digit_is_the_lower_case_digit_of_every_nibble() { + for (n, expected) in b"0123456789abcdef".iter().enumerate() { + assert_eq!(hex_digit(n as u8), *expected, "nibble {n}"); + } + } +} diff --git a/cli/src/main.rs b/cli/src/main.rs index 8dd99419..2194bf69 100644 --- a/cli/src/main.rs +++ b/cli/src/main.rs @@ -41,6 +41,7 @@ mod tdes_ctr_cmd; mod tdes_ecb_cmd; mod tdes_ofb_cmd; mod tdes_tkw_cmd; +mod x25519_cmd; use crate::blake2_cmd::BLAKE2Variant; use crate::eccdh_cmd::ECCDHAction; @@ -6644,6 +6645,28 @@ enum Subcommands { /// Output in hex format. x: bool, }, + + /// The X25519 key agreement algorithm (RFC 7748), and the DHKEM(X25519, HKDF-SHA256) key + /// encapsulation built on it (RFC 9180). + X25519 { + action: x25519_cmd::X25519Action, + + #[arg(long)] + /// The private key file (binary, or hex under --hex-input) for pk-from-sk, check-consistency, agree and decaps; stdin if absent where allowed + skfile: Option, + + #[arg(long)] + /// The public key file (binary, or hex under --hex-input) for check-consistency, agree and encaps + pkfile: Option, + + #[arg(long)] + /// The ciphertext file (binary, or hex under --hex-input): written by encaps, read by decaps. + ctfile: Option, + + #[arg(short)] + /// Output in hex format. + x: bool, + }, } fn main() { @@ -8114,6 +8137,9 @@ fn run() { Some(Subcommands::HMAC_SHA3_512 { key, key_file, verify, x }) => { mac_cmd::mac_cmd(HMACVariant::SHA3_512, key, key_file, verify, *x) } + Some(Subcommands::X25519 { action, skfile, pkfile, ctfile, x }) => { + x25519_cmd::x25519_cmd(action, skfile, pkfile, ctfile, *x); + } None => { eprintln!("No command provided. See -h") } diff --git a/cli/src/x25519_cmd.rs b/cli/src/x25519_cmd.rs new file mode 100644 index 00000000..e286f73e --- /dev/null +++ b/cli/src/x25519_cmd.rs @@ -0,0 +1,158 @@ +//! The `x25519` subcommand: X25519 key agreement (RFC 7748) through the agreement role, and +//! DHKEM(X25519, HKDF-SHA256) (RFC 9180) through the KEM roles, on one key pair. `agree` writes +//! the raw shared secret for a KDF (`hkdf-* --ikm-file` and the others), as `eccdh-*` does. + +use crate::helpers::{ + SecretBytes, println_stdout, read_input_file, read_input_file_or_stdin, read_secret_file, + read_secret_file_or_stdin, write_bytes_or_hex, write_bytes_or_hex_to_file, + write_secret_bytes_or_hex, write_stdout, +}; +use bouncycastle::core::agreement_key::AgreementKey; +use bouncycastle::core::kem_key::{DecapsulatingKey, EncapsulatingKey}; +use bouncycastle::core::key_material::KeyMaterialTrait; +use bouncycastle::core::traits::{KeyAgreementPrivateKey, KeyAgreementPublicKey}; +use bouncycastle::ed::x25519::{ + POINT_LEN, SCALAR_LEN, X25519PrivateKey, X25519PublicKey, keygen_out, +}; +use bouncycastle::rng::HashDRBG_SHA512; +use bouncycastle_utils::secret::Secret; +use clap::ValueEnum; +use std::process::exit; + +#[derive(ValueEnum, Clone, Debug)] +pub(crate) enum X25519Action { + /// Generate a private key (32 bytes) to stdout. + Keygen, + /// Derive the public key from the private key. + PkFromSk, + /// Check that a public key matches a private key. + CheckConsistency, + /// The raw X25519 shared secret from the private key and the peer's public key, for a KDF. + Agree, + /// DHKEM encapsulation against the public key: the shared secret, and the ciphertext. + Encaps, + /// DHKEM decapsulation of the ciphertext with the private key. + Decaps, +} + +pub(crate) fn x25519_cmd( + action: &X25519Action, + skfile: &Option, + pkfile: &Option, + ctfile: &Option, + output_hex: bool, +) { + match action { + X25519Action::Keygen => { + // The scalar is drawn straight into this key, never moved. + let mut sk = X25519PrivateKey::zeroized(); + keygen_out(&mut HashDRBG_SHA512::new_from_os(), &mut sk).unwrap_or_else(|e| { + eprintln!("Error: key generation failed: {e:?}"); + exit(-1); + }); + let mut sk_bytes = Secret::<[u8; SCALAR_LEN]>::new(); + sk.encode_out(&mut sk_bytes); + write_secret_bytes_or_hex(&*sk_bytes, output_hex); + } + X25519Action::PkFromSk => { + let pk = load_sk(skfile).pk(); + write_bytes_or_hex(&pk.encode(), output_hex); + } + X25519Action::CheckConsistency => { + let pk = parse_pk(&read_pkfile(pkfile)); + // The private key is dropped, and so wiped, before either branch exits. + let matches = load_sk(skfile).pk() == pk; + if matches { + println_stdout("SUCCESS: pk and sk match."); + } else { + eprintln!("FAILURE: pk and sk do not match."); + exit(-1); + } + } + X25519Action::Agree => { + let pk = parse_pk(&read_pkfile(pkfile)); + // `exit` runs no destructors, so the key is dropped before the result is looked at. + let z = { + let sk = load_sk(skfile); + sk.agree(&pk, ()) + }; + let z = z.unwrap_or_else(|e| { + eprintln!("Error: key agreement failed: {e:?}"); + exit(-1); + }); + write_secret_bytes_or_hex(z.ref_to_bytes(), output_hex); + } + X25519Action::Encaps => { + let pk = parse_pk(&read_input_file_or_stdin(pkfile)); + let (ss, ct) = pk.encaps(&mut HashDRBG_SHA512::new_from_os(), ()).unwrap_or_else(|e| { + eprintln!("Error: encapsulation failed: {e:?}"); + exit(-1); + }); + if let Some(ctfile) = ctfile { + write_bytes_or_hex_to_file(&ct, ctfile, output_hex); + write_secret_bytes_or_hex(ss.ref_to_bytes(), output_hex); + } else { + write_bytes_or_hex(&ct, true); + write_stdout(b"\n"); + write_secret_bytes_or_hex(ss.ref_to_bytes(), true); + } + } + X25519Action::Decaps => { + let Some(skfile) = skfile else { + eprintln!("Error: no skfile provided."); + exit(-1); + }; + // The ciphertext is checked before the private key is read. + let ct = read_input_file_or_stdin(ctfile); + let Ok(ct) = <[u8; POINT_LEN]>::try_from(ct.as_slice()) else { + eprintln!("Error: ciphertext is not the correct length."); + exit(-1); + }; + // `exit` runs no destructors, so the key is dropped before the result is looked at. + let ss = { + let sk = parse_sk(|| read_secret_file(skfile)); + sk.decaps(&ct, ()) + }; + let ss = ss.unwrap_or_else(|e| { + eprintln!("Error: decapsulation failed: {e:?}"); + exit(-1); + }); + write_secret_bytes_or_hex(ss.ref_to_bytes(), output_hex); + } + } +} + +fn read_pkfile(pkfile: &Option) -> Vec { + match pkfile { + Some(f) => read_input_file(f), + None => { + eprintln!("Error: no pkfile provided."); + exit(-1); + } + } +} + +/// The private key in `--skfile`, or on stdin. +fn load_sk(skfile: &Option) -> X25519PrivateKey { + parse_sk(|| read_secret_file_or_stdin(skfile)) +} + +/// The private key that the bytes `read` returns encode. The bytes go out of scope, and so are +/// wiped, before a failure exits. +fn parse_sk(read: impl FnOnce() -> SecretBytes) -> X25519PrivateKey { + let parsed = { + let bytes = read(); + X25519PrivateKey::from_bytes(bytes.ref_to_bytes()) + }; + parsed.unwrap_or_else(|_| { + eprintln!("Error: couldn't parse the input as a 32-byte X25519 private key."); + exit(-1); + }) +} + +fn parse_pk(bytes: &[u8]) -> X25519PublicKey { + X25519PublicKey::from_bytes(bytes).unwrap_or_else(|_| { + eprintln!("Error: couldn't parse the input as a 32-byte X25519 public key."); + exit(-1); + }) +} diff --git a/cli/tests/test_x25519.sh b/cli/tests/test_x25519.sh new file mode 100755 index 00000000..6560d1c2 --- /dev/null +++ b/cli/tests/test_x25519.sh @@ -0,0 +1,185 @@ +#!/usr/bin/env bash +# The x25519 subcommand, end to end through the binary: X25519 key agreement (RFC 7748) and +# DHKEM(X25519, HKDF-SHA256) encapsulation (RFC 9180). +# +# The known answers: the key agreement is RFC 7748 Section 6.1; the decapsulation is RFC 9180 +# Appendix A.1.1. Hex keys and ciphertexts are read under --hex-input; without it they are raw bytes. + +source "$(dirname "${BASH_SOURCE[0]}")/lib.sh" + +# RFC 7748 Section 6.1. +ALICE_SK=77076d0a7318a57d3c16c17251b26645df4c2f87ebc0992ab177fba51db92c2a +ALICE_PK=8520f0098930a754748b7ddcb43ef75a0dbf3a0d26381af4eba4a98eaa9b4e6a +BOB_SK=5dab087e624a8a4b79e17f8b83800ee66f3bb1292618b6fd1c2f8b27ff88e0eb +BOB_PK=de9edb7d7b7dc1b4d35b61c2ece435373f8343c85b78674dadfc7e146f882b4f +SHARED_K=4a5d9d5ba4ce2de1728e3bf480350f25e07e21c947d19e3376f09b3c1e161742 + +# RFC 9180 Appendix A.1.1. +SK_RM=4612c550263fc8ad58375df3f557aac531d26850903e55a9f23f21d8534e8ac8 +PK_RM=3948cfe0ad1ddb695d780e59077195da6c56506b027329794ab02bca80815c4d +ENC=37fda3567bdbd628e88668c3c8d7e97d1d1253b6d4ea6d44c150f741f1bf4431 +SHARED_SECRET=fe0e18c9f024ce43799ae393c7e8fe8fce9d218875e8227b0187c04e7d2ea1fc + +# ---- known answers ------------------------------------------------------------------------ + +test_pk_from_sk_matches_rfc7748() { + local got + got=$(hex_out "$BC_RUST" --hex-input x25519 pk-from-sk -x < <(printf '%s' "$ALICE_SK")) + assert_eq "$got" "$ALICE_PK" "RFC 7748 6.1 Alice's public key" + printf '%s' "$BOB_SK" >"$TMP/bob.sk" + got=$(hex_out "$BC_RUST" --hex-input x25519 pk-from-sk --skfile "$TMP/bob.sk" -x) + assert_eq "$got" "$BOB_PK" "RFC 7748 6.1 Bob's public key" +} + +test_agree_matches_rfc7748() { + local got + printf '%s' "$ALICE_SK" >"$TMP/alice.sk" + printf '%s' "$ALICE_PK" >"$TMP/alice.pk" + printf '%s' "$BOB_SK" >"$TMP/bob.sk" + printf '%s' "$BOB_PK" >"$TMP/bob.pk" + got=$(hex_out "$BC_RUST" --hex-input x25519 agree --skfile "$TMP/alice.sk" --pkfile "$TMP/bob.pk" -x) + assert_eq "$got" "$SHARED_K" "RFC 7748 6.1 K, computed by Alice" + got=$(hex_out "$BC_RUST" --hex-input x25519 agree --pkfile "$TMP/alice.pk" -x <"$TMP/bob.sk") + assert_eq "$got" "$SHARED_K" "RFC 7748 6.1 K, computed by Bob with the sk on stdin" +} + +test_decaps_matches_rfc9180_a1_1() { + local got + printf '%s' "$SK_RM" >"$TMP/sk" + got=$(hex_out "$BC_RUST" --hex-input x25519 pk-from-sk --skfile "$TMP/sk" -x) + assert_eq "$got" "$PK_RM" "RFC 9180 A.1.1 pkRm" + got=$(hex_out "$BC_RUST" --hex-input x25519 decaps --skfile "$TMP/sk" -x < <(printf '%s' "$ENC")) + assert_eq "$got" "$SHARED_SECRET" "RFC 9180 A.1.1 shared_secret, enc on stdin" + printf '%s' "$ENC" >"$TMP/ct" + got=$(hex_out "$BC_RUST" --hex-input x25519 decaps --skfile "$TMP/sk" --ctfile "$TMP/ct" -x) + assert_eq "$got" "$SHARED_SECRET" "RFC 9180 A.1.1 shared_secret, enc from --ctfile" +} + +# ---- binary and hex ----------------------------------------------------------------------- + +test_binary_keys_match_hex_keys() { + local from_hex from_bin + unhex "$ALICE_SK" >"$TMP/alice.sk" + unhex "$BOB_PK" >"$TMP/bob.pk" + from_bin=$(hex_out "$BC_RUST" x25519 agree --skfile "$TMP/alice.sk" --pkfile "$TMP/bob.pk" -x) + assert_eq "$from_bin" "$SHARED_K" "agree with binary key files" + "$BC_RUST" x25519 agree --skfile "$TMP/alice.sk" --pkfile "$TMP/bob.pk" >"$TMP/k" + assert_eq "$(hex "$TMP/k")" "$SHARED_K" "agree with binary output" + from_hex=$(hex_out "$BC_RUST" x25519 pk-from-sk -x <"$TMP/alice.sk") + assert_eq "$from_hex" "$ALICE_PK" "pk-from-sk with a binary sk on stdin" +} + +# ---- fresh keys --------------------------------------------------------------------------- + +test_keygen_outputs_fresh_keys() { + "$BC_RUST" x25519 keygen >"$TMP/sk1" + "$BC_RUST" x25519 keygen >"$TMP/sk2" + assert_size "$TMP/sk1" 32 "keygen binary private key" + assert_differs "$TMP/sk1" "$TMP/sk2" "two keygens must give different keys" + assert_eq "$(hex_out "$BC_RUST" x25519 keygen -x | wc -c | tr -d ' ')" 64 "keygen -x length" +} + +test_agree_with_fresh_keys() { + "$BC_RUST" x25519 keygen >"$TMP/a.sk" + "$BC_RUST" x25519 keygen >"$TMP/b.sk" + "$BC_RUST" x25519 pk-from-sk --skfile "$TMP/a.sk" >"$TMP/a.pk" + "$BC_RUST" x25519 pk-from-sk --skfile "$TMP/b.sk" >"$TMP/b.pk" + "$BC_RUST" x25519 agree --skfile "$TMP/a.sk" --pkfile "$TMP/b.pk" >"$TMP/k_a" + "$BC_RUST" x25519 agree --skfile "$TMP/b.sk" --pkfile "$TMP/a.pk" >"$TMP/k_b" + assert_size "$TMP/k_a" 32 "shared secret" + assert_same "$TMP/k_a" "$TMP/k_b" "both sides must agree" +} + +test_check_consistency() { + "$BC_RUST" x25519 keygen >"$TMP/sk" + "$BC_RUST" x25519 pk-from-sk --skfile "$TMP/sk" >"$TMP/pk" + expect_ok "matching pair" \ + "$BC_RUST" x25519 check-consistency --skfile "$TMP/sk" --pkfile "$TMP/pk" >/dev/null + "$BC_RUST" x25519 keygen >"$TMP/other.sk" + expect_fail "mismatched pair" \ + "$BC_RUST" x25519 check-consistency --skfile "$TMP/other.sk" --pkfile "$TMP/pk" + assert_stderr_has "FAILURE" +} + +# ---- encaps / decaps ---------------------------------------------------------------------- + +test_encaps_decaps_round_trip_with_ctfile() { + "$BC_RUST" x25519 keygen >"$TMP/sk" + "$BC_RUST" x25519 pk-from-sk --skfile "$TMP/sk" >"$TMP/pk" + "$BC_RUST" x25519 encaps --pkfile "$TMP/pk" --ctfile "$TMP/ct" >"$TMP/ss1" + "$BC_RUST" x25519 decaps --skfile "$TMP/sk" --ctfile "$TMP/ct" >"$TMP/ss2" + assert_size "$TMP/ct" 32 "ciphertext" + assert_size "$TMP/ss1" 32 "shared secret" + assert_same "$TMP/ss1" "$TMP/ss2" "decaps must recover the encapsulated secret" +} + +# Without --ctfile, encaps prints the ciphertext and then the shared secret, in hex, one per line. +test_encaps_to_stdout_round_trip() { + local ct ss got + "$BC_RUST" x25519 keygen >"$TMP/sk" + "$BC_RUST" x25519 pk-from-sk --skfile "$TMP/sk" | "$BC_RUST" x25519 encaps >"$TMP/out" + ct=$(sed -n 1p "$TMP/out") + ss=$(sed -n 2p "$TMP/out") + assert_eq "${#ct}" 64 "hex ciphertext length" + assert_eq "${#ss}" 64 "hex shared secret length" + got=$(hex_out "$BC_RUST" x25519 decaps --skfile "$TMP/sk" -x < <(unhex "$ct")) + assert_eq "$got" "$ss" "decaps must recover the encapsulated secret" +} + +test_encaps_is_randomized() { + printf '%s' "$PK_RM" >"$TMP/pk" + "$BC_RUST" --hex-input x25519 encaps --pkfile "$TMP/pk" --ctfile "$TMP/ct1" >"$TMP/ss1" + "$BC_RUST" --hex-input x25519 encaps --pkfile "$TMP/pk" --ctfile "$TMP/ct2" >"$TMP/ss2" + assert_differs "$TMP/ct1" "$TMP/ct2" "two encapsulations must give different ciphertexts" + assert_differs "$TMP/ss1" "$TMP/ss2" "two encapsulations must give different secrets" +} + +# DHKEM rejects implicitly: the wrong private key gives a different secret, not an error. +test_decaps_with_wrong_key_gives_different_secret() { + local got + "$BC_RUST" x25519 keygen >"$TMP/sk" + got=$(hex_out "$BC_RUST" x25519 decaps --skfile "$TMP/sk" -x < <(unhex "$ENC")) + assert_eq "${#got}" 64 "hex shared secret length" + [ "$got" != "$SHARED_SECRET" ] || fail "the wrong private key must not give the RFC secret" +} + +# ---- errors ------------------------------------------------------------------------------- + +# An all-zero public key has small order, so the shared secret would be all zeros, which RFC 9180 +# Section 7.1.4 and RFC 8446 Section 7.4.2 require rejecting. +test_low_order_public_key_is_rejected() { + printf '%s' "$ALICE_SK" >"$TMP/sk" + printf '%064d' 0 >"$TMP/zero.pk" + expect_fail "agree with an all-zero public key" \ + "$BC_RUST" --hex-input x25519 agree --skfile "$TMP/sk" --pkfile "$TMP/zero.pk" + assert_stderr_has "AgreementFailed" + expect_fail "encaps to an all-zero public key" \ + "$BC_RUST" --hex-input x25519 encaps --pkfile "$TMP/zero.pk" --ctfile "$TMP/ct" + expect_fail "decaps of an all-zero enc" \ + "$BC_RUST" --hex-input x25519 decaps --skfile "$TMP/sk" --ctfile "$TMP/zero.pk" +} + +test_wrong_length_inputs_are_rejected() { + printf '%s' "$ALICE_SK" >"$TMP/sk" + printf '%s' "${BOB_PK:0:62}" >"$TMP/short.pk" + expect_fail "31-byte private key" "$BC_RUST" --hex-input x25519 pk-from-sk < <(printf '%s' "${ALICE_SK:0:62}") + assert_stderr_has "private key" + expect_fail "31-byte public key" \ + "$BC_RUST" --hex-input x25519 agree --skfile "$TMP/sk" --pkfile "$TMP/short.pk" + assert_stderr_has "public key" + expect_fail "31-byte ciphertext" \ + "$BC_RUST" --hex-input x25519 decaps --skfile "$TMP/sk" --ctfile "$TMP/short.pk" + assert_stderr_has "ciphertext" +} + +test_missing_files_are_rejected() { + printf '%s' "$ALICE_SK" >"$TMP/sk" + expect_fail "agree without --pkfile" "$BC_RUST" --hex-input x25519 agree <"$TMP/sk" + assert_stderr_has "pkfile" + expect_fail "check-consistency without --pkfile" "$BC_RUST" --hex-input x25519 check-consistency <"$TMP/sk" + assert_stderr_has "pkfile" + expect_fail "decaps without --skfile" "$BC_RUST" --hex-input x25519 decaps < <(printf '%s' "$ENC") + assert_stderr_has "skfile" +} + +run_all diff --git a/crypto/core/src/errors.rs b/crypto/core/src/errors.rs index 71c7fe05..9d3db99c 100644 --- a/crypto/core/src/errors.rs +++ b/crypto/core/src/errors.rs @@ -76,6 +76,8 @@ pub enum KEMError { DecapsulationFailed, /// DecodingError(&'static str), + /// The public key given to encapsulation is unusable, for example a point of small order. + InvalidPublicKey(&'static str), /// KeyGenError(&'static str), /// diff --git a/crypto/core/src/kdf_params.rs b/crypto/core/src/kdf_params.rs index d20fb53f..64e95509 100644 --- a/crypto/core/src/kdf_params.rs +++ b/crypto/core/src/kdf_params.rs @@ -2,6 +2,7 @@ //! description of the KDF, the fixed info of the derivation, and the length of what it derives. use crate::errors::KDFError; +use crate::key_material::{KeyMaterial, KeyMaterialTrait}; use crate::traits::{AlgorithmInfo, KDF}; /// The length of the key a derivation produces, in bytes, as a value: the third argument of @@ -77,6 +78,31 @@ impl<'p, D: KdfDescription + ?Sized, const LEN: usize> KdfParams<'p, D, LEN> { pub fn info(&self) -> &'p [u8] { self.info } + + /// KDF(ikm, info) into `out`, zeroized first: a key of `LEN` bytes, derived by an engine + /// built from the description for this one derivation. What a software pairing does with + /// its shared secret; the caller's buffer is where the key lives. + /// + /// # Errors + /// What the KDF refuses, building the engine ([`KdfDescription::engine`]) or deriving + /// ([`KDF::derive_key_out`]), and [`KDFError::GenericError`] if it writes anything but `LEN` + /// bytes; `out` is left zeroized. + pub fn derive_out( + &self, + ikm: &KeyMaterial, + out: &mut KeyMaterial, + ) -> Result<(), KDFError> { + out.zeroize(); + // `derive_key_out` zeroizes `out` first and leaves it so on its errors. + let kdf = self.kdf.engine()?; + let written = kdf.derive_key_out(ikm, self.info, LEN, out)?; + // The trait says `len` bytes come back; the key handed out is LEN bytes. + if written != LEN || out.key_len() != LEN { + out.zeroize(); + return Err(KDFError::GenericError("the KDF derived a key of the wrong length")); + } + Ok(()) + } } // Written out rather than derived: a derive would demand `D: Copy` of the description. diff --git a/crypto/eccdh/src/kdf.rs b/crypto/eccdh/src/kdf.rs index a945b920..58ad8748 100644 --- a/crypto/eccdh/src/kdf.rs +++ b/crypto/eccdh/src/kdf.rs @@ -17,9 +17,10 @@ //! A key under a KDF its curve is not paired with has no role, so the wrong KDF is a compile //! error; a further pairing is one marker and one impl. //! -//! The derived key is typed by the KDF's accounting ([`KDF`]'s docs): `CryptographicRandom` at -//! the least of the curve's strength, the KDF's and the length's, so a key shorter than 14 -//! bytes carries no strength although the algorithm's `MAX_SECURITY_STRENGTH` is the curve's. +//! The derived key is typed by the KDF's accounting ([`KDF`](bouncycastle_core::traits::KDF)'s +//! docs): `CryptographicRandom` at the least of the curve's strength, the KDF's and the +//! length's, so a key shorter than 14 bytes carries no strength although the algorithm's +//! `MAX_SECURITY_STRENGTH` is the curve's. //! An all-zero `Z` (`x_P = 0`, on the curve for P-256, P-384 and P-521 and not arrangeable //! without `d`) reaches the KDF typed `Zeroized` and credits nothing: the X9.63 and //! concatenation roles, and HKDF with an empty salt, return a key typed `Unknown` with no @@ -62,8 +63,8 @@ use bouncycastle_concatkdf::{ConcatKDF, ConcatKDFParams}; use bouncycastle_core::agreement_key::KeyAgreementAlgorithm; use bouncycastle_core::errors::KeyAgreementError; use bouncycastle_core::kdf_params::{KdfDescription, KdfParams}; -use bouncycastle_core::key_material::{KeyMaterial, KeyMaterialTrait}; -use bouncycastle_core::traits::{HashAlgParams, KDF}; +use bouncycastle_core::key_material::KeyMaterial; +use bouncycastle_core::traits::HashAlgParams; use bouncycastle_hkdf::HkdfDescription; use bouncycastle_sha2::SHA256; use bouncycastle_x963kdf::{X963KDF, X963KDFParams}; @@ -111,12 +112,12 @@ pub trait KdfPairing Vec { + DUMMY_SEED + .chunks(32) + .take(NUM_ELEMS) + .enumerate() + .map(|(i, chunk)| { + // The chunks of DUMMY_SEED repeat every 8; mixing in the index keeps all NUM_ELEMS + // seeds distinct. + let mut bytes: [u8; 32] = chunk.try_into().unwrap(); + bytes[0] ^= i as u8; + KeyMaterial256::from_bytes_as_type(&bytes, KeyType::Seed).unwrap() + }) + .collect() +} + +/// A key pair for each of [`seeds`]. +fn key_pairs() -> Vec<(X25519PublicKey, X25519PrivateKey)> { + seeds().iter().map(|seed| keygen_from_seed(seed).unwrap()).collect() +} + +fn bench_x25519_keygen(c: &mut Criterion) { + let mut group = c.benchmark_group("KeyGen"); + + // Set up the seeds outside of the timing loop. + let seeds = seeds(); + + group.throughput(criterion::Throughput::Elements(seeds.len() as u64)); + + group.bench_function("X25519", |b| { + b.iter(|| { + for seed in seeds.iter() { + _ = black_box(keygen_from_seed(seed)); + } + }) + }); + + group.finish(); +} + +fn bench_x25519_key_agreement(c: &mut Criterion) { + let mut group = c.benchmark_group("KeyAgreement"); + + let keys = key_pairs(); + + group.throughput(criterion::Throughput::Elements(keys.len() as u64)); + + // Each private key agrees with the next key pair's public key. + group.bench_function("X25519", |b| { + b.iter(|| { + for i in 0..keys.len() { + let pk = &keys[(i + 1) % keys.len()].0; + _ = black_box(keys[i].1.agree(pk, ())); + } + }) + }); + + group.finish(); +} + +fn bench_x25519_encaps(c: &mut Criterion) { + let mut group = c.benchmark_group("Encaps"); + + let keys = key_pairs(); + + // A fixed-output RNG per encapsulation, so that we're not measuring the time of the DRBG. + let mut ephemeral_seeds = [[0u8; 32]; NUM_ELEMS]; + for (i, seed) in ephemeral_seeds.iter_mut().enumerate() { + seed.fill(i as u8 + 1); + } + + group.throughput(criterion::Throughput::Elements(NUM_ELEMS as u64)); + + group.bench_function("DHKEM(X25519, HKDF-SHA256)", |b| { + b.iter(|| { + for i in 0..NUM_ELEMS { + let mut rng = FixedSeedRNG::new(ephemeral_seeds[i]); + _ = black_box(keys[i].0.encaps(&mut rng, ())); + } + }) + }); + + group.finish(); +} + +fn bench_x25519_decaps(c: &mut Criterion) { + let mut group = c.benchmark_group("Decaps"); + + let keys = key_pairs(); + + // Set up the ciphertexts outside of the timing loop. + let mut rng = FixedSeedRNG::new(&DUMMY_SEED[..32]); + let cts: Vec<[u8; 32]> = + keys.iter().map(|(pk, _sk)| pk.encaps(&mut rng, ()).unwrap().1).collect(); + + group.throughput(criterion::Throughput::Elements(NUM_ELEMS as u64)); + + group.bench_function("DHKEM(X25519, HKDF-SHA256)", |b| { + b.iter(|| { + for i in 0..NUM_ELEMS { + _ = black_box(keys[i].1.decaps(&cts[i], ())); + } + }) + }); + + group.finish(); +} + +criterion_group!( + benches, + bench_x25519_keygen, + bench_x25519_key_agreement, + bench_x25519_encaps, + bench_x25519_decaps, +); +criterion_main!(benches); diff --git a/crypto/ed/src/curve25519.rs b/crypto/ed/src/curve25519.rs new file mode 100644 index 00000000..bda71a12 --- /dev/null +++ b/crypto/ed/src/curve25519.rs @@ -0,0 +1,732 @@ +use bouncycastle_utils::ct::Condition; + +/// Mask for one limb: `2^51 - 1`. A [`FieldElement25519`] holds the value +/// `x0 + x1*2^51 + x2*2^102 + x3*2^153 + x4*2^204`, so `& M51` extracts a limb's own 51 bits and +/// leaves the overflow to be carried into the next limb (or, out of `x4`, folded back into `x0` +/// scaled by 19, since `2^255 == 19 mod p`). +const M51: i64 = (1 << 51) - 1; + +/// An element of GF(p), p = 2^255 - 19: the field that curve25519's point coordinates live in. +/// +/// This is the base field, as opposed to the scalar field of integers mod the group order that +/// private keys live in. Every coordinate in this crate is one of these: the u-coordinate of +/// X25519 (RFC7748), and the x and y coordinates of Ed25519 (RFC8032). +/// +/// # Representation +/// Five signed 64-bit limbs in radix 2^51, holding the value +/// `x0 + x1*2^51 + x2*2^102 + x3*2^153 + x4*2^204` (see [`M51`]). Arithmetic is lazily reduced: +/// limbs may exceed 51 bits or go negative between operations, so the same residue mod p has many +/// representations. [`Self::normalize`] produces the canonical representation as a +/// [`NormalizedFieldElement25519`], the only type that encodes, compares and tests parity. +/// +/// # Mathematical operations implemented +/// Addition and subtraction (lazily reduced), multiplication, squaring and multiplication by a +/// small constant, inversion, a constant-time swap, decoding from 32 bytes and, through +/// [`Self::normalize`], the canonical form that encodes. Everything is constant time. The limbs +/// are wiped with volatile stores when a value is dropped, so every intermediate of the ladder +/// and the inversion is cleared at the end of its lifetime (QUALITY_AND_STYLE.md's rule for a +/// local computed from a secret); what the compiler kept in registers or spilled itself is not +/// reached. +/// +/// # Math Background +/// The group law on elliptic curve points is point addition, where A + B yields a new point C on +/// the curve. The special case of adding a point to itself, A + A, is called "point doubling" and +/// is often implemented separately because it can be done more efficiently than the general case. +/// Repeated addition, A + A + ... + A, is written k * A for a scalar k and called "scalar +/// multiplication", again implemented separately. All three are built out of the field operations +/// on this type. +/// +/// X25519 represents a point in Montgomery form by its u-coordinate alone, which identifies a +/// point on the curve or its quadratic twist up to sign; ie it names the pair {P, -P}. Point +/// doubling and scalar multiplication are well-defined on u-coordinates, since they commute with +/// negation (k*(-A) = -(k*A)), but general point addition is not. XDH (RFC7748) only needs scalar +/// multiplication, which the Montgomery ladder in [`crate::x25519`] computes. Ed25519 uses the full +/// (x, y) coordinates on the equivalent twisted Edwards curve, where general addition is defined. +#[derive(Clone, Default)] +#[must_use] // to help catch bugs that x.sqr() actually returns a result rather than mutates x, so not using the return is a bug. +pub(crate) struct FieldElement25519([i64; 5]); + +impl FieldElement25519 { + /// Wipes the limbs with volatile stores (`zeroize_in_place`); [`Drop`] calls it, so an + /// explicit call is only for a value that must be cleared before it goes out of scope. + pub(crate) fn zeroize(&mut self) { + bouncycastle_utils::secret::zeroize_in_place(&mut self.0); + } +} + +impl Drop for FieldElement25519 { + fn drop(&mut self) { + self.zeroize(); + } +} + +impl FieldElement25519 { + /// Add another [`FieldElement25519`] to this one, component-wise. + /// + /// Lazily reduced: no carry propagation, so limb magnitudes grow by up to one bit and the result + /// is congruent mod p but not normalized. That is deliberate -- every consumer here funnels into + /// a [`Self::mul`], [`Self::sqr`] or [`Self::mul_u32`], each of which reduces through + /// [`Self::reduce_products`], so magnitudes never run away and an explicit carry pass is not + /// needed. + pub(crate) fn add(&self, rhs: &Self) -> Self { + let [x0, x1, x2, x3, x4] = self.0; + let [y0, y1, y2, y3, y4] = rhs.0; + Self([x0 + y0, x1 + y1, x2 + y2, x3 + y3, x4 + y4]) + } + + /// Returns `(self + rhs, self - rhs)` in one pass over the limbs. + /// + /// Each half is the plain limb-wise [`Self::add`] / [`Self::sub`], with the same lazy-reduction + /// caveat: no carry propagation, so limbs may go negative and both results are congruent mod p + /// but not normalized. Fusing them avoids reading the limbs twice, and matches the fact that + /// the ladder always wants the sum and the difference of the same pair. + /// + /// This is Section 5 of RFC7748's `A = x_2 + z_2` / `B = x_2 - z_2` pair, and equally its + /// `C = x_3 + z_3` / `D = x_3 - z_3`. It is the workhorse of the ladder in [`crate::x25519`]. + /// + /// Note on the name: RFC7748 does not name this operation -- it writes the two assignments out + /// separately, so there is no spec name to match. + pub(crate) fn sum_and_difference(&self, rhs: &Self) -> (Self, Self) { + let [x0, x1, x2, x3, x4] = self.0; + let [y0, y1, y2, y3, y4] = rhs.0; + ( + Self([x0 + y0, x1 + y1, x2 + y2, x3 + y3, x4 + y4]), + Self([x0 - y0, x1 - y1, x2 - y2, x3 - y3, x4 - y4]), + ) + } + + /// Conditionally Swap the values of lhs and rhs if `cond` is true. + /// + /// Constant time: both limb arrays are rewritten unconditionally with a masked exchange, so + /// nothing about `cond` -- and hence nothing about the scalar bit driving it -- leaks through + /// memory access patterns or timing. + pub(crate) fn cswap(cond: Condition, lhs: &mut Self, rhs: &mut Self) { + (lhs.0[0], rhs.0[0]) = cond.swap(lhs.0[0], rhs.0[0]); + (lhs.0[1], rhs.0[1]) = cond.swap(lhs.0[1], rhs.0[1]); + (lhs.0[2], rhs.0[2]) = cond.swap(lhs.0[2], rhs.0[2]); + (lhs.0[3], rhs.0[3]) = cond.swap(lhs.0[3], rhs.0[3]); + (lhs.0[4], rhs.0[4]) = cond.swap(lhs.0[4], rhs.0[4]); + } + + /// Decodes 32 little-endian bytes as a field element, ignoring bit 255 (the most significant + /// bit of the final byte); the inverse of [`NormalizedFieldElement25519::encode_255`]. + /// + /// This is the RFC-neutral byte layout shared by both protocols. Callers own the meaning of + /// bit 255 and the policy on non-canonical input: X25519 ignores the bit and accepts values + /// `>= p` (`decode_u_coordinate` in `x25519.rs`, RFC7748 Section 5), while Ed25519 reads the bit + /// as the sign of x and rejects a y-coordinate `>= p` (RFC8032 Section 5.1.3). + /// + /// Note: Result is NOT normalized -- the value is in `[0, 2^255)`, so the 19 encodings of + /// `2^255 - 19 .. 2^255 - 1` decode to values `>= p`. Call [`Self::normalize`] before comparing + /// or encoding. + /// + /// Input: 32 bytes, read as a little-endian integer. + /// Output: The low 255 bits of that integer as a [`FieldElement25519`]. + pub(crate) fn decode_255(bytes: &[u8; 32]) -> Self { + /// Unpacks a 256-bit little-endian integer held as four 64-bit words into the five 51-bit limbs + /// of a [`FieldElement25519`], where the represented value is + /// `z0 + z1*2^51 + z2*2^102 + z3*2^153 + z4*2^204`. Each limb is a 51-bit window of the input, + /// straddling word boundaries; the `& M51` masks make every limb non-negative and leave headroom + /// for lazily-carried arithmetic. Bit 255 of the input is dropped -- see [`Self::decode_255`]. + /// Inverse of [`NormalizedFieldElement25519::encode64_255`]. + /// Input: A 256-bit integer as four little-endian 64-bit words, least significant word first. + /// Output: Bits 0..254 of that integer as a [`FieldElement25519`]. + /// + /// Note: Result is NOT normalized. + fn decode64_255(x: &[u64; 4]) -> FieldElement25519 { + let [x0, x1, x2, x3] = *x; + let z0 = x0 as i64 & M51; + let z1 = (x0 >> 51 | x1 << 13) as i64 & M51; + let z2 = (x1 >> 38 | x2 << 26) as i64 & M51; + let z3 = (x2 >> 25 | x3 << 39) as i64 & M51; + let z4 = (x3 >> 12) as i64 & M51; + FieldElement25519([z0, z1, z2, z3, z4]) + } + + let b = bytes; + let x0 = u64::from_le_bytes([b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7]]); + let x1 = u64::from_le_bytes([b[8], b[9], b[10], b[11], b[12], b[13], b[14], b[15]]); + let x2 = u64::from_le_bytes([b[16], b[17], b[18], b[19], b[20], b[21], b[22], b[23]]); + let x3 = u64::from_le_bytes([b[24], b[25], b[26], b[27], b[28], b[29], b[30], b[31]]); + decode64_255(&[x0, x1, x2, x3]) + } + + /// Multiplicative inverse in GF(p), by Fermat's little theorem: `x^(p-2) == x^-1`. + /// + /// [`Self::pow_p_sub5_div8`] writes `x^3` and `x^((p-5)/8)` into this frame's two buffers. + /// Raising the second to the 8th and multiplying by the first gives exponent + /// `8 * (2^252 - 3) + 3 == 2^255 - 21 == p - 2`. Costs 254 squarings and 12 multiplies. The + /// two buffers, which together give `x^-1`, are wiped when this frame drops them. + /// + /// Constant time: a fixed addition chain, with no data-dependent branch or index. + /// + /// `inv(0) == 0`, since `0^(p-2) == 0`. That is not a case to guard against -- X25519 depends + /// on it. A small-order input point drives the ladder's `z_2` to zero, and Section 6.1 of + /// RFC7748 requires the resulting all-zero output to be detectable: "the X25519 function + /// produces that value if it operates on an input corresponding to a point with small order". + /// Returning zero here is what carries that through the final `x_2 * z_2^-1`. + /// + /// `x * inv(x) = 1` is checked in the test module over the edge cases and patterned values. + /// + /// Scope: both x25519 and ed25519. + // TODO -- a safegcd-style `mod_odd_inverse` would be asymptotically cheaper. Only worth + // revisiting if this shows up in a profile -- it is one call per scalar_mult_into. + pub(crate) fn inv(&self) -> Self { + let mut x_cubed = Self::zero(); + let mut t = Self::zero(); + self.pow_p_sub5_div8(&mut x_cubed, &mut t); + t.sqr_n(3).mul(&x_cubed) + } + + /// Multiply self by rhs in GF(p), `p = 2^255 - 19`. + /// + /// Schoolbook 5x5: output limb `k` collects every `x[i] * y[j]` with `i + j == k`, plus every + /// pair with `i + j == k + 5`. The second set lands at weight `2^255` or above, and + /// `2^255 == 19 mod p`, so those terms are pre-scaled by 19 -- that is what `t1..t4` are. The 25 + /// products accumulate in `i128` (a 51-bit by 56-bit product would overflow `i64`) and + /// [`Self::reduce_products`] carries them back down to five `i64` limbs. + pub(crate) fn mul(&self, rhs: &Self) -> Self { + #[inline(always)] + fn m(x: i64, y: i64) -> i128 { + x as i128 * y as i128 + } + + let [x0, x1, x2, x3, x4] = self.0; + let [y0, y1, y2, y3, y4] = rhs.0; + let [t1, t2, t3, t4] = [y1 * 19, y2 * 19, y3 * 19, y4 * 19]; + + Self::reduce_products( + m(x0, y0) + m(x1, t4) + m(x2, t3) + m(x3, t2) + m(x4, t1), + m(x0, y1) + m(x1, y0) + m(x2, t4) + m(x3, t3) + m(x4, t2), + m(x0, y2) + m(x1, y1) + m(x2, y0) + m(x3, t4) + m(x4, t3), + m(x0, y3) + m(x1, y2) + m(x2, y1) + m(x3, y0) + m(x4, t4), + m(x0, y4) + m(x1, y3) + m(x2, y2) + m(x3, y1) + m(x4, y0), + ) + } + + /// Multiply self by a small unsigned scalar in GF(p). + /// + /// A single-limb multiply, so unlike [`Self::mul`] there are no wrap-around terms to pre-scale by + /// 19 -- each output limb takes exactly one product. The `19` fold still happens, but only for + /// whatever carries out of the top limb inside [`Self::reduce_products`]. + /// + /// Scope: X25519. This is the `a24 * E` of the Section 5 ladder, with + /// `a24 = (486662 - 2) / 4 = 121665`; both callers here pass `121666`, the `(A + 2) / 4` + /// form, see `C_A24` in `x25519.rs`. + pub(crate) fn mul_u32(&self, rhs: u32) -> Self { + #[inline(always)] + fn m(x: i64, y: i64) -> i128 { + x as i128 * y as i128 + } + + let [x0, x1, x2, x3, x4] = self.0; + let y0 = rhs as i64; + + Self::reduce_products(m(x0, y0), m(x1, y0), m(x2, y0), m(x3, y0), m(x4, y0)) + } + + /// The canonical representation of the value: every limb in `[0, 2^51)` and the value in + /// `[0, p)`, as a [`NormalizedFieldElement25519`]. Idempotent. + /// + /// Total on every input whose limbs lie in `[-2^53, 2^53]`, which covers everything the + /// arithmetic here produces: [`Self::reduce_products`] leaves limb 0 in `[0, 2^51)` and the + /// others in `(-2^9, 2^51 + 2^9)`, [`Self::decode_255`] leaves all five in `[0, 2^51)`, and + /// one lazy [`Self::add`] or [`Self::sub`] of two such values stays well inside the bound. + /// + /// Four carry passes of [`Self::reduce`]. With `V` the value and `x4 >> 51` the top limb's + /// overflow `t5`, each pass computes `V - p * t5` with limbs 0 to 3 in `[0, 2^51)`: + /// 1. `reduce(0)`: `t5` is in `[-4, 4]` and the carries in `[-5, 4]`, so limb 4 comes out in + /// `[-5, 2^51 + 4]`. + /// 2. `reduce(0)` again: `t5` is now `-1`, `0` or `1`. A negative limb 4 means `V < 0`, and + /// adding `p` leaves limb 4 in `[2^51 - 6, 2^51 - 1]`; a limb 4 of `2^51` or `2^51 + 1` + /// loses one `p` and comes out in `[0, 2]`; otherwise nothing moves. So every limb is in + /// `[0, 2^51)` and `V` is in `[0, 2^255)`: canonical limbs, value possibly in `[p, 2^255)`. + /// 3. `reduce(1)` adds `19`: `V + 19` is `2^255 + (V - p)` when `V >= p`, which leaves limb 4 + /// at exactly `2^51` since `V - p < 19`, and stays below `2^255` with canonical limbs + /// otherwise. + /// 4. `reduce(-1)`: when limb 4 is `2^51`, `t5 = 1 - 1 = 0` drops the `2^255` and the result + /// is `V - p`, in `[0, 19)`; otherwise `t5 = -1` takes the `19` back and the borrow it may + /// cause resolves inside the limbs, since the result `V` is at least `0`. + /// + /// Pass 3's `+19` is what implements Section 5 of RFC7748's "Implementations MUST accept + /// non-canonical values and process them as if they had been reduced modulo the field + /// prime. The non-canonical values are 2^255 - 19 through 2^255 - 1": `v >= p` if and only + /// if `v + 19 >= 2^255`. The `normalize_edge_values` unit test pins `p - 1`, `p` and + /// `2^255 - 1`. + pub(crate) fn normalize(&self) -> NormalizedFieldElement25519 { + NormalizedFieldElement25519(self.reduce(0).reduce(0).reduce(1).reduce(-1)) + } + + /// The multiplicative identity, 1, in canonical form. + pub(crate) fn one() -> Self { + Self([1, 0, 0, 0, 0]) + } + + /// Writes `x^3` to `x_cubed` and `x^((p-5)/8)` to `z`, for `x = self`, by a fixed addition + /// chain. Both are the caller's buffers so that they are wiped in the caller's frame; the + /// chain's intermediates are this frame's temporaries, wiped as they drop. + /// + /// `(p - 5) / 8 == 2^252 - 3` for `p = 2^255 - 19`, which in binary is 250 ones, a zero, then a + /// one -- the `FFFF..FD` of the comment below. The chain reaches it in 10 steps by doubling runs + /// of 1-bits. Both outputs are checked through the inversion test in the test module. + /// + /// Beware the naming: the locals count *consecutive 1-bits*, not exponents. `x_cubed` is `x^3` + /// (`0b11`, two ones), `x3` is `x^7`, `x5` is `x^31`, and `x250` is `x^(2^250 - 1)`. It reads + /// like an off-by-one bug and is not one. + /// + /// Inversion takes both, as `z.sqr_n(3).mul(&x_cubed)` -- exponent + /// `8 * (2^252 - 3) + 3 == 2^255 - 21 == p - 2`, i.e. Fermat. The `p == 5 mod 8` square root + /// Ed25519 will need takes `z` alone, as its candidate. + fn pow_p_sub5_div8(&self, x_cubed: &mut Self, z: &mut Self) { + // z = x^((p-5)/8) = x^FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFD + // (250 1s) (1 0s) (1 1s) + // Addition chain: [1] 2 3 5 10 15 25 50 75 125 [250] + + let x = self; + *x_cubed = x.sqr().mul(x); + let x3 = x_cubed.sqr().mul(x); + let x5 = x3.sqr_n(2).mul(x_cubed); + let x10 = x5.sqr_n(5).mul(&x5); + let x15 = x10.sqr_n(5).mul(&x5); + let x25 = x15.sqr_n(10).mul(&x10); + let x50 = x25.sqr_n(25).mul(&x25); + let x75 = x50.sqr_n(25).mul(&x25); + let x125 = x75.sqr_n(50).mul(&x50); + let x250 = x125.sqr_n(125).mul(&x125); + + *z = x250.sqr_n(2).mul(x); + } + + /// One carry pass that additionally subtracts `(x4 >> 51)` multiples of p and adds `19 * y` at + /// the bottom. Not a standalone reduction -- see the warning below. + /// + /// Bits at or above `2^255` (the `x4 >> 51` carry) are removed from the top and re-added at the + /// bottom scaled by 19, which subtracts a multiple of `p = 2^255 - 19`. The `y` argument is added + /// into that same fold, so it contributes `19 * y` at the bottom with *no* matching removal at + /// the top. The verified identity is: + /// + /// ```text + /// value(reduce(x, y)) == value(x) - (x4 >> 51) * p + 19 * y + /// ``` + /// + /// Warning: a single `reduce` is therefore **not** congruent to its input mod p unless `y == 0`. + /// The `19 * y` is a deliberate offset that only cancels across the pair of calls in + /// [`Self::normalize`], and this function exists to serve that pair -- it is not a general-purpose + /// reduction. + /// + /// Requires limbs inside the magnitude bound the carry chain assumes: `t5 * 19 + x0` must not + /// overflow `i64`. + fn reduce(&self, y: i64) -> Self { + let [x0, x1, x2, x3, x4] = self.0; + + let t4 = x4 & M51; + let t5 = (x4 >> 51) + y; + + let mut c = t5 * 19; + + c += x0; + let z0 = c & M51; + c >>= 51; + c += x1; + let z1 = c & M51; + c >>= 51; + c += x2; + let z2 = c & M51; + c >>= 51; + c += x3; + let z3 = c & M51; + c >>= 51; + c += t4; + let z4 = c; + + Self([z0, z1, z2, z3, z4]) + } + + /// Carry the five `i128` product accumulators produced by [`Self::mul`], [`Self::sqr`] and + /// [`Self::mul_u32`] back down into five `i64` limbs. + /// + /// One pass: `split` peels each accumulator into its own 51 bits and the carry above them, the + /// carries move up one limb each, and the carry out of the top (`c5`, at weight `2^255`) folds + /// into limb 0 scaled by 19 because `2^255 == 19 mod p`. A second short carry chain over + /// `u0..u3` absorbs the fold. + /// + /// The result is congruent mod p with limbs near 51 bits, but is *not* normalized -- it may still + /// exceed p. Call [`Self::normalize`] before encoding or comparing. + fn reduce_products(p0: i128, p1: i128, p2: i128, p3: i128, p4: i128) -> Self { + #[inline(always)] + fn split(x: i128) -> (i64, i64) { + (x as i64 & M51, (x >> 51) as i64) + } + + let (t0, c1) = split(p0); + let (t1, c2) = split(p1); + let (t2, c3) = split(p2); + let (t3, c4) = split(p3); + let (t4, c5) = split(p4 + c4 as i128); + + let u0 = t0 + c5 * 19; + let u1 = t1 + c1; + let u2 = t2 + c2; + let u3 = t3 + c3; + + Self([ + u0 & M51, + (u1 & M51) + (u0 >> 51), + (u2 & M51) + (u1 >> 51), + (u3 & M51) + (u2 >> 51), + t4 + (u3 >> 51), + ]) + } + + /// Square self in GF(p). + /// + /// Same shape as [`Self::mul`], but a squaring's cross terms come in equal pairs, so pre-doubling + /// `x0..x3` into `y0..y3` lets one product stand for two and drops the count from 25 to 15. The + /// `19` fold for the `i + j >= 5` terms is folded into `t3`, `t4` as before. + pub(crate) fn sqr(&self) -> Self { + #[inline(always)] + fn m(x: i64, y: i64) -> i128 { + x as i128 * y as i128 + } + + let [x0, x1, x2, x3, x4] = self.0; + let [y0, y1, y2, y3] = [x0 * 2, x1 * 2, x2 * 2, x3 * 2]; + let [t3, t4] = [x3 * 19, x4 * 19]; + + Self::reduce_products( + m(x0, x0) + m(y1, t4) + m(y2, t3), + m(y0, x1) + m(y2, t4) + m(x3, t3), + m(y0, x2) + m(x1, x1) + m(y3, t4), + m(y0, x3) + m(y1, x2) + m(x4, t4), + m(y0, x4) + m(y1, x3) + m(x2, x2), + ) + } + + /// Square self `n` times, i.e. raise to the `2^n`. + pub(crate) fn sqr_n(&self, mut n: usize) -> Self { + let mut z = Self(self.0); + while n > 0 { + z = z.sqr(); + n -= 1; + } + z + } + + /// Subtract rhs from self, component-wise. + /// + /// Lazily reduced, exactly as [`Self::add`]: no borrow propagation, so limbs may go negative and + /// the result is congruent mod p but not normalized. Negative limbs are fine here -- + /// [`Self::reduce_products`] and [`Self::reduce`] both use arithmetic (sign-propagating) shifts, + /// so a negative limb borrows correctly on the next reduction. + pub(crate) fn sub(&self, rhs: &Self) -> Self { + let [x0, x1, x2, x3, x4] = self.0; + let [y0, y1, y2, y3, y4] = rhs.0; + Self([x0 - y0, x1 - y1, x2 - y2, x3 - y3, x4 - y4]) + } + + /// The additive identity, 0, in canonical form. + pub(crate) fn zero() -> Self { + Self([0; 5]) + } +} + +/// A [`FieldElement25519`] in canonical form: every limb in `[0, 2^51)` and the value in `[0, p)`. +/// The only constructor is [`FieldElement25519::normalize`]. +/// +// TODO -- impl Deref once a caller needs to continue arithmetic on a +// normalized value (e.g. Ed25519 point decompression). +#[derive(Clone)] +#[must_use] +pub(crate) struct NormalizedFieldElement25519(FieldElement25519); + +impl NormalizedFieldElement25519 { + /// Debug-only check of the invariant this type carries: every limb in `[0, 2^51)` and the + /// value below p. Every method calls it first; it compiles to nothing in release builds. + /// + /// p's limbs are `[2^51 - 19, 2^51 - 1, 2^51 - 1, 2^51 - 1, 2^51 - 1]`, so a value with every + /// limb in range is `>= p` exactly when limbs 1..4 are all `2^51 - 1` and limb 0 is at least + /// `2^51 - 19`. + /// + /// Branches on the limbs, so it is not constant time. That is acceptable only because it is + /// compiled out of release builds. + fn debug_check_range(&self) { + let [x0, x1, x2, x3, x4] = self.0.0; + debug_assert!((0..=M51).contains(&x0), "limb 0 out of [0, 2^51)"); + debug_assert!((0..=M51).contains(&x1), "limb 1 out of [0, 2^51)"); + debug_assert!((0..=M51).contains(&x2), "limb 2 out of [0, 2^51)"); + debug_assert!((0..=M51).contains(&x3), "limb 3 out of [0, 2^51)"); + debug_assert!((0..=M51).contains(&x4), "limb 4 out of [0, 2^51)"); + debug_assert!( + !(x1 == M51 && x2 == M51 && x3 == M51 && x4 == M51 && x0 >= M51 - 18), + "value >= p" + ); + } + + /// Encodes the field element as a 255-bit value in 32 little-endian bytes; the inverse of + /// [`FieldElement25519::decode_255`]. Bit 255 (the most significant bit of the last byte) is + /// always written as zero. + /// + /// Callers that need that bit to carry something else -- the + /// sign of x in an Ed25519 point encoding (Section 5.1.3 of RFC 8032) -- must OR it in after. + /// + /// Input: self; a 32-byte output buffer. + /// Output: The value written to `bytes` as a 255-bit little-endian integer. + pub(crate) fn encode_255(&self, bytes: &mut [u8; 32]) { + self.debug_check_range(); + let [w0, w1, w2, w3] = self.encode64_255(); + let (a, b, c, d) = (w0.to_le_bytes(), w1.to_le_bytes(), w2.to_le_bytes(), w3.to_le_bytes()); + // Each word fills a fixed 8-byte window, least significant word first. Every index is a + // constant into a fixed-size array, so an out-of-bounds index would be a compile error (the + // deny-by-default `unconditional_panic` lint) and no runtime bounds check survives. + *bytes = [ + a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], // + b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7], // + c[0], c[1], c[2], c[3], c[4], c[5], c[6], c[7], // + d[0], d[1], d[2], d[3], d[4], d[5], d[6], d[7], + ]; + } + + /// Packs the five 51-bit limbs into a 255-bit little-endian integer held as four 64-bit words, + /// each word taking a whole limb plus the low bits of the next. Inverse of the `decode64_255` + /// step inside [`FieldElement25519::decode_255`]. Bit 255 of the result is always zero, since + /// limb `x4` lands in bits 204..254. + /// + /// Relies on the normalized form: every limb in [0, 2^51) and the value reduced mod p. The + /// splices below are `|`, not `+`, so a limb with bits at or above 51 collides with the next + /// limb's bits instead of carrying into them, and the result is garbage. (The `x1 << 51` etc. + /// deliberately shift bits off the top of the i64 -- those are the bits the previous word + /// already carried.) + /// + /// Input: self. + /// Output: The value as four little-endian 64-bit words, least significant word first. + fn encode64_255(&self) -> [u64; 4] { + self.debug_check_range(); + let [x0, x1, x2, x3, x4] = self.0.0; + let z0 = (x0 | x1 << 51) as u64; + let z1 = (x1 >> 13 | x2 << 38) as u64; + let z2 = (x2 >> 26 | x3 << 25) as u64; + let z3 = (x3 >> 39 | x4 << 12) as u64; + [z0, z1, z2, z3] + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Alice's public key from the X25519 test vector in Section 6.1 of RFC 7748, used here purely + /// as a fixed value for the byte <-> limb codec. It is less than p (its top byte is 0x6A), so + /// its encoding is canonical and it needs no normalization to round-trip exactly. + const KNOWN_VALUE: [u8; 32] = [ + 0x85, 0x20, 0xF0, 0x09, 0x89, 0x30, 0xA7, 0x54, // + 0x74, 0x8B, 0x7D, 0xDC, 0xB4, 0x3E, 0xF7, 0x5A, // + 0x0D, 0xBF, 0x3A, 0x0D, 0x26, 0x38, 0x1A, 0xF4, // + 0xEB, 0xA4, 0xA9, 0x8E, 0xAA, 0x9B, 0x4E, 0x6A, + ]; + + /// The same value as five 51-bit limbs: `KNOWN_LIMBS[i] == (v >> (51 * i)) & (2^51 - 1)`, where + /// v is `KNOWN_VALUE` read as a little-endian integer. Computed independently of this crate. + const KNOWN_LIMBS: [i64; 5] = + [0x7308909F02085, 0x69B8FB16E8A94, 0x4EAFC356BDCFA, 0x275FA0D1C1306, 0x6A4E9BAA8EA9A]; + + #[test] + fn decode_255_known_value() { + assert_eq!(FieldElement25519::decode_255(&KNOWN_VALUE).0, KNOWN_LIMBS); + + // Bit 255 is not part of the field element, so setting it must not change the result. + let mut bit_255_set = KNOWN_VALUE; + bit_255_set[31] |= 0x80; + assert_eq!(FieldElement25519::decode_255(&bit_255_set).0, KNOWN_LIMBS); + } + + /// p - 1 = 2^255 - 20, the largest canonical value, passes the range check. + #[test] + fn debug_check_range_accepts_p_minus_1() { + NormalizedFieldElement25519(FieldElement25519([M51 - 19, M51, M51, M51, M51])) + .debug_check_range(); + } + + /// p itself is not canonical; the range check must reject it. + #[test] + #[cfg(debug_assertions)] + #[should_panic(expected = "value >= p")] + fn debug_check_range_rejects_p() { + NormalizedFieldElement25519(FieldElement25519([M51 - 18, M51, M51, M51, M51])) + .debug_check_range(); + } + + /// A limb at 2^51 is out of range even though the value is below p. + #[test] + #[cfg(debug_assertions)] + #[should_panic(expected = "limb 0 out of [0, 2^51)")] + fn debug_check_range_rejects_wide_limb() { + NormalizedFieldElement25519(FieldElement25519([M51 + 1, 0, 0, 0, 0])).debug_check_range(); + } + + /// A value of `2^255` or more is outside the domain normalize is verified on. + /// `2^255` is `19` mod p: the top limb's overflow folds in the first pass. + #[test] + fn normalize_folds_2_pow_255_to_19() { + let n = FieldElement25519([0, 0, 0, 0, M51 + 1]).normalize(); + assert_eq!(n.0.0, [19, 0, 0, 0, 0]); + } + + /// A limb of exactly `2^51` under saturated limbs above it: the value is + /// `2^51 * 2^51 + (2^51 - 1) * (2^102 + 2^153) = 2^204`, well inside the domain. + #[test] + fn normalize_accepts_limb_of_2_pow_51() { + let n = FieldElement25519([0, 1 << 51, M51, M51, 0]).normalize(); + assert_eq!(n.0.0, [0, 0, 0, 0, 1]); + } + + /// The values either side of p, where normalize's `+19` / `-19` passes decide the answer. The + /// last multiply of a scalar multiplication returns the representation `r + p` for many valid + /// results (every `r` in about `[19, 2^207)`), so `[p, 2^255)` is reached routinely through + /// the public API, which is why `normalize` has to be total; see the regression in + /// `tests/x25519_tests.rs`. + #[test] + fn normalize_edge_values() { + // p - 1 = 2^255 - 20: already canonical, unchanged. + let n = FieldElement25519([M51 - 19, M51, M51, M51, M51]).normalize(); + assert_eq!(n.0.0, [M51 - 19, M51, M51, M51, M51]); + + // p = 2^255 - 19: reduces to 0. + let n = FieldElement25519([M51 - 18, M51, M51, M51, M51]).normalize(); + assert_eq!(n.0.0, [0, 0, 0, 0, 0]); + + // 2^255 - 1, the largest non-canonical value: reduces to 18. + let n = FieldElement25519([M51, M51, M51, M51, M51]).normalize(); + assert_eq!(n.0.0, [18, 0, 0, 0, 0]); + } + + #[test] + fn encode_255_known_value() { + // Start from a non-zero buffer so a partial write cannot pass by accident. + let mut bytes = [0xFF_u8; 32]; + FieldElement25519(KNOWN_LIMBS).normalize().encode_255(&mut bytes); + assert_eq!(bytes, KNOWN_VALUE); + } + /// p as limbs, the canonical representation of 0 plus one modulus. + const P_LIMBS: [i64; 5] = [M51 - 18, M51, M51, M51, M51]; + + /// The case the two-pass normalize got wrong: `p - 3` held with limb 4 at `2^51` and limb 1 + /// negative. Its single fold gave `-3`, which the `-19` pass then left with a negative top + /// limb, and `encode_255` wrote garbage in release. Also `p + 1`, `-1` and `2^255 + 2^255`. + #[test] + fn normalize_is_total_on_wide_and_negative_representations() { + let p_minus_3 = FieldElement25519([M51 - 21, -1, 0, 0, 1 << 51]).normalize(); + assert_eq!(p_minus_3.0.0, [M51 - 21, M51, M51, M51, M51]); + let p_plus_1 = FieldElement25519([M51 - 17, M51, M51, M51, M51]).normalize(); + assert_eq!(p_plus_1.0.0, [1, 0, 0, 0, 0]); + let minus_1 = FieldElement25519([-1, 0, 0, 0, 0]).normalize(); + assert_eq!(minus_1.0.0, [M51 - 19, M51, M51, M51, M51]); + let two_to_256 = FieldElement25519([0, 0, 0, 0, 1 << 52]).normalize(); + assert_eq!(two_to_256.0.0, [38, 0, 0, 0, 0]); + let top_negative = FieldElement25519([5, 0, 0, 0, -(1 << 53)]).normalize(); + // -2^257 = -4 * 2^255 = -4 * 19 mod p, plus 5: p - 71. + assert_eq!(top_negative.0.0, [M51 - 18 - 71, M51, M51, M51, M51]); + } + + /// Every limb pattern over the domain's edges: the canonical form is the same whether a + /// value is normalized as given, with `p` added limb-wise, or after a reducing multiply by + /// one; and its limbs are canonical, which `debug_check_range` asserts in debug builds. + #[test] + fn normalize_agrees_with_itself_across_representations_of_the_domain_edges() { + let edges: [i64; 7] = [0, 1, -1, M51, 1 << 51, -(1 << 51), 1 << 53]; + let one = FieldElement25519::one(); + let p = FieldElement25519(P_LIMBS); + for &a in &edges { + for &b in &edges { + for &c in &edges { + for &d in &edges { + for &e in &edges { + // Limb-wise p is only in the domain when the sum is. + if a.saturating_add(M51).abs() > (1 << 53) + || e.saturating_add(M51).abs() > (1 << 53) + { + continue; + } + let x = FieldElement25519([a, b, c, d, e]); + let direct = x.normalize(); + direct.debug_check_range(); + assert_eq!(direct.0.0, x.add(&p).normalize().0.0, "{:?} + p", x.0); + assert_eq!(direct.0.0, x.mul(&one).normalize().0.0, "{:?} * 1", x.0); + } + } + } + } + } + } + + fn patterned_values() -> [FieldElement25519; 10] { + [ + FieldElement25519::one(), + FieldElement25519([2, 0, 0, 0, 0]), + FieldElement25519([3, 0, 0, 0, 0]), + FieldElement25519([19, 0, 0, 0, 0]), + FieldElement25519([M51 - 19, M51, M51, M51, M51]), + FieldElement25519(KNOWN_LIMBS), + FieldElement25519([M51, 0, M51, 0, M51]), + FieldElement25519([1 << 50, 1 << 50, 1 << 50, 1 << 50, 1 << 50]), + FieldElement25519([0x1234567, 0x89abcde, 0xf0f0f0f, 0x5a5a5a5, 0x7777777]), + FieldElement25519([0, 0, 0, 0, 1]), + ] + } + + /// `x * inv(x) = 1` for the patterned values, and `inv` through the two exponents it is built + /// from agrees with `x^(p-2)` computed by square-and-multiply over the exponent's bits. + #[test] + fn inv_is_the_multiplicative_inverse() { + for x in patterned_values() { + let product = x.mul(&x.inv()).normalize(); + assert_eq!(product.0.0, [1, 0, 0, 0, 0], "{:?}", x.0); + } + // x^(p-2) by square-and-multiply, p - 2 = 2^255 - 21, from the top bit down. + let x = FieldElement25519(KNOWN_LIMBS); + let mut acc = FieldElement25519::one(); + for bit in (0..255).rev() { + acc = acc.sqr(); + let exponent_bit = if bit >= 5 { 1 } else { ((0b01011_i64 >> bit) & 1) as u8 }; + // 2^255 - 21 = 0b111...1101011: every bit from 254 down to 5 set, then 01011. + if exponent_bit == 1 { + acc = acc.mul(&x); + } + } + assert_eq!(acc.normalize().0.0, x.inv().normalize().0.0); + } + + /// `sqr` is `mul` of a value by itself, and `mul_u32` is `mul` by the constant as an element. + #[test] + fn sqr_and_mul_u32_agree_with_mul() { + for x in patterned_values() { + assert_eq!(x.sqr().normalize().0.0, x.mul(&x).normalize().0.0, "{:?}", x.0); + let by_const = x.mul(&FieldElement25519([121_666, 0, 0, 0, 0])); + assert_eq!(x.mul_u32(121_666).normalize().0.0, by_const.normalize().0.0, "{:?}", x.0); + } + } + + /// `cswap` exchanges both values when told to and neither when not. + #[test] + fn cswap_swaps_on_the_condition_only() { + let (mut a, mut b) = (FieldElement25519(KNOWN_LIMBS), FieldElement25519::one()); + FieldElement25519::cswap(Condition::::from_bool_const::(), &mut a, &mut b); + assert_eq!((a.0, b.0), (KNOWN_LIMBS, [1, 0, 0, 0, 0])); + FieldElement25519::cswap(Condition::::from_bool_const::(), &mut a, &mut b); + assert_eq!((a.0, b.0), ([1, 0, 0, 0, 0], KNOWN_LIMBS)); + } + + /// `reduce_products`' output limbs lie in the bound `normalize`'s domain argument relies on, + /// for the largest inputs the arithmetic feeds it. + #[test] + fn products_of_the_widest_operands_stay_inside_the_normalize_domain() { + let wide = FieldElement25519([(1 << 51) + (1 << 9); 5]); + let wide_negative = FieldElement25519([-(1 << 9); 5]); + for x in [wide.mul(&wide), wide.sqr(), wide.mul(&wide_negative), wide_negative.sqr()] { + let [x0, x1, x2, x3, x4] = x.0; + assert!((0..1 << 51).contains(&x0), "{:?}", x.0); + for limb in [x1, x2, x3, x4] { + assert!(limb > -(1 << 9) && limb < (1 << 51) + (1 << 9), "{:?}", x.0); + } + } + } +} diff --git a/crypto/ed/src/lib.rs b/crypto/ed/src/lib.rs new file mode 100644 index 00000000..99228e38 --- /dev/null +++ b/crypto/ed/src/lib.rs @@ -0,0 +1,30 @@ +//! The Edwards curve family includes curve25519 and curve448 which are used to construct +//! the EdDSA signature schemes Ed25519 and Ed448, and the XDH key exchange schemes X25519 and X448. +//! The crate name is something of a misnomer, since X25519 and X448 work on the curves' Montgomery +//! form rather than their Edwards form. +//! +//! # Standards +//! +//! Standardization of the Edwards Curve algorithms is spread across a number of documents: +//! * RFC7748 specifies the core elliptic curves "curve25519" and "curve448", as well as the XDH key exchange algorithms X25519 and X448 built on top of them. +//! * RFC8032 specifies the EdDSA digital signature algorithms, also built on top of curve25519 and curve448. +//! * FIPS 186-5 section 7 specifies the EdDSA digital signature algorithms, essentially re-published from RFC 8032. +//! * NIST SP 800-186 gives an excellent treatment of the mathematics of all the families of elliptic curves used in cryptography, including Edwards curves. +//! +//! Note that NIST SP 800-186 §3.2.2 specifies the curves Curve25519 and Curve448, but its Table 2 +//! does not list them for key establishment, and NIST SP 800-56A Rev. 3 does not include XDH +//! (X25519 / X448), so X25519 and X448 are not NIST-approved key agreement schemes. +//! +//! # Usage Examples +//! +//! See the [`x25519`] module for X25519 key generation and sample Alice-and-Bob key agreement schemes. +//! +//! The crate's own source is `no_std`, but its dependencies are not yet (`bouncycastle-core`'s +//! `Vec` returns and the `std` uses in `hmac` and `hkdf`), so a bare-metal build waits on them. + +#![no_std] +#![forbid(unsafe_code)] +#![forbid(missing_docs)] + +mod curve25519; +pub mod x25519; diff --git a/crypto/ed/src/x25519.rs b/crypto/ed/src/x25519.rs new file mode 100644 index 00000000..cf440968 --- /dev/null +++ b/crypto/ed/src/x25519.rs @@ -0,0 +1,1121 @@ +//! X25519 (RFC 7748 Section 5), the Diffie-Hellman function over Curve25519, on the key +//! agreement roles: [`X25519PrivateKey`] implements [`AgreementKey`] over `()` for the raw shared +//! secret `K` of RFC 7748 Section 6.1 and over [`KdfParams`] of HKDF-SHA256 for a key derived +//! from it, and the [`DecapsulatingKey`] role for DHKEM(X25519, HKDF-SHA256) of RFC 9180 +//! Section 4.1, whose [`EncapsulatingKey`] is [`X25519PublicKey`]. +//! +//! # Usage Examples +//! +//! ## Generating keys +//! +//! [`keygen`] draws the 32-byte private key from the caller's RNG, which must offer 128 bits; +//! [`keygen_from_seed`] takes those bytes as a [`KeyMaterial256`] of [`KeyType::Seed`] or +//! [`KeyType::CryptographicRandom`] at [`SecurityStrength::_128bit`] or more, and refuses an +//! all-zero one, which `KeyMaterial` types `Zeroized`. [`X25519PrivateKey::from_bytes`] imports +//! an existing private key from any 32 bytes, all-zero included (a valid key, `2^254` once +//! clamped), and stores them clamped. +//! +//! ```rust +//! use bouncycastle_ed::x25519::keygen; +//! use bouncycastle_rng::HashDRBG_SHA512; +//! +//! let (pk, sk) = keygen(&mut HashDRBG_SHA512::new_from_os())?; +//! assert_eq!(sk.pk(), pk); +//! # Ok::<(), bouncycastle_core::errors::KeyAgreementError>(()) +//! ``` +//! +//! ## X25519 key agreement +//! +//! Alice and Bob each generate a key pair and exchange public keys. Each combines their own +//! private key with the other's public key through the [`AgreementKey`] role, and both arrive +//! at the same `K`. Over `()` that is the raw shared secret, typed [`KeyType::SharedSecret`]: +//! for a KDF and nothing else (see [Security Considerations](#-security-considerations-)). +//! Over [`KdfParams`] of HKDF-SHA256 the key comes back derived, with the fixed info the +//! caller supplies; RFC 7748 Section 6.1 asks for a KDF over `K` and both public keys, so the +//! info here is the two public keys in an order both parties agree on. +//! +//! ```rust +//! use bouncycastle_core::agreement_key::AgreementKey; +//! use bouncycastle_core::kdf_params::{KdfParams, KeyLen}; +//! use bouncycastle_core::key_material::{KeyMaterialTrait, KeyType}; +//! use bouncycastle_core::security_strength::SecurityStrength; +//! use bouncycastle_core::traits::KeyAgreementPublicKey; +//! use bouncycastle_ed::x25519::keygen; +//! use bouncycastle_hkdf::HkdfDescription; +//! use bouncycastle_rng::HashDRBG_SHA512; +//! use bouncycastle_sha2::SHA256; +//! +//! let mut rng = HashDRBG_SHA512::new_from_os(); +//! let (alice_pk, alice_sk) = keygen(&mut rng)?; +//! let (bob_pk, bob_sk) = keygen(&mut rng)?; +//! +//! // The raw shared secret. An error means the other party's public key is unusable (a point +//! // of small order): abort the exchange. +//! let k_a = alice_sk.agree(&bob_pk, ())?; +//! let k_b = bob_sk.agree(&alice_pk, ())?; +//! assert!(k_a.equals(&k_b)); +//! assert_eq!(k_a.key_type(), KeyType::SharedSecret); +//! +//! // The same agreement with the KDF applied: a 32-byte key, CryptographicRandom at X25519's +//! // 128 bits, from one call on each side. +//! let mut info = [0u8; 64]; +//! info[..32].copy_from_slice(&alice_pk.encode()); +//! info[32..].copy_from_slice(&bob_pk.encode()); +//! let hkdf = HkdfDescription::::new(); +//! let key_a = alice_sk.agree(&bob_pk, KdfParams::new(&hkdf, &info, KeyLen::<32>))?; +//! let key_b = bob_sk.agree(&alice_pk, KdfParams::new(&hkdf, &info, KeyLen::<32>))?; +//! assert!(key_a.equals(&key_b)); +//! assert_eq!(key_a.key_type(), KeyType::CryptographicRandom); +//! assert_eq!(key_a.security_strength(), SecurityStrength::_128bit); +//! # Ok::<(), bouncycastle_core::errors::KeyAgreementError>(()) +//! ``` +//! +//! ## X25519 as a KEM +//! +//! [`X25519PublicKey`] and [`X25519PrivateKey`] also implement [`EncapsulatingKey`] and +//! [`DecapsulatingKey`], with `()` as the parameters, as DHKEM(X25519, HKDF-SHA256) of RFC 9180 +//! Section 4.1, the KEM used by HPKE. The sender encapsulates against the recipient's public +//! key and gets a shared secret and a 32-byte ciphertext (an ephemeral public key) to send. The +//! shared secret is already the output of a KDF over the X25519 output and both public keys, +//! ready to use as a key. +//! +//! ```rust +//! use bouncycastle_core::kem_key::{DecapsulatingKey, EncapsulatingKey}; +//! use bouncycastle_ed::x25519::keygen; +//! use bouncycastle_rng::HashDRBG_SHA512; +//! +//! let mut rng = HashDRBG_SHA512::new_from_os(); +//! let (pk, sk) = keygen(&mut rng).unwrap(); +//! +//! // The sender encapsulates against the recipient's public key... +//! let (ss, ct) = pk.encaps(&mut rng, ())?; +//! +//! // ...and the recipient recovers the same shared secret from the ciphertext. +//! let ss1 = sk.decaps(&ct, ())?; +//! assert_eq!(ss, ss1); +//! # Ok::<(), bouncycastle_core::errors::KEMError>(()) +//! ``` +//! +//! A public key is its 32 bytes, compared as bytes: two encodings of one point (bit 255 set, or +//! `u + p`) are two keys to [`PartialEq`] and to `check-consistency`, and encapsulating to a +//! non-canonical encoding of the recipient's key gives a secret the recipient cannot derive from +//! the canonical one. Both follow RFC 7748 Section 5 and RFC 9180 Section 7.1.1 to the letter; +//! a protocol that compares keys should compare canonical encodings. +//! +//! Like any unauthenticated Diffie-Hellman, X25519 on its own resists only passive +//! eavesdroppers. An active attacker who can substitute public keys in transit can sit in the +//! middle, so a protocol must authenticate them, for example by signing them. +//! +//! # Memory Usage +//! +//! There are no lookup tables and no heap allocation, and no state is held between calls other +//! than the keys: +//! +//! | Key Object | PK size on disk | PK size in memory | SK size on disk | SK size in memory | +//! |------------|-----------------|-------------------|-----------------|-------------------| +//! | X25519 | 32 | 32 | 32 | 64 | +//! +//! All values are in bytes. The "in memory" sizes are measured by rust's `std::mem::size_of`. +//! [`X25519PrivateKey`] holds its public key alongside the 32-byte scalar. +//! +//! Per-call stack usage, measured as the deepest frame chain below each entry point of +//! `mem_usage_benches`' x25519 harness in the release build (x86-64 Linux, rustc 1.97.0-nightly, +//! return addresses included), on the key agreement roles with the field element's wipe: +//! +//! | Entry point | Stack | +//! |---------------------------------|--------| +//! | `keygen_from_seed` | 1784 B | +//! | `X25519PrivateKey::from_bytes` | 1704 B | +//! | `agree` on the private key | 1816 B | +//! | `encaps` on the public key | 2792 B | +//! | `decaps` on the private key | 2264 B | +//! +//! Key generation, decoding a private key, and key agreement each run one Montgomery ladder plus +//! the field inversion: the chain is the in-place scalar multiplication, the ladder and a field +//! multiplication. +//! The KEM figures additionally run HPKE.DHKEM, and their chain runs through HKDF-SHA256's HMAC +//! and SHA-256 compression. The `encaps` figure includes the DRBG that draws the ephemeral key. +//! +//! # 🚨 Security Considerations 🚨 +//! +//! **A raw shared secret is not a key**. The agreement over `()` returns `K` as a +//! [`KeyMaterial`] typed [`KeyType::SharedSecret`]: the 32-byte encoding of the u-coordinate +//! of a point on curve25519, which is not uniformly random. That type is accepted by the KDFs +//! and by nothing that takes a key, so it cannot be used as one by mistake; the HKDF-SHA256 +//! pairing and the DHKEM are the two derivations this crate offers over it. +//! +//! RFC 7748 Section 7: "for each public key, there are several publicly computable public keys +//! that are equivalent to it, i.e., they produce the same shared secrets. Thus using a public +//! key as an identifier and knowledge of a shared secret as proof of ownership (without +//! including the public keys in the key derivation) might lead to subtle vulnerabilities". +//! That is the reason for putting both public keys into the KDF's info, as the example above +//! does and as the DHKEM does by construction. +//! +//! An all-zero `K`, the output for a peer key of small order, is refused as +//! [`KeyAgreementError::AgreementFailed`]: RFC 7748 Section 6.1 makes the check optional +//! ("MAY check ... whether K is the all-zero value and abort if so") and this crate always +//! performs it, in constant time, so the only thing it reveals about `K` is whether it is +//! zero. Such a point "will eliminate any contribution from the other party's private key" +//! (Section 7), so `K` would be the same for every private key and known to whoever chose the +//! peer key. +//! +//! **What is wiped, and what is not.** `K`, the decoded scalar, the ladder's and the +//! inversion's field elements and the DHKEM's intermediates each live in a `Secret` or a +//! self-wiping field element and are cleared at the end of their lifetime; `agree_out` writes +//! into the caller's buffer, and [`keygen_out`] and [`keygen_from_seed_out`] draw the scalar +//! straight into a key the caller holds. A value returned by value is moved, and a move does +//! not wipe its source: that holds for the key pairs of [`keygen`], [`keygen_from_seed`], the +//! trait's `from_bytes` and `DeriveKeyPair`, for the clamped scalar `encode` returns, and for +//! the results of `core`'s by-value `agree`, `encaps` and `decaps`. Use the `_out` forms into a +//! buffer or key you own where that matters. What HKDF's own frames keep is in +//! `bouncycastle_hpke`'s Security Considerations. +//! +//! The pairing's derived key carries the least of X25519's 128 bits, the KDF's and the length's +//! strength, so a `LEN` below 16 bytes is typed `CryptographicRandom` at less than 128 bits. +//! +//! On a 32-bit target every `i128` product of the field arithmetic is a call into the compiler's +//! runtime (`__multi3`), so constant time there rests on that routine, not on this crate. +//! +//! RFC 9180 Section 9.7.4: "HPKE ciphertexts are not forward secret with respect to recipient +//! compromise in any mode". Anyone who later obtains a long-term DHKEM private key can decrypt +//! everything ever sent to it. This equally applies to most uses of the raw agreement unless a +//! suitable protocol is layered on top. + +use bouncycastle_core::agreement_key::{AgreementKey, KeyAgreementAlgorithm}; +use bouncycastle_core::errors::{KEMError, KeyAgreementError, KeyMaterialError, RNGError}; +use bouncycastle_core::hazmat::do_hazardous_operations; +use bouncycastle_core::kdf_params::KdfParams; +use bouncycastle_core::kem_key::{DecapsulatingKey, EncapsulatingKey, KEMAlgorithm}; +use bouncycastle_core::key_material::{KeyMaterial, KeyMaterial256, KeyMaterialTrait, KeyType}; +use bouncycastle_core::security_strength::SecurityStrength; +use bouncycastle_core::traits::{ + Algorithm, KEMDecapsulator, KEMEncapsulator, KEMPrivateKey, KEMPublicKey, KeyAgreement, + KeyAgreementPrivateKey, KeyAgreementPublicKey, RNG, +}; +use bouncycastle_hkdf::HkdfDescription; +use bouncycastle_hpke::dhkem::{DHKEM, DHKEMParams}; +use bouncycastle_sha2::SHA256; +use bouncycastle_utils::ct::{Condition, ct_eq_bytes, ct_eq_zero_bytes}; +use bouncycastle_utils::secret::{Secret, zeroize_in_place}; +use core::fmt::{self, Display, Formatter}; + +use crate::curve25519::FieldElement25519; + +// Only the field arithmetic (`FieldElement25519` in curve25519.rs) is shared with Ed25519. The +// scalar and point types below are X25519's own: an Ed25519 scalar is reduced mod the group order +// and an Ed25519 point is an encoded y-coordinate plus a sign bit (RFC 8032 §5.1.2), so neither +// fits these. + +/*** Constants ***/ + +/// Size in bytes of the encoded representation of a point on curve25519, +/// which are used as public keys. +pub const POINT_LEN: usize = 32; +/// Size in bytes of the encoded representation of a scalar in the curve25519 field, +/// which are used as private keys. +pub const SCALAR_LEN: usize = 32; + +/// String name of the X25519 algorithm. +pub const X25519_NAME: &str = "X25519"; + +/// The base point of curve25519, `U(P) = 9` (Section 4.1 of RFC7748). +const BASE_POINT: X25519PublicKey = { + let mut u = [0_u8; POINT_LEN]; + u[0] = 9; + X25519PublicKey(u) +}; + +/// The coefficient A of curve25519, `v^2 = u^3 + A*u^2 + u` (RFC 7748 §4.1). +const C_A: u32 = 486662; + +/// `(A + 2) / 4 = 121666`, the ladder's doubling constant. +/// +/// Deviation from the RFC: RFC 7748 §5 uses `a24 = (486662 - 2) / 4 = 121665` in +/// `z_2 = E * (AA + a24 * E)`. Since `E = AA - BB`, `AA + a24 * E = BB + (a24 + 1) * E`, so pairing +/// the constant with BB instead needs `a24 + 1 = (A + 2) / 4`. [`scalar_mult_into`] and +/// [`ladder_double`] both use that form. +const C_A24: u32 = (C_A + 2) / 4; + +/// The X25519 key agreement algorithm of RFC 7748 §5. +pub struct X25519; + +impl Algorithm for X25519 { + const ALG_NAME: &'static str = X25519_NAME; + // RFC 7748 §7: "the security level ... of curve25519 is slightly under the standard 128-bit + // level", which it argues is acceptable; it is classed here at the conventional 128 bits. + const MAX_SECURITY_STRENGTH: SecurityStrength = SecurityStrength::_128bit; +} + +impl KeyAgreementAlgorithm for X25519 {} + +/// Generates a key pair from `rng`, which must offer X25519's 128 bits: the 32 bytes it draws +/// are the private key (RFC 7748 Section 6.1: "Alice generates 32 random bytes in a\[0\] to +/// a\[31\]"). +/// +/// [`keygen_out`] into a key you hold, moved out of this frame; a move wipes nothing (the +/// module's Security Considerations). +/// +/// # Errors +/// [`KeyAgreementError::RNGError`] if the RNG is weaker than the algorithm or fails to deliver. +pub fn keygen(rng: &mut dyn RNG) -> Result<(X25519PublicKey, X25519PrivateKey), KeyAgreementError> { + let mut sk = X25519PrivateKey::zeroized(); + let pk = keygen_out(rng, &mut sk)?; + Ok((pk, sk)) +} + +/// Generates a private key into `sk`, a key you hold, and returns its public key: the RNG, +/// which must offer X25519's 128 bits, writes the 32 bytes of the scalar straight into the +/// key's own `Secret` (RFC 7748 Section 6.1), so no copy of it is staged on the way. `sk` is +/// zeroized first and left so on every error. +/// +/// # Errors +/// [`KeyAgreementError::RNGError`] if the RNG is weaker than the algorithm or fails to deliver. +pub fn keygen_out( + rng: &mut dyn RNG, + sk: &mut X25519PrivateKey, +) -> Result { + sk.clear(); + if rng.security_strength() < X25519::MAX_SECURITY_STRENGTH { + return Err(RNGError::SecurityStrengthInsufficientForAlgorithm.into()); + } + if let Err(e) = rng.next_bytes_out(&mut *sk.k) { + sk.clear(); + return Err(e.into()); + } + sk.pk = scalar_mult_base(&sk.k); + Ok(sk.pk) +} + +/// The key pair whose private key is `seed`'s 32 bytes: a [`KeyMaterial256`] typed +/// [`KeyType::Seed`] or [`KeyType::CryptographicRandom`], at [`SecurityStrength::_128bit`] or +/// more. The bytes are kept as given; the clamping of RFC 7748 Section 5 is applied when they +/// are used, and the encoding is the clamped form. +/// +/// [`keygen_from_seed_out`] into a key you hold, moved out of this frame; a move wipes nothing +/// (the module's Security Considerations). +/// +/// # Errors +/// [`KeyAgreementError::KeyMaterialError`] for a seed of another type or length, or of too +/// little strength. +pub fn keygen_from_seed( + seed: &KeyMaterial256, +) -> Result<(X25519PublicKey, X25519PrivateKey), KeyAgreementError> { + let mut sk = X25519PrivateKey::zeroized(); + let pk = keygen_from_seed_out(seed, &mut sk)?; + Ok((pk, sk)) +} + +/// The private key whose scalar is `seed`'s 32 bytes, into `sk`, a key you hold, and its public +/// key returned: the seed's requirements are [`keygen_from_seed`]'s, and the bytes are copied +/// once, into the key's own `Secret`. `sk` is zeroized first and left so on every error. +/// +/// # Errors +/// [`KeyAgreementError::KeyMaterialError`] for a seed of another type or length, or of too +/// little strength. +pub fn keygen_from_seed_out( + seed: &KeyMaterial256, + sk: &mut X25519PrivateKey, +) -> Result { + sk.clear(); + if seed.key_type() == KeyType::Zeroized { + return Err(KeyMaterialError::ActingOnZeroizedKey.into()); + } + if !(seed.key_type() == KeyType::Seed || seed.key_type() == KeyType::CryptographicRandom) + || seed.key_len() != SCALAR_LEN + { + return Err(KeyMaterialError::InvalidKeyType( + "an X25519 seed is 32 bytes of KeyType::Seed or KeyType::CryptographicRandom", + ) + .into()); + } + if seed.security_strength() < X25519::MAX_SECURITY_STRENGTH { + return Err(KeyMaterialError::SecurityStrength( + "an X25519 seed must carry at least 128 bits of strength", + ) + .into()); + } + + sk.k.copy_from_slice(seed.ref_to_bytes()); + sk.pk = scalar_mult_base(&sk.k); + Ok(sk.pk) +} + +/// `K = X25519(k, u)` of RFC 7748 Section 6.1 into `out`, the u-coordinate of the peer's public +/// key multiplied by our scalar as its 32-byte little-endian encoding, refused when all zero +/// (and `out` left zeroized then). +/// +/// Any 32 bytes are accepted as `pk`: per Section 5, bit 255 is ignored and values `>= p` are +/// processed as if reduced mod p. An all-zero output means `pk` has small order; the check is +/// constant time, ORing the bytes together as Section 6.1 suggests, so the only information it +/// reveals about `K` is whether it is zero. +fn raw_shared_secret( + sk: &X25519PrivateKey, + pk: &X25519PublicKey, + out: &mut Secret<[u8; POINT_LEN]>, +) -> Result<(), KeyAgreementError> { + scalar_mult_into(&sk.k, pk, out); + if ct_eq_zero_bytes(&**out) { + zeroize_in_place(&mut **out); + return Err(KeyAgreementError::AgreementFailed); + } + Ok(()) +} + +/// The worker an [`X25519PrivateKey`] hands out through [`AgreementKey`] over `()`: the raw +/// `K`, typed [`KeyType::SharedSecret`] at 128 bits. It holds only the key and is reusable. +pub struct X25519Agreement<'k> { + sk: &'k X25519PrivateKey, +} + +impl Algorithm for X25519Agreement<'_> { + const ALG_NAME: &'static str = X25519::ALG_NAME; + const MAX_SECURITY_STRENGTH: SecurityStrength = X25519::MAX_SECURITY_STRENGTH; +} + +impl KeyAgreement for X25519Agreement<'_> { + /// `K` into the caller's buffer, zeroized first and left so on the error path. + fn agree_out( + &self, + peer_pk: &X25519PublicKey, + ss: &mut KeyMaterial, + ) -> Result { + ss.zeroize(); + // `K` is computed into this frame's one Secret, which is wiped when it drops; the field + // elements of the ladder and the inversion below it wipe themselves the same way. + let mut k = Secret::<[u8; POINT_LEN]>::new(); + raw_shared_secret(self.sk, peer_pk, &mut k)?; + // `K` is never all zero here, so the buffer's own zero test cannot type it `Zeroized`. + // A SharedSecret's strength is its producer's to state: X25519's 128 bits. + if let Err(e) = ss.set_bytes_as_type(&*k, KeyType::SharedSecret).and_then(|()| { + do_hazardous_operations(ss, |ss| { + ss.set_security_strength(X25519::MAX_SECURITY_STRENGTH) + }) + }) { + ss.zeroize(); + return Err(e.into()); + } + Ok(POINT_LEN) + } +} + +impl AgreementKey<(), POINT_LEN> for X25519PrivateKey { + type Algorithm = X25519; + type PublicKey = X25519PublicKey; + type Agreement<'k> = X25519Agreement<'k>; + + fn create_agreement<'k>( + &'k self, + _params: (), + ) -> Result, KeyAgreementError> { + if !self.is_filled() { + return Err(KeyMaterialError::ActingOnZeroizedKey.into()); + } + Ok(X25519Agreement { sk: self }) + } +} + +/*** The same keys under HKDF-SHA256: the pairing, and the role impl over it ***/ + +/// X25519 with its shared secret put through HKDF-SHA256, the KDF of RFC 7748 Section 6.1's +/// recommendation ("a key-derivation function that includes K, K_A, and K_B"): the caller's +/// [`KdfParams`] name the HKDF description (its salt, if any) and the fixed info, which should +/// carry both public keys. The derived key is typed by the KDF's accounting, +/// `CryptographicRandom` at the least of X25519's 128 bits, the KDF's and the length's. +#[allow(non_camel_case_types)] +pub struct X25519_HKDF_SHA256; + +impl Algorithm for X25519_HKDF_SHA256 { + const ALG_NAME: &'static str = "X25519-HKDF-SHA256"; + const MAX_SECURITY_STRENGTH: SecurityStrength = X25519::MAX_SECURITY_STRENGTH; +} + +impl KeyAgreementAlgorithm for X25519_HKDF_SHA256 {} + +/// The most HKDF-SHA256 can derive in one call (RFC 5869 Section 2.3: L <= 255 * HashLen), +/// which bounds the role's `LEN`. +pub const HKDF_SHA256_MAX_LEN: usize = 255 * 32; + +/// The worker an [`X25519PrivateKey`] hands out through [`AgreementKey`] over +/// [`KdfParams`] of HKDF-SHA256: `K` from the primitive, then the KDF, built from the +/// description for this derivation, into the caller's buffer. `K` lives in one local of this +/// frame, wiped when it drops; HKDF's own frame below +/// it keeps its copies of `K` and of the PRK's HMAC states, which are that crate's (see the +/// crate docs' Security Considerations). +pub struct X25519KdfAgreement<'k, 'p, 's, const LEN: usize> { + sk: &'k X25519PrivateKey, + params: KdfParams<'p, HkdfDescription<'s, SHA256>, LEN>, +} + +impl Algorithm for X25519KdfAgreement<'_, '_, '_, LEN> { + const ALG_NAME: &'static str = X25519_HKDF_SHA256::ALG_NAME; + const MAX_SECURITY_STRENGTH: SecurityStrength = X25519_HKDF_SHA256::MAX_SECURITY_STRENGTH; +} + +impl KeyAgreement for X25519KdfAgreement<'_, '_, '_, LEN> { + fn agree_out( + &self, + peer_pk: &X25519PublicKey, + ss: &mut KeyMaterial, + ) -> Result { + const { + assert!( + LEN > 0 && LEN <= HKDF_SHA256_MAX_LEN, + "the derived key is from one byte to 255 * 32 bytes long" + ) + }; + ss.zeroize(); + let mut k = KeyMaterial::::new(); + X25519Agreement { sk: self.sk }.agree_out(peer_pk, &mut k)?; + // The engine is an HKDF keyed with the description's salt, if any, built for this + // derivation; `ss` is zeroized first and left so on every error. + self.params.derive_out(&k, ss)?; + Ok(LEN) + } +} + +impl<'p, 's, const LEN: usize> AgreementKey, LEN>, LEN> + for X25519PrivateKey +{ + type Algorithm = X25519_HKDF_SHA256; + type PublicKey = X25519PublicKey; + type Agreement<'k> = X25519KdfAgreement<'k, 'p, 's, LEN>; + + fn create_agreement<'k>( + &'k self, + params: KdfParams<'p, HkdfDescription<'s, SHA256>, LEN>, + ) -> Result, KeyAgreementError> { + if !self.is_filled() { + return Err(KeyMaterialError::ActingOnZeroizedKey.into()); + } + Ok(X25519KdfAgreement { sk: self, params }) + } +} + +/// An X25519 private key: a 32-byte scalar, as defined in Section 5 of RFC7748. +/// +/// Any 32 bytes are a valid scalar. The fixed bits `decodeScalar25519` sets and clears +/// ("clamping") are applied each time the scalar is used, so keys that differ only in those bits +/// are the same key, and compare equal. Held in a [`Secret`], so it is zeroized on drop and +/// redacted from `Debug`. +/// +/// The public key is computed once, when the private key is created or decoded, and stored with +/// it. +#[derive(Clone)] +pub struct X25519PrivateKey { + k: Secret<[u8; SCALAR_LEN]>, + pk: X25519PublicKey, +} + +impl X25519PrivateKey { + /// The all-zero key: the key [`keygen_out`] and [`keygen_from_seed_out`] write into, so + /// that the scalar is drawn where it will live and never moved. It is not a generated key: + /// its public key is all zero until one of them fills it, and until then it makes no + /// agreement and no decapsulator ([`KeyMaterialError::ActingOnZeroizedKey`]). + pub fn zeroized() -> Self { + Self { k: Secret::new(), pk: X25519PublicKey([0; POINT_LEN]) } + } + + /// Whether the key has been generated or decoded. The stored public key says so: it is + /// `X25519(k, 9)`, which is never zero for a clamped `k` (a multiple of 8 in `[2^254, + /// 2^255)`, so not a multiple of the base point's odd prime order), and all zero only in the + /// state [`zeroized`](Self::zeroized) makes and the `_out` generators leave on an error. + fn is_filled(&self) -> bool { + self.pk.0 != [0u8; POINT_LEN] + } + + /// Back to the all-zero key, the scalar wiped. + fn clear(&mut self) { + self.k.zeroize(); + self.pk = X25519PublicKey([0; POINT_LEN]); + } + + /// The public key, `X25519(k, 9)` (RFC 7748 §6.1). + pub fn pk(&self) -> X25519PublicKey { + self.pk + } + + /// The key bytes, [`clamp`]ed, into `out`. + fn clamped_into(&self, out: &mut [u8; SCALAR_LEN]) { + *out = *self.k; + clamp(out); + } +} + +/// Applies `decodeScalar25519`'s fixed bits to the key bytes `k` (RFC 7748 §5): +/// +/// ```text +/// k_list[0] &= 248 +/// k_list[31] &= 127 +/// k_list[31] |= 64 +/// ``` +fn clamp(k: &mut [u8; SCALAR_LEN]) { + k[0] &= 248; + k[31] &= 127; + k[31] |= 64; +} + +/// The encoding is the 32 key bytes, clamped (the bit operations of `decodeScalar25519`, RFC 7748 +/// §5), so keys that compare equal have the same encoding. This is also the DHKEM serialization: +/// RFC 9180 §7.1.2 says "The SerializePrivateKey() function MUST clamp its output and the +/// DeserializePrivateKey() function MUST clamp its input". +impl KeyAgreementPrivateKey for X25519PrivateKey { + /// The clamped scalar as a plain array, the trait's contract; prefer `encode_out` into a + /// buffer you own, since the array is moved out unwiped. + fn encode(&self) -> [u8; SCALAR_LEN] { + let mut out = [0u8; SCALAR_LEN]; + self.clamped_into(&mut out); + out + } + + fn encode_out(&self, out: &mut [u8; SCALAR_LEN]) -> usize { + self.clamped_into(out); + SCALAR_LEN + } + + /// Any 32 bytes are a valid private key; they are clamped on the way in. + /// + /// # Errors + /// + /// [`KeyAgreementError::DecodingError`] if `bytes` is not 32 bytes. + fn from_bytes(bytes: &[u8]) -> Result { + let bytes: &[u8; SCALAR_LEN] = bytes.try_into().map_err(|_| { + KeyAgreementError::DecodingError("An X25519 private key must be 32 bytes") + })?; + let mut sk = Self { k: Secret::new(), pk: X25519PublicKey([0; POINT_LEN]) }; + *sk.k = *bytes; + clamp(&mut sk.k); + sk.pk = scalar_mult_base(&sk.k); + Ok(sk) + } +} + +/// Constant-time comparison of the clamped scalars. +impl PartialEq for X25519PrivateKey { + fn eq(&self, other: &Self) -> bool { + let (mut a, mut b) = (Secret::<[u8; SCALAR_LEN]>::new(), Secret::<[u8; SCALAR_LEN]>::new()); + self.clamped_into(&mut a); + other.clamped_into(&mut b); + ct_eq_bytes(&*a, &*b) + } +} + +impl Eq for X25519PrivateKey {} + +/// An X25519 public value: the u-coordinate of a point on curve25519, as 32 little-endian bytes +/// (Section 5 of RFC7748). +/// +/// Any 32 bytes are accepted: Section 5 requires bit 255 to be ignored and values `>= p` to be +/// processed as if reduced mod p. Public data, so it is `Copy` and its `Debug` shows the bytes. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct X25519PublicKey([u8; POINT_LEN]); + +impl X25519PublicKey { + /// The 32 encoded bytes. + pub const fn as_bytes(&self) -> &[u8; POINT_LEN] { + &self.0 + } +} + +/// The encoding is the 32 bytes of the u-coordinate, as is (RFC 7748 §5). +impl KeyAgreementPublicKey for X25519PublicKey { + fn encode(&self) -> [u8; POINT_LEN] { + self.0 + } + + fn encode_out(&self, out: &mut [u8; POINT_LEN]) -> usize { + out.fill(0); + *out = self.0; + POINT_LEN + } + + /// Any 32 bytes are accepted: RFC 7748 §5 requires bit 255 to be ignored and values `>= p` to + /// be processed as if reduced mod p. + /// + /// # Errors + /// + /// [`KeyAgreementError::DecodingError`] if `bytes` is not 32 bytes. + fn from_bytes(bytes: &[u8]) -> Result { + let bytes: &[u8; POINT_LEN] = bytes.try_into().map_err(|_| { + KeyAgreementError::DecodingError("An X25519 public key must be 32 bytes") + })?; + Ok(Self(*bytes)) + } +} + +impl AsRef<[u8]> for X25519PublicKey { + fn as_ref(&self) -> &[u8] { + &self.0 + } +} + +/// The 32 bytes in hex. +impl Display for X25519PublicKey { + fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { + write!(f, "X25519PublicKey {{ ")?; + for b in &self.0 { + write!(f, "{b:02x}")?; + } + write!(f, " }}") + } +} + +/// `decodeScalar25519(k)` as defined in Section 5 of RFC7748: +/// +/// ```text +/// def decodeScalar25519(k): +/// k_list = [ord(b) for b in k] +/// k_list[0] &= 248 +/// k_list[31] &= 127 +/// k_list[31] |= 64 +/// return decodeLittleEndian(k_list, 255) +/// ``` +/// +/// Section 5 gives the same rule in prose: "set the three least significant bits of the first +/// byte and the most significant bit of the last to zero, set the second most significant bit of +/// the last byte to 1 and, finally, decode as little-endian. This means that the resulting +/// integer is of the form 2^254 plus eight times a value between 0 and 2^251 - 1 (inclusive)." +/// +/// That is why the ladder can start at bit 253 against a pre-swapped initial state; +/// the `8 *` is why its last three iterations collapse into three [`ladder_double`] calls with no +/// trailing conditional swap. +/// +/// Deviation from the RFC: the RFC masks bytes and then decodes, whereas this decodes into +/// four-byte words first and masks the equivalent word positions. `k_list[0] &= 248` becomes +/// `n[0] &= 0xFFFFFFF8` -- the same low three bits, since `n[0]` is the first four bytes -- and +/// `k_list[31] &= 127` / `|= 64` become `n[7] &= 0x7FFFFFFF` / `|= 0x40000000`, the same top two +/// bits, since `n[7]` is the last four bytes. +/// +/// This differs from `decodeScalar448`, which clears two low bits rather than +/// three, and sets bit 447 (Section 5). +/// +/// Input: A 32-byte little-endian scalar. +/// Output: The decoded scalar, written to `n` as eight little-endian 32-bit words. +fn decode_scalar_25519(k: &[u8; SCALAR_LEN], n: &mut [u32; 8]) { + let (words, _) = k.as_chunks::<4>(); // 32 bytes: exactly 8 chunks, no remainder + for (n_i, w) in n.iter_mut().zip(words) { + *n_i = u32::from_le_bytes(*w); + } + + n[0] &= 0xFFFFFFF8_u32; + n[7] &= 0x7FFFFFFF_u32; + n[7] |= 0x40000000_u32; +} + +/// `decodeUCoordinate(u, 255)` as defined in Section 5 of RFC7748: +/// +/// ```text +/// def decodeUCoordinate(u, bits): +/// u_list = [ord(b) for b in u] +/// # Ignore any unused bits. +/// if bits % 8: +/// u_list[-1] &= (1<<(bits%8))-1 +/// return decodeLittleEndian(u_list, bits) +/// ``` +/// +/// With `bits` = 255, `bits % 8` is 7 and the mask clears bit 255, the most significant bit of +/// the final byte. Section 5 requires exactly that: "When receiving such an array, +/// implementations of X25519 (but not X448) MUST mask the most significant bit in the final +/// byte." [`FieldElement25519::decode_255`] does the masking and the little-endian decode. +/// +/// The result is not normalized, as Section 5 also requires: "Implementations MUST accept +/// non-canonical values and process them as if they had been reduced modulo the field prime. The +/// non-canonical values are 2^255 - 19 through 2^255 - 1 for X25519". +/// +/// Input: A 32-byte little-endian u-coordinate. +/// Output: The u-coordinate as a [`FieldElement25519`], not normalized. +fn decode_u_coordinate(u: &X25519PublicKey) -> FieldElement25519 { + FieldElement25519::decode_255(&u.0) +} + +/// `encodeUCoordinate(u, 255)` as defined in Section 5 of RFC 7748. +/// The RFC's `u = u % p` step is [`FieldElement25519::normalize`]: an X25519 output must be the +/// canonical encoding of its residue class, even though non-canonical values MUST be accepted on +/// the way in (see [`decode_u_coordinate`]). Bit 255 of the final byte is written as zero, since +/// it is unused by X25519. +/// +/// Input: A u-coordinate, in any state of reduction; a 32-byte output buffer. +/// Output: The canonical 32-byte little-endian encoding of that value, written to `r`. +fn encode_u_coordinate(u: &FieldElement25519, r: &mut [u8; POINT_LEN]) { + u.normalize().encode_255(r); +} + +/// Doubles one point, held projectively as the pair `(x : z)` representing `u = x / z` +/// Updated in place. +/// +/// Keeping u as a fraction is what lets the ladder avoid a field inversion on every step: only +/// multiplications and squarings are needed here, and [`scalar_mult_into`] divides `x` by `z` +/// once, at the end. +/// +/// This is the doubling half of the Montgomery ladder step in Section 5 of RFC7748, used by +/// [`scalar_mult_into`] for the last three iterations. With `AA = (x + z)^2`, `BB = (x - z)^2` +/// and `E = AA - BB`, it writes `x = AA * BB` and `z = E * (BB + C_A24 * E)`; see [`C_A24`] for +/// the pairing with `BB`. +/// +/// X25519 only: it works on curve25519's Montgomery form and depends on its coefficient A. +/// Ed25519 doubles points on the twisted Edwards curve in extended coordinates (Section 5.1.4 of +/// RFC8032), which is a separate function. +fn ladder_double(x: &mut FieldElement25519, z: &mut FieldElement25519) { + let (mut a, mut b) = x.sum_and_difference(z); + a = a.sqr(); + b = b.sqr(); + *x = a.mul(&b); + + a = a.sub(&b); + let t = a.mul_u32(C_A24).add(&b); + *z = t.mul(&a); +} + +/// `X25519(k, u)` as defined in Section 5 of RFC7748: the Montgomery ladder, computing scalar +/// multiplication on curve25519 from a u-coordinate alone. +/// +/// The ladder is constant time with respect to `k`: the iteration count is fixed and the only +/// scalar-dependent step is [`FieldElement25519::cswap`]. +/// +/// # Modifications from the RFC +/// Modified to fold the RFC's first ladder iteration into the initial state, to replace its last +/// three iterations with [`ladder_double`] calls, and to cycle the RFC's named intermediates +/// through a fixed set of registers rather than materialise them. +/// +/// # Inputs +/// * `k`, a 32-byte scalar +/// * `u`, a 32-byte little-endian u-coordinate +/// +/// Output: The canonical little-endian encoding of the u-coordinate of `k * u`. +fn scalar_mult_into(k: &[u8; SCALAR_LEN], u: &X25519PublicKey, out: &mut [u8; POINT_LEN]) { + // The decoded scalar is as secret as `k` itself. + let mut n: Secret<[u32; 8]> = Secret::new(); + decode_scalar_25519(k, &mut n); + + // Pre-condition: + // The ladder below is only correct for scalars of the form 2^254 + 8m, 0 <= m <= 2^251 - 1 + // which should be enforced by a correct implementation of decode_scalar_25519. + debug_assert_eq!(1, n[7] >> 30); + debug_assert_eq!(0, n[0] & 7); + + let x1 = decode_u_coordinate(u); + let mut x2 = FieldElement25519::zero(); + let mut z2 = FieldElement25519::zero(); + ladder(&n, &x1, &mut x2, &mut z2); + + // Every field element here wipes itself when it drops: the result, the ladder's registers + // and the inversion chain's. The encoding goes straight into the caller's buffer. + let r = x2.mul(&z2.inv()); + encode_u_coordinate(&r, out); +} + +/// The Montgomery ladder of [`scalar_mult_into`]: writes the projective u-coordinate of `n * x1` +/// to `(x2, z2)`, for a scalar `n` decoded by [`decode_scalar_25519`]. +// #[inline(never)]: so that the ladder's variables live in a different stack frame and can be popped +// before scalar_mult's `z2.inv()` runs (which is the other stack-expensive operation). +#[inline(never)] +fn ladder( + n: &[u32; 8], + x1: &FieldElement25519, + x2: &mut FieldElement25519, + z2: &mut FieldElement25519, +) { + *x2 = x1.clone(); + *z2 = FieldElement25519::one(); + let mut x3 = FieldElement25519::one(); + let mut z3 = FieldElement25519::zero(); + + let mut t1; + let mut t2; + + let mut swap = Condition::::from_bool_const::(); + + // Deviation from the RFC: + // RFC7748 §5 runs `For t = bits-1 down to 0`, i.e. t = 254 down to 0, with the conditional + // swap at the top of the body and the arithmetic after it. This loop deviates in three ways, + // all of them consequences of the scalar's form -- see the pre-condition above: + // + // 1. Rotated body. The arithmetic comes first here and the swap last. + // 2. t = 254 is not in the loop because bit 254 is always set, so that iteration's swap is known in + // advance: the RFC starts from x_2 = 1, z_2 = 0, x_3 = u, z_3 = 1 and its first swap + // exchanges the pairs, so the registers above are seeded with the swapped values, + // x_2 = u, z_2 = 1, x_3 = 1, z_3 = 0, and `swap` starts at k_254. So the loop starts at + // 253 and not 254. + // 3. t = 2, 1, 0 are not in the loop because bits 0..2 are always clear, so those iterations reduce + // to doubling the (x_2, z_2) branch and their swaps are no-ops. They become the three + // ladder_double calls after the loop, and the RFC's post-loop cswap is dropped for the same + // reason -- the debug_assert below is what checks it would have been a no-op. + for bit in (2..=253_usize).rev() { + // This section is the same core algorithm as in RFC7748 §5, but uses a different variable + // naming convention in order to more efficiently reuse memory. + // Comment style: + // , -> + + // C = x_3 + z_3, -> t1 + // D = x_3 - z_3, -> x3 + (t1, x3) = x3.sum_and_difference(&z3); + // A = x_2 + z_2, -> z3 + // B = x_2 - z_2, -> x2 + // Must follow the line above, not precede it: that one still reads the incoming z_3, + // which this one overwrites. + (z3, *x2) = x2.sum_and_difference(z2); + // CB = C * B, -> t1 + t1 = t1.mul(x2); + // DA = D * A, -> x3 + x3 = x3.mul(&z3); + // AA = A^2, -> z3 + z3 = z3.sqr(); + // BB = B^2, -> x2 + *x2 = x2.sqr(); + + // E = AA - BB, -> t2 + t2 = z3.sub(x2); + // z_2 = E * (AA + a24 * E), -> z2 + // Deviation from the RFC: written as E * (BB + C_A24 * E), an equivalent pairing of the + // constant with the other operand. See C_A24's declaration. + // The incoming z_2 died on the `sum_and_difference` above, which is what frees this slot. + *z2 = t2.mul_u32(C_A24).add(x2).mul(&t2); + // x_2 = AA * BB, -> x2 + *x2 = x2.mul(&z3); + + // x_3 = (DA + CB)^2, -> x3 + // z_3 = x_1 * (DA - CB)^2, -> z3 + // The function `sum_and_difference()` computes `(DA + CB) and (DA - CB)` is a single + // operation, allowing these lines to be combined. + // Deviation from the RFC: yields CB - DA, negated. Harmless as both lines below square it. + (x3, z3) = t1.sum_and_difference(&x3); + // (completes x_3) + x3 = x3.sqr(); + // (completes z_3) + z3 = z3.sqr().mul(x1); + + // This differs from the ladder presentation in the RFC because it implements the + // constant-time cswap recommendation at the bottom of §5 using an all-ones/all-zeros + // mask and the Condition type. + + // k_t = (k >> t) & 1 + // > Presentation differs due to decoding k into n, and the bit-selecting Condition operator. + let k_bit = Condition::::is_bit_set(n[bit >> 5] as i64, (bit & 0x1F) as u32); + // swap ^= k_t + swap ^= k_bit; + // (x_2, x_3) = cswap(swap, x_2, x_3) + // > swaps in-place + FieldElement25519::cswap(swap, x2, &mut x3); + // (z_2, z_3) = cswap(swap, z_2, z_3) + // > swaps in-place + FieldElement25519::cswap(swap, z2, &mut z3); + // swap = k_t + swap = k_bit; + } + + debug_assert!(!swap.to_bool()); + + for _ in 0..3 { + ladder_double(x2, z2); + } +} + +fn scalar_mult_base(k: &[u8; SCALAR_LEN]) -> X25519PublicKey { + // The result is public, so it may live in the plain array of the key type. A fixed-base + // table would make this faster; the variable-base ladder serves for now. + let mut out = [0u8; POINT_LEN]; + scalar_mult_into(k, &BASE_POINT, &mut out); + X25519PublicKey(out) +} + +/*** DHKEM ***/ + +// This section provides the machinery to promote x25519 to a KEM via RFC9180's DHKEM construction. + +/// The length of the shared secret from [`X25519`]'s KEM: Nsecret for DHKEM(X25519, HKDF-SHA256) +/// (RFC 9180 §7.1). +pub const DHKEM_SS_LEN: usize = 32; + +/// DHKEM(X25519, HKDF-SHA256) of RFC 9180 §4.1. Nenc = Npk = Ndh = 32 and Nsk = 32 (§7.1). +type X25519DHKEM = DHKEM; + +/// DHKEM(X25519, HKDF-SHA256): kem_id 0x0020, with Nenc = Npk = Nsk = 32 (RFC 9180 §7.1). +impl DHKEMParams for X25519 { + type PublicKey = X25519PublicKey; + type PrivateKey = X25519PrivateKey; + type KDFHash = SHA256; + const KEM_ID: u16 = 0x0020; + + fn with_generated_key_pair( + rng: &mut dyn RNG, + f: impl FnOnce(&X25519PublicKey, &X25519PrivateKey) -> R, + ) -> Result { + // For X25519, 32 random bytes are a private key (RFC 7748 §6.1). The key is generated + // in this frame and dropped here, so its scalar is wiped where it was drawn. + let mut sk = X25519PrivateKey::zeroized(); + // keygen_out fails only through the RNG. + let pk = keygen_out(rng, &mut sk).map_err(|e| match e { + KeyAgreementError::RNGError(e) => KEMError::RNGError(e), + _ => KEMError::GenericError("X25519 key generation failed"), + })?; + Ok(f(&pk, &sk)) + } + + const DERIVE_KEY_PAIR_BY_EXPAND: bool = true; + + fn private_key_from_bytes(sk: &[u8; SCALAR_LEN]) -> X25519PrivateKey { + let mut key = X25519PrivateKey { k: Secret::new(), pk: X25519PublicKey([0; POINT_LEN]) }; + *key.k = *sk; + key.pk = scalar_mult_base(&key.k); + key + } + + fn pk(sk: &X25519PrivateKey) -> X25519PublicKey { + sk.pk() + } + + fn dh_into( + sk: &X25519PrivateKey, + pk: &X25519PublicKey, + out: &mut Secret<[u8; POINT_LEN]>, + ) -> Result<(), KeyAgreementError> { + raw_shared_secret(sk, pk, out) + } + + // RFC 9180 §7.1.1: "For X25519 and X448, the SerializePublicKey() and DeserializePublicKey() + // functions are the identity function". + fn serialize_public_key(pk: &X25519PublicKey) -> [u8; POINT_LEN] { + pk.0 + } + + fn deserialize_public_key(pkm: &[u8; POINT_LEN]) -> Result { + Ok(X25519PublicKey(*pkm)) + } +} + +/// DHKEM(X25519, HKDF-SHA256) of RFC 9180 §4.1 (`kem_id` 0x0020, §7.1): the KEM the X25519 keys +/// carry through [`EncapsulatingKey`] and [`DecapsulatingKey`], as distinct from the X25519 +/// function itself, [`X25519`]. +#[allow(non_camel_case_types)] +pub struct DHKEM_X25519_HKDF_SHA256; + +impl Algorithm for DHKEM_X25519_HKDF_SHA256 { + const ALG_NAME: &'static str = "DHKEM(X25519, HKDF-SHA256)"; + const MAX_SECURITY_STRENGTH: SecurityStrength = X25519::MAX_SECURITY_STRENGTH; +} + +impl KEMAlgorithm for DHKEM_X25519_HKDF_SHA256 {} + +/// The encapsulator an [`X25519PublicKey`] hands out through [`EncapsulatingKey`]: +/// DHKEM(X25519, HKDF-SHA256) of RFC 9180 §4.1, where the ciphertext is an ephemeral public key +/// (`enc`) and the shared secret is derived with HKDF-SHA256 from the X25519 output and both +/// public keys. It borrows the recipient's key. +pub struct X25519Encapsulator<'k> { + pk: &'k X25519PublicKey, +} + +impl Algorithm for X25519Encapsulator<'_> { + const ALG_NAME: &'static str = DHKEM_X25519_HKDF_SHA256::ALG_NAME; + const MAX_SECURITY_STRENGTH: SecurityStrength = DHKEM_X25519_HKDF_SHA256::MAX_SECURITY_STRENGTH; +} + +impl KEMEncapsulator for X25519Encapsulator<'_> { + /// `Encap(pkR)` (RFC 9180 §4.1), drawing the ephemeral key pair from `rng`. + /// + /// # Errors + /// + /// * [`KEMError::RNGError`] if `rng`'s security strength is below 128 bits. + /// * [`KEMError::InvalidPublicKey`] if the key gives an all-zero X25519 output, the case the + /// agreement role refuses as [`KeyAgreementError::AgreementFailed`]. + fn encaps_out( + &self, + rng: &mut dyn RNG, + ct: &mut [u8; POINT_LEN], + ss: &mut KeyMaterial, + ) -> Result { + ct.fill(0); + ss.zeroize(); + X25519DHKEM::encap_rng_out(self.pk, rng, ct, ss)?; + Ok(POINT_LEN) + } +} + +/// X25519 public keys encapsulate as DHKEM(X25519, HKDF-SHA256), with `()` as the parameters. +impl EncapsulatingKey<(), POINT_LEN, DHKEM_SS_LEN> for X25519PublicKey { + type Algorithm = DHKEM_X25519_HKDF_SHA256; + type Encapsulator<'k> = X25519Encapsulator<'k>; + + fn create_encapsulator<'k>(&'k self, _params: ()) -> Result, KEMError> { + Ok(X25519Encapsulator { pk: self }) + } +} + +/// The decapsulator an [`X25519PrivateKey`] hands out through [`DecapsulatingKey`]: +/// DHKEM(X25519, HKDF-SHA256) `Decap` of RFC 9180 §4.1. It borrows the recipient's key. +pub struct X25519Decapsulator<'k> { + sk: &'k X25519PrivateKey, +} + +impl Algorithm for X25519Decapsulator<'_> { + const ALG_NAME: &'static str = DHKEM_X25519_HKDF_SHA256::ALG_NAME; + const MAX_SECURITY_STRENGTH: SecurityStrength = DHKEM_X25519_HKDF_SHA256::MAX_SECURITY_STRENGTH; +} + +impl KEMDecapsulator for X25519Decapsulator<'_> { + /// `Decap(enc, skR)` (RFC 9180 §4.1), with the ciphertext `ct` as `enc`. + /// + /// # Errors + /// + /// [`KEMError::DecapsulationFailed`] if `ct` gives an all-zero X25519 output. + fn decaps_out( + &self, + ct: &[u8; POINT_LEN], + ss: &mut KeyMaterial, + ) -> Result { + ss.zeroize(); + X25519DHKEM::decap_out(ct, self.sk, ss)?; + Ok(DHKEM_SS_LEN) + } +} + +/// X25519 private keys decapsulate as DHKEM(X25519, HKDF-SHA256), with `()` as the parameters. +impl DecapsulatingKey<(), POINT_LEN, DHKEM_SS_LEN> for X25519PrivateKey { + type Algorithm = DHKEM_X25519_HKDF_SHA256; + type Decapsulator<'k> = X25519Decapsulator<'k>; + + fn create_decapsulator<'k>(&'k self, _params: ()) -> Result, KEMError> { + if !self.is_filled() { + return Err(KeyMaterialError::ActingOnZeroizedKey.into()); + } + Ok(X25519Decapsulator { sk: self }) + } +} + +/// The same clamped encoding as the [`KeyAgreementPrivateKey`] impl, which RFC 9180 §7.1.2 requires +/// of a DHKEM. +impl KEMPrivateKey for X25519PrivateKey { + fn encode(&self) -> [u8; SCALAR_LEN] { + >::encode(self) + } + + fn encode_out(&self, out: &mut [u8; SCALAR_LEN]) -> usize { + >::encode_out(self, out) + } + + /// # Errors + /// + /// [`KEMError::DecodingError`] if `bytes` is not 32 bytes. + fn from_bytes(bytes: &[u8]) -> Result { + >::from_bytes(bytes) + .map_err(|_| KEMError::DecodingError("An X25519 private key must be 32 bytes")) + } +} + +/// The same encoding as the [`KeyAgreementPublicKey`] impl: RFC 9180 §7.1.1 makes serialization the +/// identity function for X25519. +impl KEMPublicKey for X25519PublicKey { + fn encode(&self) -> [u8; POINT_LEN] { + >::encode(self) + } + + fn encode_out(&self, out: &mut [u8; POINT_LEN]) -> usize { + >::encode_out(self, out) + } + + /// # Errors + /// + /// [`KEMError::DecodingError`] if `bytes` is not 32 bytes. + fn from_bytes(bytes: &[u8]) -> Result { + >::from_bytes(bytes) + .map_err(|_| KEMError::DecodingError("An X25519 public key must be 32 bytes")) + } +} diff --git a/crypto/ed/tests/x25519_dhkem_tests.rs b/crypto/ed/tests/x25519_dhkem_tests.rs new file mode 100644 index 00000000..da6f3a38 --- /dev/null +++ b/crypto/ed/tests/x25519_dhkem_tests.rs @@ -0,0 +1,408 @@ +//! X25519 as a KEM: DHKEM(X25519, HKDF-SHA256) of RFC 9180 Section 4.1, against the RFC 9180 +//! Appendix A.1 vectors and the core-test-framework KEM suites. + +use bouncycastle_core::errors::{KEMError, KeyMaterialError, RNGError}; +use bouncycastle_core::kem_key::{DecapsulatingKey, EncapsulatingKey}; +use bouncycastle_core::key_material::{KeyMaterial, KeyMaterial256, KeyMaterialTrait, KeyType}; +use bouncycastle_core::security_strength::SecurityStrength; +use bouncycastle_core::traits::{ + Algorithm, AlgorithmInfo, KEMDecapsulator, KEMEncapsulator, KEMPrivateKey, KEMPublicKey, RNG, +}; +use bouncycastle_core_test_framework::kem::{TestFrameworkKEM, TestFrameworkKEMKeys}; +use bouncycastle_ed::x25519::{ + DHKEM_SS_LEN, DHKEM_X25519_HKDF_SHA256, POINT_LEN, SCALAR_LEN, X25519, X25519PrivateKey, + X25519PublicKey, keygen, keygen_from_seed, +}; +use bouncycastle_hex as hex; +use bouncycastle_hpke::dhkem::DHKEM; +use bouncycastle_rng::{DefaultRNG, FixedSeedRNG, HashDRBG_SHA512}; + +type X25519DHKEM = DHKEM; + +/// The DHKEM values of one RFC 9180 Appendix A.1 vector set. +struct Vector { + ikm_e: &'static str, + pk_em: &'static str, + sk_em: &'static str, + ikm_r: &'static str, + pk_rm: &'static str, + sk_rm: &'static str, + enc: &'static str, + shared_secret: &'static str, +} + +/// RFC 9180 Appendix A.1.1 (Base mode) and A.1.2 (PSK mode). The PSK only enters the HPKE key +/// schedule, so for the KEM these are two independent sets. +const VECTORS: [Vector; 6] = [ + Vector { + ikm_e: "7268600d403fce431561aef583ee1613527cff655c1343f29812e66706df3234", + pk_em: "37fda3567bdbd628e88668c3c8d7e97d1d1253b6d4ea6d44c150f741f1bf4431", + sk_em: "52c4a758a802cd8b936eceea314432798d5baf2d7e9235dc084ab1b9cfa2f736", + ikm_r: "6db9df30aa07dd42ee5e8181afdb977e538f5e1fec8a06223f33f7013e525037", + pk_rm: "3948cfe0ad1ddb695d780e59077195da6c56506b027329794ab02bca80815c4d", + sk_rm: "4612c550263fc8ad58375df3f557aac531d26850903e55a9f23f21d8534e8ac8", + enc: "37fda3567bdbd628e88668c3c8d7e97d1d1253b6d4ea6d44c150f741f1bf4431", + shared_secret: "fe0e18c9f024ce43799ae393c7e8fe8fce9d218875e8227b0187c04e7d2ea1fc", + }, + Vector { + ikm_e: "78628c354e46f3e169bd231be7b2ff1c77aa302460a26dbfa15515684c00130b", + pk_em: "0ad0950d9fb9588e59690b74f1237ecdf1d775cd60be2eca57af5a4b0471c91b", + sk_em: "463426a9ffb42bb17dbe6044b9abd1d4e4d95f9041cef0e99d7824eef2b6f588", + ikm_r: "d4a09d09f575fef425905d2ab396c1449141463f698f8efdb7accfaff8995098", + pk_rm: "9fed7e8c17387560e92cc6462a68049657246a09bfa8ade7aefe589672016366", + sk_rm: "c5eb01eb457fe6c6f57577c5413b931550a162c71a03ac8d196babbd4e5ce0fd", + enc: "0ad0950d9fb9588e59690b74f1237ecdf1d775cd60be2eca57af5a4b0471c91b", + shared_secret: "727699f009ffe3c076315019c69648366b69171439bd7dd0807743bde76986cd", + }, + // A.2.1 (DHKEM(X25519, HKDF-SHA256), HKDF-SHA256, ChaCha20Poly1305, Base): the same KEM. + Vector { + ikm_e: "909a9b35d3dc4713a5e72a4da274b55d3d3821a37e5d099e74a647db583a904b", + pk_em: "1afa08d3dec047a643885163f1180476fa7ddb54c6a8029ea33f95796bf2ac4a", + sk_em: "f4ec9b33b792c372c1d2c2063507b684ef925b8c75a42dbcbf57d63ccd381600", + ikm_r: "1ac01f181fdf9f352797655161c58b75c656a6cc2716dcb66372da835542e1df", + pk_rm: "4310ee97d88cc1f088a5576c77ab0cf5c3ac797f3d95139c6c84b5429c59662a", + sk_rm: "8057991eef8f1f1af18f4a9491d16a1ce333f695d4db8e38da75975c4478e0fb", + enc: "1afa08d3dec047a643885163f1180476fa7ddb54c6a8029ea33f95796bf2ac4a", + shared_secret: "0bbe78490412b4bbea4812666f7916932b828bba79942424abb65244930d69a7", + }, + // A.2.2 (the same, PSK mode: the KEM does not see the PSK). + Vector { + ikm_e: "35706a0b09fb26fb45c39c2f5079c709c7cf98e43afa973f14d88ece7e29c2e3", + pk_em: "2261299c3f40a9afc133b969a97f05e95be2c514e54f3de26cbe5644ac735b04", + sk_em: "0c35fdf49df7aa01cd330049332c40411ebba36e0c718ebc3edf5845795f6321", + ikm_r: "26b923eade72941c8a85b09986cdfa3f1296852261adedc52d58d2930269812b", + pk_rm: "13640af826b722fc04feaa4de2f28fbd5ecc03623b317834e7ff4120dbe73062", + sk_rm: "77d114e0212be51cb1d76fa99dd41cfd4d0166b08caa09074430a6c59ef17879", + enc: "2261299c3f40a9afc133b969a97f05e95be2c514e54f3de26cbe5644ac735b04", + shared_secret: "4be079c5e77779d0215b3f689595d59e3e9b0455d55662d1f3666ec606e50ea7", + }, + // A.7.1 (DHKEM(X25519, HKDF-SHA256), HKDF-SHA256, Export-Only AEAD, Base). + Vector { + ikm_e: "55bc245ee4efda25d38f2d54d5bb6665291b99f8108a8c4b686c2b14893ea5d9", + pk_em: "e5e8f9bfff6c2f29791fc351d2c25ce1299aa5eaca78a757c0b4fb4bcd830918", + sk_em: "095182b502f1f91f63ba584c7c3ec473d617b8b4c2cec3fad5af7fa6748165ed", + ikm_r: "683ae0da1d22181e74ed2e503ebf82840deb1d5e872cade20f4b458d99783e31", + pk_rm: "194141ca6c3c3beb4792cd97ba0ea1faff09d98435012345766ee33aae2d7664", + sk_rm: "33d196c830a12f9ac65d6e565a590d80f04ee9b19c83c87f2c170d972a812848", + enc: "e5e8f9bfff6c2f29791fc351d2c25ce1299aa5eaca78a757c0b4fb4bcd830918", + shared_secret: "e81716ce8f73141d4f25ee9098efc968c91e5b8ce52ffff59d64039e82918b66", + }, + // A.7.2 (the same, PSK mode). + Vector { + ikm_e: "c51211a8799f6b8a0021fcba673d9c4067a98ebc6794232e5b06cb9febcbbdf5", + pk_em: "d3805a97cbcd5f08babd21221d3e6b362a700572d14f9bbeb94ec078d051ae3d", + sk_em: "1d72396121a6a826549776ef1a9d2f3a2907fc6a38902fa4e401afdb0392e627", + ikm_r: "5e0516b1b29c0e13386529da16525210c796f7d647c37eac118023a6aa9eb89a", + pk_rm: "d53af36ea5f58f8868bb4a1333ed4cc47e7a63b0040eb54c77b9c8ec456da824", + sk_rm: "98f304d4ecb312689690b113973c61ffe0aa7c13f2fbe365e48f3ed09e5a6a0c", + enc: "d3805a97cbcd5f08babd21221d3e6b362a700572d14f9bbeb94ec078d051ae3d", + shared_secret: "024573db58c887decb4c57b6ed39f2c9a09c85600a8a0ecb11cac24c6aaec195", + }, +]; + +fn decode_32(s: &str) -> [u8; 32] { + hex::decode(s).unwrap().try_into().unwrap() +} + +fn seed(s: &str) -> KeyMaterial256 { + KeyMaterial256::from_bytes_as_type(&decode_32(s), KeyType::Seed).unwrap() +} + +/// Clamps as `decodeScalar25519` does (RFC 7748 Section 5). +fn clamp(mut k: [u8; 32]) -> [u8; 32] { + k[0] &= 248; + k[31] &= 127; + k[31] |= 64; + k +} + +/// `keygen` with its error mapped, in the shape the KEM test framework takes. +fn keygen_kem() -> Result<(X25519PublicKey, X25519PrivateKey), KEMError> { + keygen(&mut DefaultRNG::default()).map_err(|_| KEMError::KeyGenError("X25519 keygen failed")) +} + +/// `Encap` with the vector's ephemeral key: the RNG emits skEm, which keygen uses as the private +/// key unchanged. +#[test] +fn rfc9180_encaps() { + for (i, v) in VECTORS.iter().enumerate() { + let pk_r = X25519PublicKey::from_bytes(&decode_32(v.pk_rm)).unwrap(); + let mut rng = FixedSeedRNG::new(decode_32(v.sk_em)); + let (ss, enc) = pk_r.encaps(&mut rng, ()).unwrap(); + assert_eq!(enc, decode_32(v.enc), "vector {i}: enc"); + assert_eq!(enc, decode_32(v.pk_em), "vector {i}: enc = pkEm"); + assert_eq!(ss.ref_to_bytes(), decode_32(v.shared_secret), "vector {i}: shared_secret"); + assert_eq!(ss.key_type(), KeyType::CryptographicRandom, "vector {i}"); + assert_eq!(ss.security_strength(), SecurityStrength::_128bit, "vector {i}"); + } +} + +#[test] +fn rfc9180_decaps() { + for (i, v) in VECTORS.iter().enumerate() { + let sk_r = X25519PrivateKey::from_bytes(&decode_32(v.sk_rm)).unwrap(); + assert_eq!(sk_r.pk().as_bytes(), &decode_32(v.pk_rm), "vector {i}: pk(skRm)"); + let ss = sk_r.decaps(&decode_32(v.enc), ()).unwrap(); + assert_eq!(ss.ref_to_bytes(), decode_32(v.shared_secret), "vector {i}: shared_secret"); + assert_eq!(ss.key_type(), KeyType::CryptographicRandom, "vector {i}"); + assert_eq!(ss.security_strength(), SecurityStrength::_128bit, "vector {i}"); + } +} + +/// `DeriveKeyPair` (RFC 9180 Section 7.1.3) maps ikmE and ikmR to the vectors' key pairs. +/// +/// The vectors list skEm and skRm unclamped, while RFC 9180 Section 7.1.2 requires a serialized +/// private key to be clamped, so the encodings are compared against the clamped vector values. +#[test] +fn rfc9180_derive_key_pair() { + for (i, v) in VECTORS.iter().enumerate() { + for (ikm, pkm, skm) in [(v.ikm_e, v.pk_em, v.sk_em), (v.ikm_r, v.pk_rm, v.sk_rm)] { + let (pk, sk) = X25519DHKEM::derive_key_pair(&seed(ikm)).unwrap(); + assert_eq!(pk.encode(), decode_32(pkm), "vector {i}: pk from ikm {ikm}"); + assert_eq!(sk.encode(), clamp(decode_32(skm)), "vector {i}: sk from ikm {ikm}"); + } + } +} + +#[test] +fn derive_key_pair_rejects_bad_ikm() { + let ikm = VECTORS[0].ikm_e; + + let mac_key = KeyMaterial256::from_bytes_as_type(&decode_32(ikm), KeyType::MACKey).unwrap(); + match X25519DHKEM::derive_key_pair(&mac_key) { + Err(KEMError::KeyGenError(_)) => { /* good */ } + _ => panic!("expected KeyGenError for the wrong key type"), + } + + let short = KeyMaterial256::from_bytes_as_type(&decode_32(ikm)[..31], KeyType::Seed).unwrap(); + match X25519DHKEM::derive_key_pair(&short) { + Err(KEMError::KeyGenError(_)) => { /* good */ } + _ => panic!("expected KeyGenError for a 31-byte ikm"), + } + + let mut weak = seed(ikm); + weak.set_security_strength(SecurityStrength::_112bit).unwrap(); + match X25519DHKEM::derive_key_pair(&weak) { + Err(KEMError::KeyGenError(_)) => { /* good */ } + _ => panic!("expected KeyGenError for a 112-bit ikm"), + } + + // Exactly the algorithm's strength is enough. + let mut just_right = seed(ikm); + just_right.set_security_strength(SecurityStrength::_128bit).unwrap(); + X25519DHKEM::derive_key_pair(&just_right).unwrap(); + + // A longer ikm is allowed. + let long = KeyMaterial256::from_bytes_as_type(&[0x5A; 32], KeyType::Seed).unwrap(); + X25519DHKEM::derive_key_pair(&long).unwrap(); +} + +/// `encaps` rejects an RNG below 128 bits and accepts one at exactly 128 bits. +#[test] +fn encaps_rng_security_strength() { + let (pk, _) = keygen(&mut DefaultRNG::default()).unwrap(); + + let mut weak = FixedSeedRNG::new([0x5A; 32]); + weak.set_security_strength(SecurityStrength::_112bit); + match pk.encaps(&mut weak, ()) { + Err(KEMError::RNGError(_)) => { /* good */ } + _ => panic!("expected RNGError for a 112-bit RNG"), + } + + let mut just_right = FixedSeedRNG::new([0x5A; 32]); + just_right.set_security_strength(SecurityStrength::_128bit); + pk.encaps(&mut just_right, ()).unwrap(); +} + +/// An RNG at full strength whose every request fails. +struct FailingRNG; + +impl RNG for FailingRNG { + fn add_seed_keymaterial(&mut self, _: &dyn KeyMaterialTrait) -> Result<(), RNGError> { + Ok(()) + } + fn next_int(&mut self) -> Result { + Err(RNGError::GenericError("failing RNG")) + } + fn next_bytes(&mut self, _: usize) -> Result, RNGError> { + Err(RNGError::GenericError("failing RNG")) + } + fn next_bytes_out(&mut self, _: &mut [u8]) -> Result { + Err(RNGError::GenericError("failing RNG")) + } + fn fill_keymaterial_out(&mut self, _: &mut dyn KeyMaterialTrait) -> Result { + Err(RNGError::GenericError("failing RNG")) + } + fn security_strength(&self) -> SecurityStrength { + SecurityStrength::_256bit + } +} + +/// An RNG failure while generating the ephemeral key pair is passed through as the RNG's error. +#[test] +fn encaps_rng_passes_through_rng_failure() { + let (pk, _) = keygen(&mut DefaultRNG::default()).unwrap(); + match pk.encaps(&mut FailingRNG, ()) { + Err(KEMError::RNGError(RNGError::GenericError(_))) => { /* good */ } + other => panic!("expected the RNG's error, got {other:?}"), + } +} + +#[test] +fn kem_framework() { + // DHKEM is randomized. A modified ciphertext is another public key, so decaps succeeds with a + // different shared secret, which is the behaviour the framework checks for an implicitly + // rejecting KEM. Every bit of enc is flipped: X25519 ignores bit 255 of a u-coordinate, but + // enc is also in kem_context, so flipping any of its 256 bits changes the shared secret. + TestFrameworkKEM::new(false, true) + .test_kem::<(), X25519PublicKey, X25519PrivateKey, POINT_LEN, DHKEM_SS_LEN>( + keygen_kem, + (), + true, + ); +} + +#[test] +fn kem_keys_framework() { + TestFrameworkKEMKeys::new() + .test_keys::(keygen_kem); +} + +/// Every public key in Wycheproof's `x25519_test.json` (testvectors_v1, tcId 32, 33, 63 to 68, +/// 74 to 77, 81 and 82) whose shared secret is all zero: u = 0 and u = 1, the two points of +/// order 8, u = p - 1, p and p + 1, and each of them again with the ignored bit 255 set. Kept +/// here so that the check does not depend on the Wycheproof checkout being present. +const LOW_ORDER_PUBLIC_KEYS: [&str; 14] = [ + "0000000000000000000000000000000000000000000000000000000000000000", + "0100000000000000000000000000000000000000000000000000000000000000", + "e0eb7a7c3b41b8ae1656e3faf19fc46ada098deb9c32b1fd866205165f49b800", + "5f9c95bca3508c24b1d0b1559c83ef5b04445cc4581c8e86d8224eddd09f1157", + "ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f", + "e0eb7a7c3b41b8ae1656e3faf19fc46ada098deb9c32b1fd866205165f49b880", + "5f9c95bca3508c24b1d0b1559c83ef5b04445cc4581c8e86d8224eddd09f11d7", + "ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", + "edffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f", + "eeffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f", + "0000000000000000000000000000000000000000000000000000000000000080", + "0100000000000000000000000000000000000000000000000000000000000080", + "edffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", + "eeffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", +]; + +/// Low-order public keys give an all-zero X25519 output, which RFC 9180 Section 7.1.4 requires +/// both sides to reject. +#[test] +fn rejects_low_order_public_key() { + let (_, sk) = keygen(&mut DefaultRNG::default()).unwrap(); + + for u in LOW_ORDER_PUBLIC_KEYS.map(decode_32) { + match X25519PublicKey::from_bytes(&u) + .unwrap() + .encaps(&mut HashDRBG_SHA512::new_from_os(), ()) + { + Err(KEMError::InvalidPublicKey(_)) => { /* good */ } + other => panic!("encaps: expected InvalidPublicKey for u = {u:02x?}, got {other:?}"), + } + match sk.decaps(&u, ()) { + Err(KEMError::DecapsulationFailed) => { /* good */ } + other => panic!("decaps: expected DecapsulationFailed for u = {u:02x?}, got {other:?}"), + } + } +} + +/// RFC 9180 Section 7.1.2: SerializePrivateKey clamps its output and DeserializePrivateKey clamps +/// its input, and keys differing only in the clamped bits are the same key. +#[test] +fn private_key_encoding_is_clamped() { + let raw = decode_32(VECTORS[0].sk_rm); + assert_ne!(raw, clamp(raw), "the vector key must be unclamped for this test to mean anything"); + + let sk = X25519PrivateKey::from_bytes(&raw).unwrap(); + assert_eq!(sk.encode(), clamp(raw)); + let mut out = [0xFF_u8; 32]; + assert_eq!(sk.encode_out(&mut out), 32); + assert_eq!(out, clamp(raw)); + + // A key from keygen_from_seed keeps the unclamped bytes, but is equal to the clamped one. + let (_, unclamped) = keygen_from_seed(&seed(VECTORS[0].sk_rm)).unwrap(); + assert!(unclamped == sk); + assert_eq!(unclamped.encode(), clamp(raw)); + assert!(unclamped.clone() == sk); + + let (_, other) = keygen(&mut DefaultRNG::default()).unwrap(); + assert!(other != sk); +} + +#[test] +fn public_key_encoding() { + let bytes = decode_32(VECTORS[0].pk_rm); + let pk = >::from_bytes(&bytes).unwrap(); + assert_eq!(pk.encode(), bytes); + let mut out = [0xFF_u8; 32]; + assert_eq!(pk.encode_out(&mut out), 32); + assert_eq!(out, bytes); + assert_eq!( + pk.to_string(), + format!("X25519PublicKey {{ {} }}", VECTORS[0].pk_rm), + "Display shows the bytes in hex" + ); +} + +/// The KEM workers called directly, not through the roles' provided one-shots (which zeroize +/// the buffers themselves): each leaves stale buffers zeroized when the key has small order. +#[test] +fn the_kem_workers_leave_stale_buffers_zeroized_on_a_small_order_key() { + let (_, sk) = keygen(&mut DefaultRNG::default()).unwrap(); + let zero_pk = X25519PublicKey::from_bytes(&[0u8; POINT_LEN]).unwrap(); + let stale = || { + KeyMaterial::::from_bytes_as_type(&[0xFF; DHKEM_SS_LEN], KeyType::Seed) + .unwrap() + }; + + let encapsulator = zero_pk.create_encapsulator(()).unwrap(); + let mut ct = [0xFFu8; POINT_LEN]; + let mut ss = stale(); + assert!(matches!( + encapsulator.encaps_out(&mut HashDRBG_SHA512::new_from_os(), &mut ct, &mut ss), + Err(KEMError::InvalidPublicKey(_)) + )); + assert_eq!(ct, [0u8; POINT_LEN]); + assert_eq!(ss.key_type(), KeyType::Zeroized); + assert_eq!(ss.key_len(), 0); + + let decapsulator = sk.create_decapsulator(()).unwrap(); + let mut ss = stale(); + assert!(matches!( + decapsulator.decaps_out(&[0u8; POINT_LEN], &mut ss), + Err(KEMError::DecapsulationFailed) + )); + assert_eq!(ss.key_type(), KeyType::Zeroized); + assert_eq!(ss.key_len(), 0); +} + +/// The KEM roles name the KEM, not the function under it, and at X25519's strength. +#[test] +fn the_kem_workers_name_dhkem() { + let (pk, sk) = keygen(&mut DefaultRNG::default()).unwrap(); + let encapsulator = pk.create_encapsulator(()).unwrap(); + let decapsulator = sk.create_decapsulator(()).unwrap(); + assert_eq!(encapsulator.alg_name(), "DHKEM(X25519, HKDF-SHA256)"); + assert_eq!(decapsulator.alg_name(), "DHKEM(X25519, HKDF-SHA256)"); + assert_eq!(DHKEM_X25519_HKDF_SHA256::ALG_NAME, "DHKEM(X25519, HKDF-SHA256)"); + assert_eq!(DHKEM_X25519_HKDF_SHA256::MAX_SECURITY_STRENGTH, X25519::MAX_SECURITY_STRENGTH); + assert_eq!(encapsulator.max_security_strength(), SecurityStrength::_128bit); +} + +/// The all-zero key that `keygen_out` writes into makes no decapsulator until it is filled. +#[test] +fn an_unfilled_key_makes_no_decapsulator() { + let unfilled = X25519PrivateKey::zeroized(); + assert!(matches!( + unfilled.create_decapsulator(()), + Err(KEMError::KeyMaterialError(KeyMaterialError::ActingOnZeroizedKey)) + )); + assert!(matches!( + unfilled.decaps(&[9u8; POINT_LEN], ()), + Err(KEMError::KeyMaterialError(KeyMaterialError::ActingOnZeroizedKey)) + )); +} diff --git a/crypto/ed/tests/x25519_key_tests.rs b/crypto/ed/tests/x25519_key_tests.rs new file mode 100644 index 00000000..2bbcd755 --- /dev/null +++ b/crypto/ed/tests/x25519_key_tests.rs @@ -0,0 +1,235 @@ +use bouncycastle_core::errors::{KeyAgreementError, KeyMaterialError, RNGError}; +use bouncycastle_core::key_material::{KeyMaterial256, KeyMaterialTrait, KeyType}; +use bouncycastle_core::security_strength::SecurityStrength; +use bouncycastle_core::traits::{KeyAgreementPrivateKey, KeyAgreementPublicKey}; +use bouncycastle_core_test_framework::key_agreement::TestFrameworkKeyAgreementKeys; +use bouncycastle_ed::x25519::{ + POINT_LEN, SCALAR_LEN, X25519PrivateKey, X25519PublicKey, keygen, keygen_from_seed, + keygen_from_seed_out, keygen_out, +}; +use bouncycastle_hex as hex; +use bouncycastle_rng::{DefaultRNG, FixedSeedRNG}; + +/// RFC 7748 Section 6.1: Alice's private key a and public key X25519(a, 9). +const ALICE_SK: &str = "77076d0a7318a57d3c16c17251b26645df4c2f87ebc0992ab177fba51db92c2a"; +const ALICE_PK: &str = "8520f0098930a754748b7ddcb43ef75a0dbf3a0d26381af4eba4a98eaa9b4e6a"; + +fn seed(hex_str: &str, key_type: KeyType) -> KeyMaterial256 { + KeyMaterial256::from_bytes_as_type(&hex::decode(hex_str).unwrap(), key_type).unwrap() +} + +fn keygen_default() -> Result<(X25519PublicKey, X25519PrivateKey), KeyAgreementError> { + keygen(&mut DefaultRNG::default()) +} + +#[test] +fn core_framework_tests() { + TestFrameworkKeyAgreementKeys::new() + .test_keys::(keygen_default); +} + +#[test] +fn keygen_from_seed_takes_a_seed_or_random_material() { + for key_type in [KeyType::Seed, KeyType::CryptographicRandom] { + let (pk, sk) = keygen_from_seed(&seed(ALICE_SK, key_type)).unwrap(); + assert_eq!(pk.as_bytes().as_slice(), hex::decode(ALICE_PK).unwrap()); + assert_eq!(sk.pk(), pk); + } +} + +#[test] +fn keygen_from_seed_rejects_bad_seeds() { + // Wrong key type. + match keygen_from_seed(&seed(ALICE_SK, KeyType::MACKey)) { + Err(KeyAgreementError::KeyMaterialError(KeyMaterialError::InvalidKeyType(_))) => {} + other => panic!("expected InvalidKeyType, got {:?}", other.err()), + } + + // All zeros: KeyMaterial marks it KeyType::Zeroized, and the refusal says so. + match keygen_from_seed(&seed(&"00".repeat(32), KeyType::Seed)) { + Err(KeyAgreementError::KeyMaterialError(KeyMaterialError::ActingOnZeroizedKey)) => {} + other => panic!("expected ActingOnZeroizedKey, got {:?}", other.err()), + } + + // Undersized. + let short = seed(&ALICE_SK[..62], KeyType::Seed); + assert_eq!(short.key_len(), 31); + match keygen_from_seed(&short) { + Err(KeyAgreementError::KeyMaterialError(KeyMaterialError::InvalidKeyType(_))) => {} + other => panic!("expected InvalidKeyType, got {:?}", other.err()), + } + + // Security strength below the algorithm's, and exactly at it. + let mut weak = seed(ALICE_SK, KeyType::Seed); + weak.set_security_strength(SecurityStrength::_112bit).unwrap(); + match keygen_from_seed(&weak) { + Err(KeyAgreementError::KeyMaterialError(KeyMaterialError::SecurityStrength(_))) => {} + other => panic!("expected SecurityStrength, got {:?}", other.err()), + } + let mut just_right = seed(ALICE_SK, KeyType::Seed); + just_right.set_security_strength(SecurityStrength::_128bit).unwrap(); + keygen_from_seed(&just_right).unwrap(); +} + +#[test] +fn keygen_uses_the_rng_output_as_the_key() { + // The RNG output is used as the seed, so this must match keygen_from_seed. + let seed_bytes: [u8; 32] = hex::decode(ALICE_SK).unwrap().try_into().unwrap(); + let mut rng = FixedSeedRNG::new(seed_bytes); + let (pk, sk) = keygen(&mut rng).unwrap(); + assert_eq!(pk.as_bytes().as_slice(), hex::decode(ALICE_PK).unwrap()); + assert_eq!(sk.pk(), pk); + + // RNG too weak. + let mut rng = FixedSeedRNG::new(seed_bytes); + rng.set_security_strength(SecurityStrength::_112bit); + match keygen(&mut rng) { + Err(KeyAgreementError::RNGError(RNGError::SecurityStrengthInsufficientForAlgorithm)) => {} + other => { + panic!( + "expected RNGError::SecurityStrengthInsufficientForAlgorithm, got {:?}", + other.err() + ) + } + } + + // RNG just right. + let mut rng = FixedSeedRNG::new(seed_bytes); + rng.set_security_strength(SecurityStrength::_128bit); + keygen(&mut rng).unwrap(); +} + +/// The out forms write into a key the caller holds: a stale key is overwritten with what the +/// by-value forms give for the same RNG output or seed, the returned public key is the key's +/// own, and a refused RNG or seed leaves the key all zero. +#[test] +fn the_out_forms_fill_the_callers_key_and_zeroize_it_on_refusal() { + let seed_bytes: [u8; 32] = hex::decode(ALICE_SK).unwrap().try_into().unwrap(); + let zero = X25519PrivateKey::zeroized(); + assert_eq!(zero.pk().as_bytes(), &[0u8; POINT_LEN]); + + let (_, mut sk) = keygen_default().unwrap(); + let pk = keygen_out(&mut FixedSeedRNG::new(seed_bytes), &mut sk).unwrap(); + assert_eq!(pk.as_bytes().as_slice(), hex::decode(ALICE_PK).unwrap()); + assert_eq!(sk.pk(), pk); + assert!(sk == keygen(&mut FixedSeedRNG::new(seed_bytes)).unwrap().1); + + let mut weak = FixedSeedRNG::new(seed_bytes); + weak.set_security_strength(SecurityStrength::_112bit); + assert!(matches!( + keygen_out(&mut weak, &mut sk), + Err(KeyAgreementError::RNGError(RNGError::SecurityStrengthInsufficientForAlgorithm)) + )); + assert!(sk == zero); + assert_eq!(sk.pk(), zero.pk()); + + let (_, mut sk) = keygen_default().unwrap(); + let pk = keygen_from_seed_out(&seed(ALICE_SK, KeyType::Seed), &mut sk).unwrap(); + assert_eq!(pk.as_bytes().as_slice(), hex::decode(ALICE_PK).unwrap()); + assert_eq!(sk.pk(), pk); + assert!(sk == keygen_from_seed(&seed(ALICE_SK, KeyType::Seed)).unwrap().1); + + assert!(matches!( + keygen_from_seed_out(&seed(ALICE_SK, KeyType::Unknown), &mut sk), + Err(KeyAgreementError::KeyMaterialError(KeyMaterialError::InvalidKeyType(_))) + )); + assert!(sk == zero); + assert_eq!(sk.pk(), zero.pk()); +} + +#[test] +fn keygen_gives_fresh_pairs_whose_public_keys_belong_to_them() { + let (pk1, sk1) = keygen_default().unwrap(); + let (pk2, sk2) = keygen_default().unwrap(); + assert_ne!(pk1, pk2); + assert_eq!(sk1.pk(), pk1); + assert_eq!(sk2.pk(), pk2); + assert_ne!(sk1.pk(), pk2); + assert_ne!(sk2.pk(), pk1); +} + +#[test] +fn private_key_pk() { + let (_, sk) = keygen_from_seed(&seed(ALICE_SK, KeyType::Seed)).unwrap(); + assert_eq!(sk.pk().as_bytes().as_slice(), hex::decode(ALICE_PK).unwrap()); + + let (pk, sk) = keygen_default().unwrap(); + assert_eq!(sk.pk(), pk); +} + +#[test] +fn public_key_to_bytes() { + let (pk, _) = keygen_from_seed(&seed(ALICE_SK, KeyType::Seed)).unwrap(); + let expected = hex::decode(ALICE_PK).unwrap(); + + let as_ref: &[u8] = pk.as_ref(); + assert_eq!(as_ref, expected); +} + +fn decode_32(s: &str) -> [u8; 32] { + hex::decode(s).unwrap().try_into().unwrap() +} + +/// Clamps as `decodeScalar25519` does (RFC 7748 Section 5). +fn clamp(mut k: [u8; 32]) -> [u8; 32] { + k[0] &= 248; + k[31] &= 127; + k[31] |= 64; + k +} + +#[test] +fn public_key_encoding() { + let bytes = decode_32(ALICE_PK); + let pk = X25519PublicKey::from_bytes(&bytes).unwrap(); + assert_eq!(KeyAgreementPublicKey::encode(&pk), bytes); + + let mut out = [0xFF_u8; 32]; + assert_eq!(KeyAgreementPublicKey::encode_out(&pk, &mut out), 32); + assert_eq!(out, bytes); + + // Decoding round-trips, and accepts any 32 bytes, including bit 255 set (RFC 7748 Section 5). + let decoded = >::from_bytes(&bytes).unwrap(); + assert_eq!(decoded, pk); + let top_bit = [0xFF_u8; 32]; + let decoded = >::from_bytes(&top_bit).unwrap(); + assert_eq!(KeyAgreementPublicKey::encode(&decoded), top_bit); + + for len in [0, 31, 33] { + match >::from_bytes(&vec![1_u8; len]) { + Err(KeyAgreementError::DecodingError(_)) => { /* good */ } + _ => panic!("expected DecodingError for {len} bytes"), + } + } +} + +#[test] +fn private_key_encoding() { + // The RFC 7748 Section 6.1 key is unclamped, so this exercises the clamping. + let raw = decode_32(ALICE_SK); + assert_ne!(raw, clamp(raw)); + + let sk = >::from_bytes(&raw).unwrap(); + assert_eq!(KeyAgreementPrivateKey::encode(&sk), clamp(raw)); + assert_eq!(sk.pk().as_bytes(), &decode_32(ALICE_PK)); + + let mut out = [0xFF_u8; 32]; + assert_eq!(KeyAgreementPrivateKey::encode_out(&sk, &mut out), 32); + assert_eq!(out, clamp(raw)); + + // A key built from the unclamped seed is the same key, with the same encoding, and it + // round-trips through its encoding. + let (_, from_seed) = keygen_from_seed(&seed(ALICE_SK, KeyType::Seed)).unwrap(); + assert!(from_seed == sk); + assert_eq!(KeyAgreementPrivateKey::encode(&from_seed), clamp(raw)); + let encoded = KeyAgreementPrivateKey::encode(&from_seed); + let decoded = >::from_bytes(&encoded).unwrap(); + assert!(decoded == from_seed); + + for len in [0, 31, 33] { + match >::from_bytes(&vec![1_u8; len]) { + Err(KeyAgreementError::DecodingError(_)) => { /* good */ } + _ => panic!("expected DecodingError for {len} bytes"), + } + } +} diff --git a/crypto/ed/tests/x25519_tests.rs b/crypto/ed/tests/x25519_tests.rs new file mode 100644 index 00000000..86794039 --- /dev/null +++ b/crypto/ed/tests/x25519_tests.rs @@ -0,0 +1,378 @@ +use bouncycastle_core::agreement_key::AgreementKey; +use bouncycastle_core::errors::{KeyAgreementError, KeyMaterialError}; +use bouncycastle_core::kdf_params::{KdfDescription, KdfParams, KeyLen}; +use bouncycastle_core::key_material::{ + KeyMaterial, KeyMaterial0, KeyMaterial256, KeyMaterialTrait, KeyType, +}; +use bouncycastle_core::security_strength::SecurityStrength; +use bouncycastle_core::traits::{KDF, KeyAgreement, KeyAgreementPrivateKey, KeyAgreementPublicKey}; +use bouncycastle_core_test_framework::DUMMY_SEED; +use bouncycastle_core_test_framework::key_agreement::TestFrameworkKeyAgreement; +use bouncycastle_ed::x25519::{ + HKDF_SHA256_MAX_LEN, POINT_LEN, SCALAR_LEN, X25519PrivateKey, X25519PublicKey, keygen, + keygen_from_seed, +}; +use bouncycastle_hex as hex; +use bouncycastle_hkdf::HkdfDescription; +use bouncycastle_rng::DefaultRNG; +use bouncycastle_sha2::SHA256; +use bouncycastle_sha2::hkdf::HKDF_SHA256; + +fn keygen_default() -> Result<(X25519PublicKey, X25519PrivateKey), KeyAgreementError> { + keygen(&mut DefaultRNG::default()) +} + +/// The framework's agreement suite over the raw primitive and over the HKDF-SHA256 pairing. +#[test] +fn core_framework_tests() { + TestFrameworkKeyAgreement::new().test_key_agreement(keygen_default, ()); + let hkdf = HkdfDescription::::new(); + TestFrameworkKeyAgreement::new().test_key_agreement( + keygen_default, + KdfParams::new(&hkdf, b"X25519 framework info", KeyLen::<32>), + ); +} + +/// The raw agreement's output is `K` typed for a KDF at X25519's strength, and the HKDF-SHA256 +/// pairing is HKDF run by hand over that `K` with the same info. +#[test] +fn raw_z_is_a_shared_secret_and_the_pairing_is_hkdf_over_it() { + let (alice_pk, alice_sk) = keygen_default().unwrap(); + let (bob_pk, bob_sk) = keygen_default().unwrap(); + + let z = alice_sk.agree(&bob_pk, ()).unwrap(); + assert_eq!(z.key_type(), KeyType::SharedSecret); + assert_eq!(z.security_strength(), SecurityStrength::_128bit); + assert_eq!(z.key_len(), POINT_LEN); + + let mut info = [0u8; 2 * POINT_LEN]; + info[..POINT_LEN].copy_from_slice(&alice_pk.encode()); + info[POINT_LEN..].copy_from_slice(&bob_pk.encode()); + let hkdf = HkdfDescription::::new(); + let derived = bob_sk.agree(&alice_pk, KdfParams::new(&hkdf, &info, KeyLen::<48>)).unwrap(); + let mut by_hand = KeyMaterial::<48>::new(); + hkdf.engine().unwrap().derive_key_out(&z, &info, 48, &mut by_hand).unwrap(); + assert!(derived.equals(&by_hand)); + assert_eq!(derived.key_type(), KeyType::CryptographicRandom); + assert_eq!(derived.security_strength(), SecurityStrength::_128bit); +} + +/// The pairing under a salted description: the framework suite, both sides agree, the key is +/// HKDF-SHA256 extract-and-expand by hand over `K` with that salt, and the absent salt or +/// another info derives a different key. A salt typed `Unknown` is refused at the description. +#[test] +fn the_pairing_takes_the_descriptions_salt() { + const LEN: usize = 32; + let salt = + KeyMaterial::<32>::from_bytes_as_type(&DUMMY_SEED[..32], KeyType::CryptographicRandom) + .unwrap(); + let hkdf = HkdfDescription::::with_salt(&salt).unwrap(); + let params = KdfParams::new(&hkdf, b"X25519 salted info", KeyLen::); + TestFrameworkKeyAgreement::new().test_key_agreement(keygen_default, params); + + let (alice_pk, alice_sk) = keygen_default().unwrap(); + let (bob_pk, bob_sk) = keygen_default().unwrap(); + let key = alice_sk.agree(&bob_pk, params).unwrap(); + assert!(key.equals(&bob_sk.agree(&alice_pk, params).unwrap())); + assert_eq!(key.key_len(), LEN); + assert_eq!(key.key_type(), KeyType::CryptographicRandom); + assert_eq!(key.security_strength(), SecurityStrength::_128bit); + + let z = alice_sk.agree(&bob_pk, ()).unwrap(); + let mut expected = KeyMaterial::::new(); + HKDF_SHA256::extract_and_expand_out(&salt, &z, b"X25519 salted info", LEN, &mut expected) + .unwrap(); + assert!(key.equals(&expected)); + + let other_info = KdfParams::new(&hkdf, b"another context", KeyLen::); + assert!(!alice_sk.agree(&bob_pk, other_info).unwrap().equals(&key)); + let absent = KeyMaterial0::new(); + let hkdf_absent = HkdfDescription::::with_salt(&absent).unwrap(); + let no_salt = KdfParams::new(&hkdf_absent, b"X25519 salted info", KeyLen::); + assert!(!alice_sk.agree(&bob_pk, no_salt).unwrap().equals(&key)); + + let unknown = + KeyMaterial::<32>::from_bytes_as_type(&DUMMY_SEED[..32], KeyType::Unknown).unwrap(); + assert!(HkdfDescription::::with_salt(&unknown).is_err()); +} + +/// The pairing derives its longest key, RFC 5869 Section 2.3's 255 * HashLen bytes, in one call, +/// and the constant is that bound: 255 * 32 for SHA-256. +#[test] +fn the_pairing_derives_its_longest_key() { + assert_eq!(HKDF_SHA256_MAX_LEN, 8160); + let (alice_pk, alice_sk) = keygen_default().unwrap(); + let (bob_pk, bob_sk) = keygen_default().unwrap(); + let hkdf = HkdfDescription::::new(); + let key_a = alice_sk + .agree(&bob_pk, KdfParams::new(&hkdf, b"longest", KeyLen::)) + .unwrap(); + let key_b = bob_sk + .agree(&alice_pk, KdfParams::new(&hkdf, b"longest", KeyLen::)) + .unwrap(); + assert_eq!(key_a.key_len(), HKDF_SHA256_MAX_LEN); + assert!(key_a.equals(&key_b)); +} + +#[test] +fn iterated() { + rfc7748_check_iterated(1000); +} + +/// Ignored because it's quite slow, can be run with +/// cargo test -p bouncycastle-ed -- --ignored +/// or +/// cargo test -p bouncycastle-ed -- --include-ignored +#[ignore] +#[test] +fn iterated_full() { + rfc7748_check_iterated(1000000); +} + +/// The first X25519 single-call test vector of RFC 7748 Section 5.2. +#[test] +fn vector_1() { + check_vector( + "a546e36bf0527c9d3b16154b82465edd62144c0ac1fc5a18506a2244ba449ac4", + "e6db6867583030db3594c1a424b15f7c726624ec26b3353b10a903a6d0ab1c4c", + "c3da55379de9c6908e94ea4df28d084f32eccf03491c71f754b4075577a28552", + "Vector #1", + ); +} + +/// The second X25519 single-call test vector of RFC 7748 Section 5.2. +#[test] +fn vector_2() { + check_vector( + "4b66e9d4d1b4673c5ad22691957d6af5c11b6421e0ea01d42ca4169e7918ba0d", + "e5210f12786811d3f4b7959d0538ae2c31dbe7106fc03c3efc4cd549c715a493", + "95cbde9476e8907d7aade45cb4b873f88b595a68799fa152e6f8f7647aac7957", + "Vector #2", + ); +} + +/// RFC 7748 Section 6.1: Alice's and Bob's public keys, X25519(a, 9) and X25519(b, 9), and the +/// shared secret K that each derives from their own private key and the other's public key. +#[test] +fn rfc7748_section_6_1() { + let alice_sk = sk_from_bytes(&decode_32( + "77076d0a7318a57d3c16c17251b26645df4c2f87ebc0992ab177fba51db92c2a", + )); + let bob_sk = sk_from_bytes(&decode_32( + "5dab087e624a8a4b79e17f8b83800ee66f3bb1292618b6fd1c2f8b27ff88e0eb", + )); + + let alice_pk = alice_sk.pk(); + let bob_pk = bob_sk.pk(); + check_value( + alice_pk.as_bytes(), + "Section 6.1 Alice's public key", + "8520f0098930a754748b7ddcb43ef75a0dbf3a0d26381af4eba4a98eaa9b4e6a", + ); + check_value( + bob_pk.as_bytes(), + "Section 6.1 Bob's public key", + "de9edb7d7b7dc1b4d35b61c2ece435373f8343c85b78674dadfc7e146f882b4f", + ); + + let k = "4a5d9d5ba4ce2de1728e3bf480350f25e07e21c947d19e3376f09b3c1e161742"; + let alice_k = alice_sk.agree(&bob_pk, ()).unwrap(); + let bob_k = bob_sk.agree(&alice_pk, ()).unwrap(); + check_value(alice_k.ref_to_bytes(), "Section 6.1 K (Alice)", k); + check_value(bob_k.ref_to_bytes(), "Section 6.1 K (Bob)", k); +} + +/// Every public key in Wycheproof's `x25519_test.json` (testvectors_v1, tcId 32, 33, 63 to 68, +/// 74 to 77, 81 and 82) whose shared secret is all zero: u = 0 and u = 1, the two points of +/// order 8, u = p - 1, p and p + 1, and each of them again with the ignored bit 255 set. Kept +/// here so that the check does not depend on the Wycheproof checkout being present. +const LOW_ORDER_PUBLIC_KEYS: [&str; 14] = [ + "0000000000000000000000000000000000000000000000000000000000000000", + "0100000000000000000000000000000000000000000000000000000000000000", + "e0eb7a7c3b41b8ae1656e3faf19fc46ada098deb9c32b1fd866205165f49b800", + "5f9c95bca3508c24b1d0b1559c83ef5b04445cc4581c8e86d8224eddd09f1157", + "ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f", + "e0eb7a7c3b41b8ae1656e3faf19fc46ada098deb9c32b1fd866205165f49b880", + "5f9c95bca3508c24b1d0b1559c83ef5b04445cc4581c8e86d8224eddd09f11d7", + "ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", + "edffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f", + "eeffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f", + "0000000000000000000000000000000000000000000000000000000000000080", + "0100000000000000000000000000000000000000000000000000000000000080", + "edffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", + "eeffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", +]; + +/// The agreement rejects a public key that gives an all-zero shared secret, however that key +/// is encoded: every small-order point, canonical or not, with or without the ignored bit 255. +/// The caller's buffer is left zeroized. +#[test] +fn key_agreement_rejects_all_zero_shared_secret() { + for u in LOW_ORDER_PUBLIC_KEYS.map(decode_32) { + let sk = sk_from_bytes(&decode_32( + "77076d0a7318a57d3c16c17251b26645df4c2f87ebc0992ab177fba51db92c2a", + )); + let pk = X25519PublicKey::from_bytes(&u).unwrap(); + match sk.agree(&pk, ()) { + Err(KeyAgreementError::AgreementFailed) => { /* good */ } + Err(e) => panic!("expected AgreementFailed for u = {u:02x?}, got {e:?}"), + Ok(_) => panic!("expected AgreementFailed for u = {u:02x?}, got Ok"), + } + let mut ss = + KeyMaterial::::from_bytes_as_type(&[0xFF; POINT_LEN], KeyType::Seed) + .unwrap(); + assert!(matches!(sk.agree_out(&pk, (), &mut ss), Err(KeyAgreementError::AgreementFailed))); + assert_eq!(ss.key_type(), KeyType::Zeroized); + assert_eq!(ss.key_len(), 0); + } +} + +fn decode_32(s: &str) -> [u8; 32] { + hex::decode(s).unwrap().try_into().unwrap() +} + +/// RFC 7748 Section 5: "Implementations MUST accept non-canonical values and process them as if +/// they had been reduced modulo the field prime", and "MUST mask the most significant bit in the +/// final byte". So u = p + 3 agrees as u = 3 does, and so does u = 3 with bit 255 set. +#[test] +fn non_canonical_u_coordinates_agree_as_their_reduced_value() { + let sk = sk_from_bytes(&decode_32( + "77076d0a7318a57d3c16c17251b26645df4c2f87ebc0992ab177fba51db92c2a", + )); + let mut three = [0_u8; POINT_LEN]; + three[0] = 3; + // p + 3 = 2^255 - 16 + let p_plus_3 = decode_32("f0ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f"); + let mut three_bit_255 = three; + three_bit_255[31] |= 0x80; + + let expected = sk.agree(&X25519PublicKey::from_bytes(&three).unwrap(), ()).unwrap(); + for u in [p_plus_3, three_bit_255] { + let k = sk.agree(&X25519PublicKey::from_bytes(&u).unwrap(), ()).unwrap(); + assert_eq!(k.ref_to_bytes(), expected.ref_to_bytes(), "u = {u:02x?}"); + } +} + +/// The all-zero key that `keygen_out` writes into is not a key until it is filled: it makes no +/// agreement, raw or through HKDF, and the generators leave it in that state on an error. +#[test] +fn an_unfilled_key_makes_no_agreement() { + let unfilled = X25519PrivateKey::zeroized(); + let (pk, _) = keygen_default().unwrap(); + assert!(matches!( + unfilled.agree(&pk, ()), + Err(KeyAgreementError::KeyMaterialError(KeyMaterialError::ActingOnZeroizedKey)) + )); + let description = HkdfDescription::::new(); + let params = KdfParams::new(&description, b"info", KeyLen::<32>); + assert!(matches!( + unfilled.agree(&pk, params), + Err(KeyAgreementError::KeyMaterialError(KeyMaterialError::ActingOnZeroizedKey)) + )); + + // A generated key is unaffected, including the one whose bytes are all zero: its scalar + // clamps to 2^254 and its public key is not zero. + let zero_bytes = X25519PrivateKey::from_bytes(&[0u8; SCALAR_LEN]).unwrap(); + assert!(zero_bytes.agree(&pk, ()).is_ok()); +} + +/// A private key from its 32 bytes, via [`keygen_from_seed`]. +fn sk_from_bytes(bytes: &[u8]) -> X25519PrivateKey { + let seed = KeyMaterial256::from_bytes_as_type(bytes, KeyType::Seed).unwrap(); + keygen_from_seed(&seed).unwrap().1 +} + +/// The iterated test of RFC 7748 Section 5.2: starting from k = u = 9, each iteration sets k to +/// `X25519(k, u)` and u to the old k, and k is checked after 1, 1,000 and 1,000,000 iterations. +/// +/// Feeding each output back in as the next scalar and u-coordinate exercises the ladder, field +/// arithmetic and encodings on `count` effectively random inputs against a single known answer, +/// and one wrong step corrupts every value after it. The single-call vectors cover two inputs. +fn rfc7748_check_iterated(count: usize) { + assert_eq!(POINT_LEN, SCALAR_LEN); + + let mut k = [0_u8; POINT_LEN]; + k[0] = 9; + let mut u = [0_u8; POINT_LEN]; + u[0] = 9; + let mut iterations = 0; + while iterations < count { + let r = sk_from_bytes(&k).agree(&X25519PublicKey::from_bytes(&u).unwrap(), ()).unwrap(); + + u = k; + k.copy_from_slice(r.ref_to_bytes()); + + iterations += 1; + + match iterations { + 1 => check_value( + &k, + "Iterated @1", + "422c8e7a6227d7bca1350b3e2bb7279f7897b87bb6854b783c60e80311ae3079", + ), + 1000 => check_value( + &k, + "Iterated @1000", + "684cf59ba83309552800ef566f2f4d3c1c3887c49360e3875f2eb94d99532c51", + ), + 1000000 => check_value( + &k, + "Iterated @1000000", + "7c3911e0ab2586fd864497297e575e6f3bc601c0883c30df5f4dd2d24f665424", + ), + _ => {} + } + } +} + +fn check_value(n: &[u8], text: &str, se: &str) { + let e = hex::decode(se).unwrap(); + assert_eq!(e.as_slice(), n, "{}", text); +} + +fn check_vector(sk: &str, su: &str, se: &str, text: &str) { + let k = sk_from_bytes(&decode_32(sk)); + let u = X25519PublicKey::from_bytes(&decode_32(su)).unwrap(); + + let r = k.agree(&u, ()).unwrap(); + check_value(r.ref_to_bytes(), text, se); +} + +/// Review of PR #186, B1: Alice's key against a u whose K is 21. The last multiply returns the +/// representation `r + p` for every r in about `[19, 2^207)`, which the old normalize's debug +/// assertion rejected, so this agreement panicked in a debug build. Debug and release give 21. +#[test] +fn a_shared_secret_of_21_is_computed_in_every_build() { + let sk = sk_from_bytes(&decode_32( + "77076d0a7318a57d3c16c17251b26645df4c2f87ebc0992ab177fba51db92c2a", + )); + let pk = X25519PublicKey::from_bytes(&decode_32( + "564f21c353c8571dc99804aa5508352172195d6fd4a24387112d5caaf30d6951", + )) + .unwrap(); + let mut expected = [0u8; POINT_LEN]; + expected[0] = 21; + assert_eq!(sk.agree(&pk, ()).unwrap().ref_to_bytes(), &expected); +} + +/// The workers called directly, not through the role's provided `agree_out` (which zeroizes the +/// buffer itself): each leaves a stale buffer zeroized when the peer key has small order. +#[test] +fn the_workers_leave_a_stale_buffer_zeroized_on_a_small_order_peer() { + let (_, sk) = keygen_default().unwrap(); + let zero_pk = X25519PublicKey::from_bytes(&[0u8; POINT_LEN]).unwrap(); + + let raw = sk.create_agreement(()).unwrap(); + let mut ss = + KeyMaterial::::from_bytes_as_type(&[0xFF; POINT_LEN], KeyType::Seed).unwrap(); + assert!(matches!(raw.agree_out(&zero_pk, &mut ss), Err(KeyAgreementError::AgreementFailed))); + assert_eq!(ss.key_type(), KeyType::Zeroized); + assert_eq!(ss.key_len(), 0); + + let hkdf = HkdfDescription::::new(); + let paired = sk.create_agreement(KdfParams::new(&hkdf, b"info", KeyLen::<32>)).unwrap(); + let mut ss = KeyMaterial::<32>::from_bytes_as_type(&[0xFF; 32], KeyType::Seed).unwrap(); + assert!(matches!(paired.agree_out(&zero_pk, &mut ss), Err(KeyAgreementError::AgreementFailed))); + assert_eq!(ss.key_type(), KeyType::Zeroized); + assert_eq!(ss.key_len(), 0); +} diff --git a/crypto/ed/tests/x25519_wycheproof.rs b/crypto/ed/tests/x25519_wycheproof.rs new file mode 100644 index 00000000..86f86149 --- /dev/null +++ b/crypto/ed/tests/x25519_wycheproof.rs @@ -0,0 +1,76 @@ +//! Known-answer tests against Project Wycheproof's `testvectors_v1/x25519_test.json`. +//! +//! Requires the Wycheproof repository (https://github.com/C2SP/wycheproof) to be cloned alongside +//! this repository, i.e. at `../wycheproof` relative to the root of this git project. If it is +//! absent the tests print a warning and pass, matching the convention used by the other vector +//! suites. +//! +//! Every case is either `valid` or `acceptable`, and every case has an expected shared secret, so +//! each one is checked for exact output. The `acceptable` cases are low-order, twist and +//! non-canonical public keys, which RFC 7748 Section 5 requires to be processed rather than +//! rejected. The exception is those whose shared secret is all zeros (flag `ZeroSharedSecret`), +//! which the agreement refuses as `KeyAgreementError::AgreementFailed`. + +use bouncycastle_core::agreement_key::AgreementKey; +use bouncycastle_core::errors::KeyAgreementError; +use bouncycastle_core::key_material::{KeyMaterial256, KeyMaterialTrait, KeyType}; +use bouncycastle_core::traits::KeyAgreementPublicKey; +use bouncycastle_core_test_framework::test_data_loaders::{Value, hex_field, wycheproof_json}; +use bouncycastle_ed::x25519::{ + POINT_LEN, SCALAR_LEN, X25519PrivateKey, X25519PublicKey, keygen_from_seed, +}; + +#[test] +fn wycheproof_x25519() { + let filename = "x25519_test.json"; + let Some(doc) = wycheproof_json(filename) else { return }; + + assert_eq!(doc.get("algorithm").and_then(Value::as_str), Some("XDH"), "{filename}"); + + let (mut valid, mut acceptable, mut zero_shared) = (0usize, 0usize, 0usize); + for group in doc.get("testGroups").and_then(Value::as_array).expect("testGroups") { + assert_eq!(group.get("curve").and_then(Value::as_str), Some("curve25519"), "{filename}"); + + for test in group.get("tests").and_then(Value::as_array).expect("tests") { + let tc_id = test.get("tcId").and_then(Value::as_u64).expect("tcId"); + let ctx = format!("{filename} tcId {tc_id}"); + match test.get("result").and_then(Value::as_str).expect("result") { + "valid" => valid += 1, + "acceptable" => acceptable += 1, + other => panic!("{ctx}: unexpected result {other}"), + } + + let k: [u8; SCALAR_LEN] = + hex_field(test, "private", tc_id).try_into().expect("a 32-byte private key"); + let u: [u8; POINT_LEN] = + hex_field(test, "public", tc_id).try_into().expect("a 32-byte public key"); + let shared = hex_field(test, "shared", tc_id); + + let (k, u) = (sk_from_bytes(&k), X25519PublicKey::from_bytes(&u).unwrap()); + match k.agree(&u, ()) { + Ok(r) => assert_eq!(r.ref_to_bytes(), shared.as_slice(), "{ctx}: shared secret"), + Err(KeyAgreementError::AgreementFailed) => { + assert!(shared.iter().all(|&b| b == 0), "{ctx}: rejected a non-zero secret"); + zero_shared += 1; + } + Err(e) => panic!("{ctx}: unexpected error {e:?}"), + } + } + } + + println!( + "Wycheproof X25519: {} cases ({valid} valid, {acceptable} acceptable; \ + {zero_shared} with an all-zero shared secret)", + valid + acceptable + ); + assert!( + valid > 0 && acceptable > 0 && zero_shared > 0, + "{filename}: expected every kind of case" + ); +} + +/// A private key from its 32 bytes, via [`keygen_from_seed`]. +fn sk_from_bytes(bytes: &[u8]) -> X25519PrivateKey { + let seed = KeyMaterial256::from_bytes_as_type(bytes, KeyType::Seed).unwrap(); + keygen_from_seed(&seed).unwrap().1 +} diff --git a/crypto/hpke/Cargo.toml b/crypto/hpke/Cargo.toml new file mode 100644 index 00000000..b2469905 --- /dev/null +++ b/crypto/hpke/Cargo.toml @@ -0,0 +1,14 @@ +[package] +name = "bouncycastle-hpke" +version.workspace = true +edition.workspace = true + +[dependencies] +bouncycastle-core.workspace = true +bouncycastle-hmac.workspace = true +bouncycastle-utils.workspace = true + +[dev-dependencies] +bouncycastle-ed.workspace = true +bouncycastle-hex.workspace = true +bouncycastle-rng.workspace = true diff --git a/crypto/hpke/src/dhkem.rs b/crypto/hpke/src/dhkem.rs new file mode 100644 index 00000000..ab4fa22d --- /dev/null +++ b/crypto/hpke/src/dhkem.rs @@ -0,0 +1,526 @@ +//! The DH-Based KEM (DHKEM) of RFC 9180 Section 4.1, generic over the Diffie-Hellman group. +//! +//! A group's crate implements [`DHKEMParams`] for its algorithm struct and then calls +//! [`DHKEM::encap_rng_out`] and [`DHKEM::decap_out`] from the workers its keys hand out through +//! [`EncapsulatingKey`](bouncycastle_core::kem_key::EncapsulatingKey) and +//! [`DecapsulatingKey`](bouncycastle_core::kem_key::DecapsulatingKey). + +use bouncycastle_core::errors::{KEMError, KeyAgreementError, KeyMaterialError, RNGError}; +use bouncycastle_core::key_material::{KeyMaterial, KeyMaterialTrait, KeyType}; +use bouncycastle_core::security_strength::SecurityStrength; +use bouncycastle_core::symmetric_key::FromAnyKeyMaterial; +use bouncycastle_core::traits::{Algorithm, Hash, HashAlgParams, RNG}; +use bouncycastle_hmac::hazmat as hmac_hazmat; +use bouncycastle_hmac::{HMACParams, HmacKey}; +use bouncycastle_utils::secret::Secret; +use core::marker::PhantomData; + +/// The version label that RFC 9180 Section 4 puts at the front of every labeled KDF input. +const HPKE_VERSION_LABEL: &[u8] = b"HPKE-v1"; + +// The labels of RFC 9180 Sections 4.1 and 7.1.3. +const LABEL_EAE_PRK: &[u8] = b"eae_prk"; +const LABEL_SHARED_SECRET: &[u8] = b"shared_secret"; +const LABEL_DKP_PRK: &[u8] = b"dkp_prk"; +const LABEL_SK: &[u8] = b"sk"; + +/// The largest Nh among the KDFs of RFC 9180 Section 7.2 (HKDF-SHA512). The PRK and HKDF-Expand +/// block buffers are sized to it. +const MAX_NH: usize = 64; + +/// A strength as a bit count, for the compile-time check that a group's hash is long enough. +const fn strength_bits(strength: SecurityStrength) -> usize { + match strength { + SecurityStrength::None => 0, + SecurityStrength::_112bit => 112, + SecurityStrength::_128bit => 128, + SecurityStrength::_192bit => 192, + SecurityStrength::_256bit => 256, + #[allow(unreachable_patterns)] // the enum is non_exhaustive + _ => 256, + } +} + +/// The Diffie-Hellman group of a DHKEM, and the KDF it is paired with: DHKEM(Group, KDF) in RFC 9180 +/// Section 4.1. +/// +/// Implemented by a group's algorithm struct. The const parameters are the group's sizes from RFC +/// 9180 Section 7.1: `N_PK` is Npk (which equals Nenc), `N_SK` is Nsk and `N_DH` is Ndh. +pub trait DHKEMParams: Algorithm { + /// The group's public key. + type PublicKey; + /// The group's private key. + type PrivateKey; + /// The hash of the DHKEM's KDF, which is HKDF over this hash. + type KDFHash: HMACParams; + /// The `kem_id` of RFC 9180 Section 7.1, Table 2. + const KEM_ID: u16; + + /// `GenerateKeyPair()` (RFC 9180 Section 4), drawing its randomness from `rng`, with the pair + /// lent to `f` rather than returned: the implementation generates the private key in a slot + /// of its own frame and drops it there, so the ephemeral key of an encapsulation is never + /// moved. + fn with_generated_key_pair( + rng: &mut dyn RNG, + f: impl FnOnce(&Self::PublicKey, &Self::PrivateKey) -> R, + ) -> Result; + + /// The private key with the byte string `sk` as its value, as `DeriveKeyPair` (RFC 9180 + /// Section 7.1.3) requires. + fn private_key_from_bytes(sk: &[u8; N_SK]) -> Self::PrivateKey; + + /// `pk(skX)` (RFC 9180 Section 4): the public key of `sk`. + fn pk(sk: &Self::PrivateKey) -> Self::PublicKey; + + /// Whether `DeriveKeyPair` (RFC 9180 Section 7.1.3) is the X25519 and X448 form, `sk = + /// LabeledExpand(dkp_prk, "sk", "", Nsk)` with no rejection loop, which is the only form + /// [`DHKEM::derive_key_pair`] implements: a group whose form is the NIST curves' candidate + /// loop sets this `false` and gets a compile error from `derive_key_pair` instead of a wrong + /// key. + const DERIVE_KEY_PAIR_BY_EXPAND: bool; + /// `DH(skX, pkY)` (RFC 9180 Section 4.1) into `out`, including the validation of its output + /// that RFC 9180 Section 7.1.4 requires for the group. A validation failure is an `Err`, with + /// `out` left zeroized. + fn dh_into( + sk: &Self::PrivateKey, + pk: &Self::PublicKey, + out: &mut Secret<[u8; N_DH]>, + ) -> Result<(), KeyAgreementError>; + + /// `SerializePublicKey(pkX)` (RFC 9180 Section 7.1.1). + fn serialize_public_key(pk: &Self::PublicKey) -> [u8; N_PK]; + + /// `DeserializePublicKey(pkXm)` (RFC 9180 Section 7.1.1). + fn deserialize_public_key(pkm: &[u8; N_PK]) -> Result; +} + +/// The DHKEM of RFC 9180 Section 4.1 over the group `G`, without the optional `AuthEncap` and +/// `AuthDecap`. +/// +/// The const parameters are `G`'s sizes (see [`DHKEMParams`]) plus `N_SECRET`, the Nsecret of RFC +/// 9180 Section 7.1, which must equal the output length of [`DHKEMParams::KDFHash`] (Section 4.1: +/// "the size Nsecret of the KEM shared secret is equal to the output length of the hash function +/// underlying the KDF"). That, and the other relations between the parameters, are checked when +/// a DHKEM is used, so DHKEM(X25519, HKDF-SHA256) with its Nsecret of 32 compiles: +/// +/// ``` +/// use bouncycastle_core::traits::KEMPrivateKey; +/// use bouncycastle_ed::x25519::{X25519, X25519PrivateKey}; +/// use bouncycastle_hpke::dhkem::DHKEM; +/// +/// let sk = >::from_bytes(&[7u8; 32]).unwrap(); +/// let _ = DHKEM::::decap(&[9u8; 32], &sk); +/// ``` +/// +/// and with an Nsecret that is not SHA-256's output length it does not: +/// +/// ```compile_fail +/// use bouncycastle_core::traits::KEMPrivateKey; +/// use bouncycastle_ed::x25519::{X25519, X25519PrivateKey}; +/// use bouncycastle_hpke::dhkem::DHKEM; +/// +/// let sk = >::from_bytes(&[7u8; 32]).unwrap(); +/// let _ = DHKEM::::decap(&[9u8; 32], &sk); +/// ``` +pub struct DHKEM +{ + _group: PhantomData, +} + +impl< + G: DHKEMParams, + const N_PK: usize, + const N_SK: usize, + const N_DH: usize, + const N_SECRET: usize, +> DHKEM +{ + /// `suite_id = concat("KEM", I2OSP(kem_id, 2))` (RFC 9180 Section 4.1). + const SUITE_ID: [u8; 5] = { + let kem_id = G::KEM_ID.to_be_bytes(); + [b'K', b'E', b'M', kem_id[0], kem_id[1]] + }; + + /// Checked when a DHKEM is instantiated, so a wrong set of const parameters fails to compile. + const PARAMS_CHECK: () = { + let nh = ::OUTPUT_LEN; + assert!(N_SECRET == nh, "Nsecret must equal the output length of the KDF's hash"); + assert!(nh <= MAX_NH, "the KDF's hash output is longer than MAX_NH"); + // HKDF-Expand's L, which here is Nsecret or Nsk, must be at most 255*HashLen (RFC 5869 + // Section 2.3), and fit the two bytes of I2OSP(L, 2) in LabeledExpand. + assert!(N_SK <= 255 * nh && N_SK <= 0xFFFF, "Nsk is too long for HKDF-Expand"); + // RFC 9180 Section 7.1, Table 2 pairs each group with a hash of at least twice its + // strength (X25519 with SHA-256, P-384 with SHA-384, P-521 and X448 with SHA-512); a + // shorter hash would cap the KEM's secret below the group. + assert!( + 8 * nh >= 2 * strength_bits(G::MAX_SECURITY_STRENGTH), + "the KDF's hash must offer twice the group's strength" + ); + }; + + /// `Encap(pkR)` (RFC 9180 Section 4.1), with the ephemeral key pair generated from `rng`: + /// the shared secret, a [`KeyType::CryptographicRandom`] key at the group's security + /// strength, into `shared_secret` and `enc`, the ephemeral public key, into `enc`, each + /// zeroized first and left so on the error path. + /// + /// # Errors + /// * [`KEMError::RNGError`] if `rng`'s security strength is below the group's. + /// * [`KEMError::InvalidPublicKey`] if `pk_r` fails the group's validation (RFC 9180 Section + /// 7.1.4), such as an all-zero X25519 output. + pub fn encap_rng_out( + pk_r: &G::PublicKey, + rng: &mut dyn RNG, + enc: &mut [u8; N_PK], + shared_secret: &mut KeyMaterial, + ) -> Result<(), KEMError> { + let () = Self::PARAMS_CHECK; + enc.fill(0); + shared_secret.zeroize(); + if rng.security_strength() < G::MAX_SECURITY_STRENGTH { + return Err(RNGError::SecurityStrengthInsufficientForAlgorithm.into()); + } + // skE, pkE = GenerateKeyPair(); skE stays in the group's frame and is wiped there. + let mut dh = Secret::<[u8; N_DH]>::new(); + G::with_generated_key_pair(rng, |pk_e, sk_e| { + // dh = DH(skE, pkR) + G::dh_into(sk_e, pk_r, &mut dh)?; + // enc = SerializePublicKey(pkE) + *enc = G::serialize_public_key(pk_e); + Ok(()) + })? + .map_err(|_: KeyAgreementError| { + KEMError::InvalidPublicKey("The recipient's public key failed validation") + })?; + // pkRm = SerializePublicKey(pkR); kem_context = concat(enc, pkRm) + let pk_rm = G::serialize_public_key(pk_r); + // shared_secret = ExtractAndExpand(dh, kem_context) + Self::extract_and_expand_into(&*dh, &[&*enc, &pk_rm], shared_secret); + Ok(()) + } + + /// [`Self::encap_rng_out`] returning the pair by value: the shared secret is moved out of + /// this frame, which does not wipe its source; prefer the `_out` form where that matters. + pub fn encap_rng( + pk_r: &G::PublicKey, + rng: &mut dyn RNG, + ) -> Result<(KeyMaterial, [u8; N_PK]), KEMError> { + let mut enc = [0u8; N_PK]; + let mut shared_secret = KeyMaterial::new(); + Self::encap_rng_out(pk_r, rng, &mut enc, &mut shared_secret)?; + Ok((shared_secret, enc)) + } + + /// `Decap(enc, skR)` (RFC 9180 Section 4.1): the shared secret, a + /// [`KeyType::CryptographicRandom`] key at the group's security strength, into + /// `shared_secret`, zeroized first and left so on the error path. + /// + /// # Errors + /// [`KEMError::DecapsulationFailed`] if `enc` does not deserialize or the DH output fails the + /// group's validation. + pub fn decap_out( + enc: &[u8; N_PK], + sk_r: &G::PrivateKey, + shared_secret: &mut KeyMaterial, + ) -> Result<(), KEMError> { + let () = Self::PARAMS_CHECK; + shared_secret.zeroize(); + // pkE = DeserializePublicKey(enc) + let pk_e = G::deserialize_public_key(enc).map_err(|_| KEMError::DecapsulationFailed)?; + // dh = DH(skR, pkE) + let mut dh = Secret::<[u8; N_DH]>::new(); + G::dh_into(sk_r, &pk_e, &mut dh).map_err(|_| KEMError::DecapsulationFailed)?; + // pkRm = SerializePublicKey(pk(skR)); kem_context = concat(enc, pkRm) + let pk_rm = G::serialize_public_key(&G::pk(sk_r)); + // shared_secret = ExtractAndExpand(dh, kem_context) + Self::extract_and_expand_into(&*dh, &[enc, &pk_rm], shared_secret); + Ok(()) + } + + /// [`Self::decap_out`] returning the shared secret by value: it is moved out of this frame, + /// which does not wipe its source; prefer the `_out` form where that matters. + pub fn decap( + enc: &[u8; N_PK], + sk_r: &G::PrivateKey, + ) -> Result, KEMError> { + let mut shared_secret = KeyMaterial::new(); + Self::decap_out(enc, sk_r, &mut shared_secret)?; + Ok(shared_secret) + } + + /// `DeriveKeyPair(ikm)` (RFC 9180 Section 7.1.3), for groups whose private key is the byte string + /// itself, such as X25519 and X448. + /// + /// Section 7.1.3: "the ikm parameter given to DeriveKeyPair() SHOULD have length at least Nsk, + /// and SHOULD have at least Nsk bytes of entropy". This requires `ikm` to be at least Nsk bytes, + /// of [`KeyType::Seed`] or [`KeyType::CryptographicRandom`], and at least the group's security + /// strength. + /// + /// # Errors + /// + /// [`KEMError::KeyGenError`] if `ikm` does not meet those requirements. + /// + /// A group that declares the expand form ([`DHKEMParams::DERIVE_KEY_PAIR_BY_EXPAND`]) + /// compiles: + /// + /// ``` + /// # use bouncycastle_core::errors::{KEMError, KeyAgreementError}; + /// # use bouncycastle_core::key_material::{KeyMaterial256, KeyType}; + /// # use bouncycastle_core::security_strength::SecurityStrength; + /// # use bouncycastle_core::traits::{Algorithm, RNG}; + /// # use bouncycastle_ed::x25519::{X25519, X25519PrivateKey, X25519PublicKey}; + /// # use bouncycastle_hpke::dhkem::{DHKEM, DHKEMParams}; + /// # use bouncycastle_utils::secret::Secret; + /// # type Sk = X25519PrivateKey; + /// # type Pk = X25519PublicKey; + /// # // X25519 with its DeriveKeyPair form as a parameter. + /// # struct Group; + /// # impl Algorithm for Group { + /// # const ALG_NAME: &'static str = "test group"; + /// # const MAX_SECURITY_STRENGTH: SecurityStrength = SecurityStrength::_128bit; + /// # } + /// # impl DHKEMParams<32, 32, 32> for Group { + /// # type PublicKey = Pk; + /// # type PrivateKey = Sk; + /// # type KDFHash = >::KDFHash; + /// # const KEM_ID: u16 = 0x0020; + /// # const DERIVE_KEY_PAIR_BY_EXPAND: bool = B; + /// # fn with_generated_key_pair( + /// # rng: &mut dyn RNG, + /// # f: impl FnOnce(&Pk, &Sk) -> R, + /// # ) -> Result { + /// # >::with_generated_key_pair(rng, f) + /// # } + /// # fn private_key_from_bytes(sk: &[u8; 32]) -> Sk { + /// # >::private_key_from_bytes(sk) + /// # } + /// # fn pk(sk: &Sk) -> Pk { + /// # >::pk(sk) + /// # } + /// # fn dh_into( + /// # sk: &Sk, + /// # pk: &Pk, + /// # out: &mut Secret<[u8; 32]>, + /// # ) -> Result<(), KeyAgreementError> { + /// # >::dh_into(sk, pk, out) + /// # } + /// # fn serialize_public_key(pk: &Pk) -> [u8; 32] { + /// # >::serialize_public_key(pk) + /// # } + /// # fn deserialize_public_key(pkm: &[u8; 32]) -> Result { + /// # >::deserialize_public_key(pkm) + /// # } + /// # } + /// let ikm = KeyMaterial256::from_bytes_as_type(&[7u8; 32], KeyType::Seed).unwrap(); + /// let _ = DHKEM::, 32, 32, 32, 32>::derive_key_pair(&ikm); + /// ``` + /// + /// and one that does not is refused at compile time: + /// + /// ```compile_fail + /// # use bouncycastle_core::errors::{KEMError, KeyAgreementError}; + /// # use bouncycastle_core::key_material::{KeyMaterial256, KeyType}; + /// # use bouncycastle_core::security_strength::SecurityStrength; + /// # use bouncycastle_core::traits::{Algorithm, RNG}; + /// # use bouncycastle_ed::x25519::{X25519, X25519PrivateKey, X25519PublicKey}; + /// # use bouncycastle_hpke::dhkem::{DHKEM, DHKEMParams}; + /// # use bouncycastle_utils::secret::Secret; + /// # type Sk = X25519PrivateKey; + /// # type Pk = X25519PublicKey; + /// # // X25519 with its DeriveKeyPair form as a parameter. + /// # struct Group; + /// # impl Algorithm for Group { + /// # const ALG_NAME: &'static str = "test group"; + /// # const MAX_SECURITY_STRENGTH: SecurityStrength = SecurityStrength::_128bit; + /// # } + /// # impl DHKEMParams<32, 32, 32> for Group { + /// # type PublicKey = Pk; + /// # type PrivateKey = Sk; + /// # type KDFHash = >::KDFHash; + /// # const KEM_ID: u16 = 0x0020; + /// # const DERIVE_KEY_PAIR_BY_EXPAND: bool = B; + /// # fn with_generated_key_pair( + /// # rng: &mut dyn RNG, + /// # f: impl FnOnce(&Pk, &Sk) -> R, + /// # ) -> Result { + /// # >::with_generated_key_pair(rng, f) + /// # } + /// # fn private_key_from_bytes(sk: &[u8; 32]) -> Sk { + /// # >::private_key_from_bytes(sk) + /// # } + /// # fn pk(sk: &Sk) -> Pk { + /// # >::pk(sk) + /// # } + /// # fn dh_into( + /// # sk: &Sk, + /// # pk: &Pk, + /// # out: &mut Secret<[u8; 32]>, + /// # ) -> Result<(), KeyAgreementError> { + /// # >::dh_into(sk, pk, out) + /// # } + /// # fn serialize_public_key(pk: &Pk) -> [u8; 32] { + /// # >::serialize_public_key(pk) + /// # } + /// # fn deserialize_public_key(pkm: &[u8; 32]) -> Result { + /// # >::deserialize_public_key(pkm) + /// # } + /// # } + /// let ikm = KeyMaterial256::from_bytes_as_type(&[7u8; 32], KeyType::Seed).unwrap(); + /// let _ = DHKEM::, 32, 32, 32, 32>::derive_key_pair(&ikm); + /// ``` + pub fn derive_key_pair( + ikm: &impl KeyMaterialTrait, + ) -> Result<(G::PublicKey, G::PrivateKey), KEMError> { + let () = Self::PARAMS_CHECK; + const { + assert!( + G::DERIVE_KEY_PAIR_BY_EXPAND, + "derive_key_pair implements only the X25519 / X448 form of RFC 9180 Section 7.1.3" + ) + }; + + if !(ikm.key_type() == KeyType::Seed || ikm.key_type() == KeyType::CryptographicRandom) + || ikm.key_len() < N_SK + { + return Err(KEMError::KeyGenError( + "ikm must be at least Nsk bytes and KeyType::Seed or KeyType::CryptographicRandom.", + )); + } + if ikm.security_strength() < G::MAX_SECURITY_STRENGTH { + return Err(KEMError::KeyGenError( + "ikm SecurityStrength must match algorithm security strength", + )); + } + + // dkp_prk = LabeledExtract("", "dkp_prk", ikm) + let mut dkp_prk = KeyMaterial::::new(); + Self::labeled_extract_into(LABEL_DKP_PRK, ikm.ref_to_bytes(), &mut dkp_prk); + // sk = LabeledExpand(dkp_prk, "sk", "", Nsk) + let mut sk = Secret::<[u8; N_SK]>::new(); + Self::labeled_expand(&dkp_prk, LABEL_SK, &[], &mut *sk); + let sk = G::private_key_from_bytes(&sk); + // return (sk, pk(sk)) + Ok((G::pk(&sk), sk)) + } + + /// `ExtractAndExpand(dh, kem_context)` (RFC 9180 Section 4.1) into `out`, zeroized first, + /// with `kem_context` given as the parts it is the concatenation of. The output is labelled + /// as a full-entropy key at the group's strength: it is HKDF output, and so pseudorandom, + /// unlike the DH output it is derived from. + // #[inline(never)]: inlined into encap_rng, its two HMAC states were allocated for the whole + // encapsulation, on top of the key generation that sets the peak. + #[inline(never)] + fn extract_and_expand_into(dh: &[u8], kem_context: &[&[u8]], out: &mut KeyMaterial) { + out.zeroize(); + // eae_prk = LabeledExtract("", "eae_prk", dh) + let mut eae_prk = KeyMaterial::::new(); + Self::labeled_extract_into(LABEL_EAE_PRK, dh, &mut eae_prk); + // shared_secret = LabeledExpand(eae_prk, "shared_secret", kem_context, Nsecret) + let mut shared_secret = Secret::<[u8; N_SECRET]>::new(); + Self::labeled_expand(&eae_prk, LABEL_SHARED_SECRET, kem_context, &mut *shared_secret); + + // An all-zero output, one HMAC value in 2^(8 * Nsecret), is typed Zeroized by the buffer + // and carries no strength; that is not an error, as for an all-zero agreement output. + // Nothing else can fail: Nsecret bytes fit the buffer. + match out.set_bytes_as_type(&*shared_secret, KeyType::CryptographicRandom) { + Ok(()) | Err(KeyMaterialError::ActingOnZeroizedKey) => {} + Err(_) => unreachable!("Nsecret bytes fit a KeyMaterial"), + } + if out.key_type() == KeyType::CryptographicRandom { + // Cannot fail: N_SECRET >= 32 bytes is enough for any strength, and the inferred + // strength (set from the length) is lowered, never raised. + out.set_security_strength(G::MAX_SECURITY_STRENGTH) + .expect("the group's strength is within Nsecret's"); + } + } + + /// `LabeledExtract("", label, ikm)` (RFC 9180 Section 4), where `Extract` is HKDF-Extract + /// (RFC 5869 Section 2.2) over [`DHKEMParams::KDFHash`]. Every call in a DHKEM has an empty salt. + /// + /// Writes the PRK into `prk` as a MAC key, ready for [`Self::labeled_expand`]: into the + /// caller's buffer rather than returned, so that it is not moved. + fn labeled_extract_into(label: &[u8], ikm: &[u8], prk: &mut KeyMaterial) { + // PRK = HMAC-Hash(salt, IKM) + // An empty salt is an empty HMAC key. RFC 5869 Section 2.2 says an absent salt "is set to a + // string of HashLen zeros", which is the same HMAC key, as HMAC zero-pads its key. + // Cannot fail: an empty KeyMaterial is Zeroized, which HMAC accepts as a weak key. + let salt = + HmacKey::::from_key_material_allow_weak(&KeyMaterial::<0>::new()).unwrap(); + // HMAC through its hazmat halves, as HKDF's expand loop runs it: the role wants the tag + // length as a const, which a hash-generic KDF does not have. + let mut hmac = hmac_hazmat::inner_state(&salt); + // labeled_ikm = concat("HPKE-v1", suite_id, label, ikm) + // Deviation from the RFC: the parts of labeled_ikm are absorbed by HMAC in order rather than + // concatenated first. + hmac.do_update(HPKE_VERSION_LABEL); + hmac.do_update(&Self::SUITE_ID); + hmac.do_update(label); + hmac.do_update(ikm); + + let mut bytes = Secret::<[u8; MAX_NH]>::new(); + // The whole tag: the buffer is the hash output length, at most MAX_NH (PARAMS_CHECK). + let nh = ::OUTPUT_LEN; + let nh = hmac_hazmat::finish_out(&salt, &mut hmac, &mut bytes[..nh]); + // nh <= MAX_NH bytes fit a KeyMaterial; the one way this fails is an all-zero + // PRK (one HMAC output in 2^(8 * nh)), which the buffer types Zeroized and the expand's + // HmacKey then refuses. Not reachable in practice; a panic is the right report for it. + prk.set_bytes_as_type(&bytes[..nh], KeyType::MACKey) + .expect("an all-zero PRK, one HMAC output in 2^(8 * nh)"); + } + + /// `LabeledExpand(prk, label, info, L)` (RFC 9180 Section 4), where `Expand` is HKDF-Expand (RFC + /// 5869 Section 2.3) over [`DHKEMParams::KDFHash`], `L` is `out.len()`, and `info` is given as + /// the parts it is the concatenation of. + fn labeled_expand(prk: &KeyMaterial, label: &[u8], info: &[&[u8]], out: &mut [u8]) { + let nh = ::OUTPUT_LEN; + // L is Nsecret or Nsk, which PARAMS_CHECK bounds by 255*HashLen and by 0xFFFF. + debug_assert!(out.len() <= 255 * nh && out.len() <= 0xFFFF); + let l = (out.len() as u16).to_be_bytes(); + + // T(0) = empty string (zero length) + let mut t = Secret::<[u8; MAX_NH]>::new(); + let mut t_len = 0; + // N = ceil(L/HashLen); T = T(1) | T(2) | ... | T(N); OKM = first L octets of T + // The PRK keys one HmacKey for the whole expand, so that its pads are scheduled once + // and not once per block. It refuses an + // all-zero PRK, one HMAC output in 2^(8 * nh); see labeled_extract_into. + let key = HmacKey::::from_key_material(prk) + .expect("an all-zero PRK, one HMAC output in 2^(8 * nh)"); + // Each chunk of `out` is one T(i), the last one truncated. + for (i, okm_chunk) in out.chunks_mut(nh).enumerate() { + // T(i) = HMAC-Hash(PRK, T(i-1) | info | i), with info = labeled_info + let mut hmac = hmac_hazmat::inner_state(&key); + hmac.do_update(&t[..t_len]); + // labeled_info = concat(I2OSP(L, 2), "HPKE-v1", suite_id, label, info) + // Deviation from the RFC: absorbed in parts, as in labeled_extract_into. + hmac.do_update(&l); + hmac.do_update(HPKE_VERSION_LABEL); + hmac.do_update(&Self::SUITE_ID); + hmac.do_update(label); + for part in info { + hmac.do_update(part); + } + // i <= N <= 255, since L <= 255*HashLen. + hmac.do_update(&[(i + 1) as u8]); + // The whole tag: the buffer is the hash output length (PARAMS_CHECK). + t_len = hmac_hazmat::finish_out(&key, &mut hmac, &mut t[..nh]); + okm_chunk.copy_from_slice(&t[..okm_chunk.len()]); + } + } +} + +// `strength_bits` is private and only read by the compile-time `PARAMS_CHECK`, which `cargo +// mutants` cannot see fail, so its table is pinned here as well. +#[cfg(test)] +mod tests { + use super::strength_bits; + use bouncycastle_core::security_strength::SecurityStrength; + + #[test] + fn strength_bits_is_the_strength_as_a_bit_count() { + assert_eq!(strength_bits(SecurityStrength::None), 0); + assert_eq!(strength_bits(SecurityStrength::_112bit), 112); + assert_eq!(strength_bits(SecurityStrength::_128bit), 128); + assert_eq!(strength_bits(SecurityStrength::_192bit), 192); + assert_eq!(strength_bits(SecurityStrength::_256bit), 256); + } +} diff --git a/crypto/hpke/src/lib.rs b/crypto/hpke/src/lib.rs new file mode 100644 index 00000000..d33df3f9 --- /dev/null +++ b/crypto/hpke/src/lib.rs @@ -0,0 +1,81 @@ +//! Building blocks of Hybrid Public Key Encryption (HPKE), as specified in RFC 9180. +//! +//! This is a utility crate and is not intended to be used directly. It provides +//! [`dhkem::DHKEM`] -- the DH-Based KEM of RFC 9180 Section 4.1, generic over any Diffie-Hellman +//! group that implements [`dhkem::DHKEMParams`], the extension point through which a group +//! declares its keys, its DH operation and the KDF that the DHKEM pairs it with. Each group's crate +//! implements that trait and exposes the result through the +//! [`EncapsulatingKey`](bouncycastle_core::kem_key::EncapsulatingKey) and +//! [`DecapsulatingKey`](bouncycastle_core::kem_key::DecapsulatingKey) roles on its own key types. +//! +//! For example: +//! +//! | KEM | kem_id | Exposed as | +//! |----------------------------|--------|----------------------------------------------------------------| +//! | DHKEM(X25519, HKDF-SHA256) | 0x0020 | `bouncycastle_ed::x25519::{X25519PublicKey, X25519PrivateKey}` | +//! +//! The KDF is HKDF over the hash named by [`dhkem::DHKEMParams::KDFHash`], computed on +//! [`HMAC`](bouncycastle_hmac::HMAC) as RFC 5869 defines it, so any hash that +//! [`HMAC`](bouncycastle_hmac::HMAC) supports can be used. +//! +//! The rest of HPKE (the key schedule, AEAD encryption and secret export of RFC 9180 Section 5) is +//! not yet implemented. +//! +//! # Usage Examples +//! +//! A group's keys are the usual way in (`pk.encaps(&mut rng, ())` on an X25519 public key). The +//! generic DHKEM can also be driven directly, here as DHKEM(X25519, HKDF-SHA256): +//! +//! ``` +//! use bouncycastle_core::key_material::{KeyMaterial, KeyMaterialTrait}; +//! use bouncycastle_ed::x25519::{X25519, keygen}; +//! use bouncycastle_hpke::dhkem::DHKEM; +//! use bouncycastle_rng::HashDRBG_SHA512; +//! +//! // Npk = Nsk = Ndh = Nsecret = 32 (RFC 9180 Section 7.1). +//! type Kem = DHKEM; +//! +//! let mut rng = HashDRBG_SHA512::new_from_os(); +//! let (pk_r, sk_r) = keygen(&mut rng).unwrap(); +//! +//! // The sender: the shared secret, and `enc` to send. +//! let mut enc = [0u8; 32]; +//! let mut sender_secret = KeyMaterial::<32>::new(); +//! Kem::encap_rng_out(&pk_r, &mut rng, &mut enc, &mut sender_secret)?; +//! +//! // The recipient recovers the same shared secret from `enc`. +//! let mut recipient_secret = KeyMaterial::<32>::new(); +//! Kem::decap_out(&enc, &sk_r, &mut recipient_secret)?; +//! assert_eq!(sender_secret.ref_to_bytes(), recipient_secret.ref_to_bytes()); +//! # Ok::<(), bouncycastle_core::errors::KEMError>(()) +//! ``` +//! +//! # Memory Usage +//! +//! [`dhkem::DHKEM`] is a set of functions over its group, with no state of its own, no lookup +//! tables and no heap allocation. A call's working memory is on the stack: the DH output (Ndh +//! bytes), one PRK and one HKDF-Expand block, each sized for the largest hash of RFC 9180 +//! Section 7.2 (64 bytes), and the HMAC states of the extract and the expand. The per-call stack +//! figures for the X25519 instantiation are in `bouncycastle_ed::x25519`'s Memory Usage table. +//! +//! # 🚨 Security Considerations 🚨 +//! +//! * [`dhkem::DHKEMParams::dh_into`] must perform the group's validation of the DH output (RFC 9180 +//! Section 7.1.4), such as rejecting the all-zero X25519 output. [`dhkem::DHKEM`] relies on it to +//! reject unusable public keys. +//! * [`dhkem::DHKEM::derive_key_pair`] is deterministic: the key pair is only as secret as the +//! input keying material. +//! * The DH output, the PRKs and the derived values live in `Secret`s here and are wiped at the +//! end of their lifetime, and the `_out` forms write into the caller's buffers. What is not +//! reached: the by-value `encap_rng`, `decap` and `derive_key_pair` move their result out of +//! the frame that built it, and the HMAC the KDF runs leaves its inner and outer chaining states +//! and the SHA-256 message schedule of `prk XOR opad` on the dead stack below this crate's +//! frames, from which the PRK is recoverable; that residue is `hmac`'s and `sha2`'s, and the +//! PRK keys one `HmacKey` per expand so it is left once. +//! * The crate's own source is `no_std`, but `bouncycastle-core` and `hmac` are not yet. + +#![no_std] +#![forbid(unsafe_code)] +#![forbid(missing_docs)] + +pub mod dhkem; diff --git a/crypto/hpke/tests/dhkem_x25519_tests.rs b/crypto/hpke/tests/dhkem_x25519_tests.rs new file mode 100644 index 00000000..93b2045e --- /dev/null +++ b/crypto/hpke/tests/dhkem_x25519_tests.rs @@ -0,0 +1,113 @@ +//! The generic DHKEM driven directly, over X25519 as its group, against RFC 9180 Appendix +//! A.1.1 (Base) and A.1.2 (PSK): `Encap` with the vector's ephemeral key, `Decap`, +//! `DeriveKeyPair`, the `_out` forms, and the buffers left zeroized on a small-order key. The +//! ed crate's own suites cover the same KEM through the key roles and the other four sets. + +use bouncycastle_core::errors::KEMError; +use bouncycastle_core::key_material::{KeyMaterial, KeyMaterial256, KeyMaterialTrait, KeyType}; +use bouncycastle_core::security_strength::SecurityStrength; +use bouncycastle_core::traits::{KeyAgreementPrivateKey, KeyAgreementPublicKey}; +use bouncycastle_ed::x25519::{ + DHKEM_SS_LEN, POINT_LEN, SCALAR_LEN, X25519, X25519PrivateKey, X25519PublicKey, +}; +use bouncycastle_hex as hex; +use bouncycastle_hpke::dhkem::DHKEM; +use bouncycastle_rng::FixedSeedRNG; + +type X25519DHKEM = DHKEM; + +/// RFC 9180 Appendix A.1.1 (Base) and A.1.2 (PSK): ikmR, pkRm, skRm, skEm, enc, shared_secret. +const VECTORS: [[&str; 6]; 2] = [ + [ + "6db9df30aa07dd42ee5e8181afdb977e538f5e1fec8a06223f33f7013e525037", + "3948cfe0ad1ddb695d780e59077195da6c56506b027329794ab02bca80815c4d", + "4612c550263fc8ad58375df3f557aac531d26850903e55a9f23f21d8534e8ac8", + "52c4a758a802cd8b936eceea314432798d5baf2d7e9235dc084ab1b9cfa2f736", + "37fda3567bdbd628e88668c3c8d7e97d1d1253b6d4ea6d44c150f741f1bf4431", + "fe0e18c9f024ce43799ae393c7e8fe8fce9d218875e8227b0187c04e7d2ea1fc", + ], + [ + "d4a09d09f575fef425905d2ab396c1449141463f698f8efdb7accfaff8995098", + "9fed7e8c17387560e92cc6462a68049657246a09bfa8ade7aefe589672016366", + "c5eb01eb457fe6c6f57577c5413b931550a162c71a03ac8d196babbd4e5ce0fd", + "463426a9ffb42bb17dbe6044b9abd1d4e4d95f9041cef0e99d7824eef2b6f588", + "0ad0950d9fb9588e59690b74f1237ecdf1d775cd60be2eca57af5a4b0471c91b", + "727699f009ffe3c076315019c69648366b69171439bd7dd0807743bde76986cd", + ], +]; + +fn decode_32(s: &str) -> [u8; 32] { + hex::decode(s).unwrap().try_into().unwrap() +} + +#[test] +fn encap_and_decap_match_the_vectors_by_value_and_through_the_out_forms() { + for (i, [ikm_r, pk_rm, sk_rm, sk_em, enc, shared_secret]) in VECTORS.iter().enumerate() { + let pk_r = X25519PublicKey::from_bytes(&decode_32(pk_rm)).unwrap(); + let sk_r = X25519PrivateKey::from_bytes(&decode_32(sk_rm)).unwrap(); + + let (ss, enc_got) = + X25519DHKEM::encap_rng(&pk_r, &mut FixedSeedRNG::new(decode_32(sk_em))).unwrap(); + assert_eq!(enc_got, decode_32(enc), "vector {i}: enc"); + assert_eq!(ss.ref_to_bytes(), decode_32(shared_secret), "vector {i}: shared_secret"); + assert_eq!(ss.key_type(), KeyType::CryptographicRandom); + assert_eq!(ss.security_strength(), SecurityStrength::_128bit); + + let mut enc_out = [0xFFu8; POINT_LEN]; + let mut ss_out = + KeyMaterial::::from_bytes_as_type(&[0xFF; 32], KeyType::Seed).unwrap(); + X25519DHKEM::encap_rng_out( + &pk_r, + &mut FixedSeedRNG::new(decode_32(sk_em)), + &mut enc_out, + &mut ss_out, + ) + .unwrap(); + assert_eq!(enc_out, decode_32(enc), "vector {i}: enc (out form)"); + assert!(ss_out.equals(&ss), "vector {i}: shared_secret (out form)"); + + let ss_dec = X25519DHKEM::decap(&decode_32(enc), &sk_r).unwrap(); + assert!(ss_dec.equals(&ss), "vector {i}: decap"); + let mut ss_dec_out = + KeyMaterial::::from_bytes_as_type(&[0xFF; 32], KeyType::Seed).unwrap(); + X25519DHKEM::decap_out(&decode_32(enc), &sk_r, &mut ss_dec_out).unwrap(); + assert!(ss_dec_out.equals(&ss), "vector {i}: decap (out form)"); + + let ikm = KeyMaterial256::from_bytes_as_type(&decode_32(ikm_r), KeyType::Seed).unwrap(); + let (pk, sk) = X25519DHKEM::derive_key_pair(&ikm).unwrap(); + assert_eq!(pk.encode(), decode_32(pk_rm), "vector {i}: DeriveKeyPair pk"); + assert!(sk == sk_r, "vector {i}: DeriveKeyPair sk"); + } +} + +#[test] +fn a_small_order_recipient_key_is_refused_and_the_buffers_left_zeroized() { + let zero_pk = X25519PublicKey::from_bytes(&[0u8; POINT_LEN]).unwrap(); + let mut enc = [0xFFu8; POINT_LEN]; + let mut ss = + KeyMaterial::::from_bytes_as_type(&[0xFF; 32], KeyType::Seed).unwrap(); + assert!(matches!( + X25519DHKEM::encap_rng_out(&zero_pk, &mut FixedSeedRNG::new([0x5A; 64]), &mut enc, &mut ss), + Err(KEMError::InvalidPublicKey(_)) + )); + assert_eq!(enc, [0u8; POINT_LEN]); + assert_eq!(ss.key_type(), KeyType::Zeroized); + + let sk = X25519PrivateKey::from_bytes(&decode_32(VECTORS[0][2])).unwrap(); + let mut ss = + KeyMaterial::::from_bytes_as_type(&[0xFF; 32], KeyType::Seed).unwrap(); + assert!(matches!( + X25519DHKEM::decap_out(&[0u8; POINT_LEN], &sk, &mut ss), + Err(KEMError::DecapsulationFailed) + )); + assert_eq!(ss.key_type(), KeyType::Zeroized); +} + +/// An RNG below the group's strength is refused before any key is drawn. +#[test] +fn encap_refuses_a_weak_rng() { + let pk_r = X25519PublicKey::from_bytes(&decode_32(VECTORS[0][1])).unwrap(); + let mut weak = FixedSeedRNG::new([0x5A; 64]); + weak.set_security_strength(SecurityStrength::_112bit); + assert!(matches!(X25519DHKEM::encap_rng(&pk_r, &mut weak), Err(KEMError::RNGError(_)))); +} diff --git a/mem_usage_benches/Cargo.toml b/mem_usage_benches/Cargo.toml index 5e141a3e..0dc0b109 100644 --- a/mem_usage_benches/Cargo.toml +++ b/mem_usage_benches/Cargo.toml @@ -51,6 +51,10 @@ path = "src/bench_ascon_mem_usage.rs" name = "bench_tdes_mem_usage" path = "src/bench_tdes_mem_usage.rs" +[[bin]] +name = "bench_x25519_mem_usage" +path = "src/bench_x25519_mem_usage.rs" + [[bin]] name = "bench_blake2_mem_usage" path = "src/bench_blake2_mem_usage.rs" diff --git a/mem_usage_benches/src/bench_x25519_mem_usage.rs b/mem_usage_benches/src/bench_x25519_mem_usage.rs new file mode 100644 index 00000000..ef97d4ee --- /dev/null +++ b/mem_usage_benches/src/bench_x25519_mem_usage.rs @@ -0,0 +1,170 @@ +//! The purpose of this binary is to perform a single run of the primitive under test so that +//! its peak memory usage can be measured with: +//! +//! ```text +//! valgrind --tool=massif --heap=no --stacks=yes -- target/release/bench_x25519_mem_usage > /dev/null +//! +//! ms_print massif.out.* +//! ``` +//! +//! Make sure you build in release mode! +//! +//! Note: print!() forces the compiler not to optimize away the actual code. The name of the bench +//! goes to stderr so that the junk on stdout can be piped to /dev/null. +//! +//! Main is at the bottom, controls which bench is actually run. +//! +//! The keys and the ciphertext are the published test vectors (RFC 7748 Section 6.1 and RFC 9180 +//! Appendix A.1.1), hard-coded so that no keygen runs in a bench that does not measure it. + +#![allow(dead_code)] +#![allow(unused_imports)] + +use bouncycastle::core::agreement_key::AgreementKey; +use bouncycastle::core::kem_key::{DecapsulatingKey, EncapsulatingKey}; +use bouncycastle::core::key_material::{KeyMaterial256, KeyMaterialTrait, KeyType}; +use bouncycastle::core::traits::{KeyAgreementPrivateKey, KeyAgreementPublicKey}; +use bouncycastle::ed::x25519::{X25519PrivateKey, X25519PublicKey, keygen_from_seed}; +use bouncycastle::rng::HashDRBG_SHA512; + +/// Runs the operation under test in its own stack frame, with the key already loaded by the +/// caller. +/// +/// `#[inline(never)]` matters here too: the bench functions inline the whole operation, so +/// without this boundary the operation's frame would be allocated on entry to the bench and the +/// key-load helper's frame would stack on top of it, reporting their sum instead of their max. +/// The closure returns nothing, so no result is copied back across the boundary. +#[inline(never)] +fn measure(f: impl FnOnce()) { + f() +} + +/// This exists so I can use /usr/bin/time to measure the base memory footprint of the harness. +fn bench_do_nothing() { + eprintln!("DoNothing"); + + print!("{}", 1 + 1); +} + +/// This prints the in-memory size of the public and private key structs. +fn print_struct_sizes() { + println!("X25519PublicKey: {}", size_of::()); + println!("X25519PrivateKey: {}", size_of::()); +} + +/// Loads RFC 7748 Section 6.1's Alice private key. `#[inline(never)]` so its byte array and decode +/// temporaries are popped before the operation runs. +#[inline(never)] +fn load_alice_sk() -> X25519PrivateKey { + X25519PrivateKey::from_bytes(&[ + 0x77, 0x07, 0x6d, 0x0a, 0x73, 0x18, 0xa5, 0x7d, 0x3c, 0x16, 0xc1, 0x72, 0x51, 0xb2, 0x66, + 0x45, 0xdf, 0x4c, 0x2f, 0x87, 0xeb, 0xc0, 0x99, 0x2a, 0xb1, 0x77, 0xfb, 0xa5, 0x1d, 0xb9, + 0x2c, 0x2a, + ]) + .unwrap() +} + +/// Loads RFC 7748 Section 6.1's Bob public key. +#[inline(never)] +fn load_bob_pk() -> X25519PublicKey { + X25519PublicKey::from_bytes(&[ + 0xde, 0x9e, 0xdb, 0x7d, 0x7b, 0x7d, 0xc1, 0xb4, 0xd3, 0x5b, 0x61, 0xc2, 0xec, 0xe4, 0x35, + 0x37, 0x3f, 0x83, 0x43, 0xc8, 0x5b, 0x78, 0x67, 0x4d, 0xad, 0xfc, 0x7e, 0x14, 0x6f, 0x88, + 0x2b, 0x4f, + ]) + .unwrap() +} + +/// Loads RFC 9180 Appendix A.1.1's skRm. +#[inline(never)] +fn load_sk_rm() -> X25519PrivateKey { + X25519PrivateKey::from_bytes(&[ + 0x46, 0x12, 0xc5, 0x50, 0x26, 0x3f, 0xc8, 0xad, 0x58, 0x37, 0x5d, 0xf3, 0xf5, 0x57, 0xaa, + 0xc5, 0x31, 0xd2, 0x68, 0x50, 0x90, 0x3e, 0x55, 0xa9, 0xf2, 0x3f, 0x21, 0xd8, 0x53, 0x4e, + 0x8a, 0xc8, + ]) + .unwrap() +} + +/// Loads RFC 9180 Appendix A.1.1's pkRm. +#[inline(never)] +fn load_pk_rm() -> X25519PublicKey { + X25519PublicKey::from_bytes(&[ + 0x39, 0x48, 0xcf, 0xe0, 0xad, 0x1d, 0xdb, 0x69, 0x5d, 0x78, 0x0e, 0x59, 0x07, 0x71, 0x95, + 0xda, 0x6c, 0x56, 0x50, 0x6b, 0x02, 0x73, 0x29, 0x79, 0x4a, 0xb0, 0x2b, 0xca, 0x80, 0x81, + 0x5c, 0x4d, + ]) + .unwrap() +} + +/// Key generation from a seed (RFC 7748 Section 6.1's Alice private key): one fixed-base scalar +/// multiplication. The seed is the input, so it is built in the bench body. +fn bench_x25519_keygen() { + eprintln!("X25519/KeyGen"); + + let seed = KeyMaterial256::from_bytes_as_type( + &[ + 0x77, 0x07, 0x6d, 0x0a, 0x73, 0x18, 0xa5, 0x7d, 0x3c, 0x16, 0xc1, 0x72, 0x51, 0xb2, + 0x66, 0x45, 0xdf, 0x4c, 0x2f, 0x87, 0xeb, 0xc0, 0x99, 0x2a, 0xb1, 0x77, 0xfb, 0xa5, + 0x1d, 0xb9, 0x2c, 0x2a, + ], + KeyType::Seed, + ) + .unwrap(); + + measure(|| { + let (pk, _sk) = keygen_from_seed(&seed).unwrap(); + print!("{:x?}", pk.encode()); + }); +} + +/// Key agreement: one variable-base scalar multiplication and the all-zero check. +fn bench_x25519_key_agreement() { + eprintln!("X25519/KeyAgreement"); + + let sk = load_alice_sk(); + let pk = load_bob_pk(); + measure(|| { + let k = sk.agree(&pk, ()).unwrap(); + print!("{:x?}", k.ref_to_bytes()); + }); +} + +/// DHKEM(X25519, HKDF-SHA256) encapsulation, including the OS-seeded DRBG that generates the +/// ephemeral key, since that is part of what an encapsulation costs. +fn bench_x25519_encaps() { + eprintln!("X25519/Encaps"); + + let pk = load_pk_rm(); + measure(|| { + let (ss, ct) = pk.encaps(&mut HashDRBG_SHA512::new_from_os(), ()).unwrap(); + print!("{:x?}", ss); + print!("{:x?}", ct); + }); +} + +/// DHKEM(X25519, HKDF-SHA256) decapsulation of RFC 9180 Appendix A.1.1's enc. +fn bench_x25519_decaps() { + eprintln!("X25519/Decaps"); + + let ct: [u8; 32] = [ + 0x37, 0xfd, 0xa3, 0x56, 0x7b, 0xdb, 0xd6, 0x28, 0xe8, 0x86, 0x68, 0xc3, 0xc8, 0xd7, 0xe9, + 0x7d, 0x1d, 0x12, 0x53, 0xb6, 0xd4, 0xea, 0x6d, 0x44, 0xc1, 0x50, 0xf7, 0x41, 0xf1, 0xbf, + 0x44, 0x31, + ]; + + let sk = load_sk_rm(); + measure(|| { + let ss = sk.decaps(&ct, ()).unwrap(); + print!("{:x?}", ss); + }); +} + +fn main() { + // print_struct_sizes() + // bench_do_nothing() + bench_x25519_keygen() + // bench_x25519_key_agreement() + // bench_x25519_encaps() + // bench_x25519_decaps() +} diff --git a/mem_usage_benches/src/lib.rs b/mem_usage_benches/src/lib.rs index d5b0cf26..e3f87cc7 100644 --- a/mem_usage_benches/src/lib.rs +++ b/mem_usage_benches/src/lib.rs @@ -24,3 +24,4 @@ mod bench_sm2_mem_usage; mod bench_sm3_mem_usage; mod bench_sm4_mem_usage; mod bench_tdes_mem_usage; +mod bench_x25519_mem_usage; diff --git a/src/lib.rs b/src/lib.rs index fd041857..b87025b4 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -13,10 +13,12 @@ pub use bouncycastle_core as core; pub use bouncycastle_ec as ec; pub use bouncycastle_eccdh as eccdh; pub use bouncycastle_ecdsa as ecdsa; +pub use bouncycastle_ed as ed; pub use bouncycastle_factory as factory; pub use bouncycastle_hex as hex; pub use bouncycastle_hkdf as hkdf; pub use bouncycastle_hmac as hmac; +pub use bouncycastle_hpke as hpke; pub use bouncycastle_mldsa as mldsa; pub use bouncycastle_mldsa_lowmemory as mldsa_lowmemory; pub use bouncycastle_mlkem as mlkem;