Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
59 commits
Select commit Hold shift + click to select a range
4e5d288
Some incremental progress towards 25519
ounsworth Aug 20, 2026
71183d8
updated cargo.toml
ounsworth Aug 24, 2026
b455d0c
progress towards 25519
ounsworth Aug 25, 2026
ba80ce5
progress on 25519
ounsworth Aug 26, 2026
a0aeddf
progress on 25519
ounsworth Aug 26, 2026
cf2677b
progress on 25519
ounsworth Aug 26, 2026
d2cf4f1
Adding tests and a todo list for finishing this feature.
Oct 29, 2026
c467db0
Progress on x25519
Oct 30, 2026
f182bb1
Progress on x25519
Oct 30, 2026
07b6629
Progress on x25519
Oct 30, 2026
6b1df21
Progress on x25519
Oct 30, 2026
d806822
Progress on x25519
Oct 30, 2026
acfbad7
cargo mutants pass for x25519
Oct 30, 2026
6df5b79
Implemented core::traits::KeyAgreement for X25519. And started writin…
Oct 30, 2026
a467ea3
Impl'd KEMEncapsulator / KEMDecapsulator for x25519 via the new crypt…
Oct 30, 2026
313ca10
Added key encoding / decoding routines for x25519.
Oct 30, 2026
87f0ea1
Added core-test-framework/key_agreement.rs
Oct 30, 2026
5e54dde
Added a cli for x25519
Oct 30, 2026
ab7997c
Re-ran mutants. Nothing new found.
Oct 30, 2026
85045e8
Added perf and memory benches.
Oct 30, 2026
a338dbf
Split the ladder into two functions, which lowers x25519 stack usage …
Oct 31, 2026
f0f45f7
Docs and style tweaks.
Oct 31, 2026
270fac8
DONE X25519!!
Oct 31, 2026
11a04ec
doc tweak
Oct 31, 2026
78ab66f
Suggestions from Nicola Tuveri: have a separate type for the DerivedK…
Oct 31, 2026
a2744b3
Removed the X25519PublicKey -> X25519DerivedKey promotion from the pu…
Oct 31, 2026
ad1556a
Merge release/0.1.4alpha c2db8107 into feature/x25519
dghgit Nov 7, 2026
6294a82
hpke, ed, cli: the adaptations to release/0.1.4alpha
dghgit Nov 7, 2026
7978b63
Merge release/0.1.4alpha f3fdb8bf (PR #192: KEM roles on the key obje…
dghgit Nov 8, 2026
18ecfc1
ed, hpke, cli: X25519's DHKEM on the KEM key roles of PR #192
dghgit Nov 8, 2026
a82c0fb
Merge release/0.1.4alpha 7cb54e02 into feature/x25519: the KEM-era ti…
dghgit Nov 11, 2026
02ac864
ed: X25519 on the release's key agreement roles, with an HKDF-SHA256 …
dghgit Nov 11, 2026
a0094fe
hpke: the DHKEM's HMAC runs through the hazmat halves
dghgit Nov 11, 2026
ca630ed
cli: the x25519 subcommand agrees through the key agreement role
dghgit Nov 11, 2026
1387c45
mem_usage_benches: the X25519 harness agrees through the role
dghgit Nov 11, 2026
a5b5faa
release notes: X25519 and the hpke crate
dghgit Nov 11, 2026
98d06e2
Merge release/0.1.4alpha f87a69e1 (fix/ec-keygen squash: one key pair…
dghgit Nov 11, 2026
fc84c80
ed: the field element wipes itself, normalize is total, keys and K ar…
dghgit Nov 12, 2026
c9f5e71
hpke: out-forms for the DHKEM, one HmacKey per expand, a strength che…
dghgit Nov 12, 2026
4c04b86
cli: the x25519 private key's encoding lives in a Secret, and the hel…
dghgit Nov 12, 2026
88ec18d
release notes: the X25519 entry names the RFC 9180 sets the tests use
dghgit Nov 12, 2026
7afeed1
Merge release/0.1.4alpha (f213c9e4) into feature/x25519
dghgit Nov 13, 2026
2b4b29e
ed: the stack table is re-measured on the roles, after the field elem…
dghgit Nov 13, 2026
626e00b
core: KdfParams derives into the caller's buffer, derive_out
dghgit Nov 14, 2026
ed80cb6
eccdh: the pairing's derivation is KdfParams::derive_out
dghgit Nov 14, 2026
9839cbd
ed: the pairing derives through KdfParams::derive_out, a salted test,…
dghgit Nov 14, 2026
212d8c8
hpke: encap_rng_out, decap_out and extract_and_expand_into have one s…
dghgit Nov 14, 2026
3e3b532
release notes: the HKDF pairings are over KdfParams<HkdfDescription<S…
dghgit Nov 14, 2026
aab8e0b
ed: the inversion's two powers are written into the caller's buffers
dghgit Nov 14, 2026
68a5b76
ed: keygen_out and keygen_from_seed_out draw the scalar into a key th…
dghgit Nov 14, 2026
5015f1f
cli: x25519 keygen draws the key into one it holds
dghgit Nov 14, 2026
1110935
ed: the longest-key test pins HKDF_SHA256_MAX_LEN at 255 * 32
dghgit Nov 14, 2026
52099d6
Merge release/0.1.4alpha (b398a3fb) into feature/x25519
dghgit Nov 16, 2026
0183e8c
hpke: the ephemeral key and the PRKs are not moved, and the parameter…
dghgit Nov 16, 2026
6cb504c
ed: the KEM names DHKEM, an unfilled key is refused, and the low-orde…
dghgit Nov 16, 2026
4f5b8e7
release notes: the DHKEM marker
dghgit Nov 16, 2026
d6e5913
cli: x25519 writes its secrets as hex through a wiped buffer and drop…
dghgit Nov 16, 2026
ef309c1
ed: the docs say what is wiped without the review's history
dghgit Nov 16, 2026
3a6fdac
hpke: the crate docs gain Usage Examples and Memory Usage
dghgit Nov 16, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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" }
Expand Down Expand Up @@ -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
Expand Down
5 changes: 3 additions & 2 deletions QUALITY_AND_STYLE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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<T>` 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;
Expand Down
10 changes: 9 additions & 1 deletion alpha_0.1.4_release_notes.md
Original file line number Diff line number Diff line change
Expand Up @@ -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<HkdfDescription<SHA256>, 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

Expand Down Expand Up @@ -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<HKDF_SHA256, LEN>` on the P-256 keys;
`AgreementKey` role over `()`, and `ECCDHP256_HKDF_SHA256` over `KdfParams<HkdfDescription<SHA256>, 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
Expand Down
37 changes: 37 additions & 0 deletions cli/src/helpers/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand Down Expand Up @@ -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| {
Expand Down Expand Up @@ -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}");
}
}
}
26 changes: 26 additions & 0 deletions cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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<String>,

#[arg(long)]
/// The public key file (binary, or hex under --hex-input) for check-consistency, agree and encaps
pkfile: Option<String>,

#[arg(long)]
/// The ciphertext file (binary, or hex under --hex-input): written by encaps, read by decaps.
ctfile: Option<String>,

#[arg(short)]
/// Output in hex format.
x: bool,
},
}

fn main() {
Expand Down Expand Up @@ -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")
}
Expand Down
158 changes: 158 additions & 0 deletions cli/src/x25519_cmd.rs
Original file line number Diff line number Diff line change
@@ -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<String>,
pkfile: &Option<String>,
ctfile: &Option<String>,
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<String>) -> Vec<u8> {
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<String>) -> 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);
})
}
Loading
Loading