use curve25519_dalek::constants::EIGHT_TORSION;
use curve25519_dalek::edwards::EdwardsPoint;
use rand_core::CryptoRng;
use zeroize::ZeroizeOnDrop;
use crate::{LEN, to_representative};
pub const MAX_ATTEMPTS: usize = 64;
#[derive(ZeroizeOnDrop)]
pub struct HiddenKey {
secret: [u8; LEN],
#[zeroize(skip)]
point: [u8; LEN],
#[zeroize(skip)]
representative: [u8; LEN],
}
impl HiddenKey {
#[must_use]
pub const fn point(&self) -> &[u8; LEN] {
&self.point
}
#[must_use]
pub const fn representative(&self) -> &[u8; LEN] {
&self.representative
}
#[must_use]
pub const fn secret_bytes(&self) -> &[u8; LEN] {
&self.secret
}
#[cfg(feature = "x25519")]
#[must_use]
pub fn static_secret(&self) -> x25519_dalek::StaticSecret {
x25519_dalek::StaticSecret::from(self.secret)
}
#[cfg(feature = "x25519")]
#[must_use]
pub fn diffie_hellman(&self, peer: &x25519_dalek::PublicKey) -> x25519_dalek::SharedSecret {
self.static_secret().diffie_hellman(peer)
}
}
impl core::fmt::Debug for HiddenKey {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.debug_struct("HiddenKey")
.field("point", &Hex4(&self.point))
.field("representative", &Hex4(&self.representative))
.finish_non_exhaustive()
}
}
struct Hex4<'a>(&'a [u8; LEN]);
impl core::fmt::Debug for Hex4<'_> {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
for byte in &self.0[..4] {
write!(f, "{byte:02x}")?;
}
f.write_str("…")
}
}
#[must_use]
pub fn generate<R: CryptoRng + ?Sized>(rng: &mut R) -> Option<HiddenKey> {
for _ in 0..MAX_ATTEMPTS {
let mut sk = [0u8; LEN];
rng.fill_bytes(&mut sk);
let torsion = EIGHT_TORSION[usize::from(sk[0] & 7)];
let mut tweak = [0u8; 1];
rng.fill_bytes(&mut tweak);
let dirty: EdwardsPoint = EdwardsPoint::mul_base_clamped(sk) + torsion;
let point = dirty.to_montgomery().to_bytes();
if let Some(representative) = to_representative(&point, tweak[0]) {
return Some(HiddenKey {
secret: sk,
point,
representative,
});
}
}
None
}
#[cfg(test)]
mod tests {
use super::*;
use crate::from_representative;
use rand::Rng;
#[test]
fn generation_succeeds_and_round_trips() {
let mut rng = rand::rng();
for _ in 0..64 {
let e = generate(&mut rng).expect("generate");
assert_eq!(
from_representative(e.representative()),
*e.point(),
"decoding a representative must recover the exact point that was encoded"
);
}
}
#[test]
fn high_bits_are_randomised() {
let mut rng = rand::rng();
let mut seen = [false; 4];
for _ in 0..256 {
let e = generate(&mut rng).expect("generate");
seen[usize::from(e.representative()[31] >> 6)] = true;
}
assert!(
seen.iter().all(|s| *s),
"all four values of the top two bits must occur: {seen:?}"
);
}
#[test]
fn decoding_ignores_the_high_bits() {
let mut rng = rand::rng();
let e = generate(&mut rng).expect("generate");
let mut alt = *e.representative();
alt[31] ^= 0xc0;
assert_eq!(
from_representative(&alt),
from_representative(e.representative())
);
}
#[test]
fn about_half_of_candidates_are_representable() {
let mut rng = rand::rng();
let mut representable = 0;
const TRIALS: usize = 512;
for _ in 0..TRIALS {
let mut sk = [0u8; 32];
rng.fill_bytes(&mut sk);
let torsion = EIGHT_TORSION[usize::from(sk[0] & 7)];
let point = (EdwardsPoint::mul_base_clamped(sk) + torsion)
.to_montgomery()
.to_bytes();
if to_representative(&point, 0).is_some() {
representable += 1;
}
}
let pct = representable * 100 / TRIALS;
assert!(
(35..=65).contains(&pct),
"representable rate {pct}% is implausibly far from 50%"
);
}
#[test]
fn debug_does_not_print_the_secret() {
use std::format;
let e = generate(&mut rand::rng()).expect("generate");
let rendered = format!("{e:?}");
let secret_hex: std::string::String = e
.secret_bytes()
.iter()
.map(|b| format!("{b:02x}"))
.collect();
assert!(
!rendered.contains(&secret_hex[..8]),
"Debug leaked secret material: {rendered}"
);
}
#[cfg(feature = "x25519")]
#[test]
fn torsion_does_not_disturb_the_shared_secret() {
use x25519_dalek::{PublicKey, StaticSecret};
let mut rng = rand::rng();
for _ in 0..32 {
let hidden = generate(&mut rng).expect("generate");
let mut peer_sk = [0u8; 32];
rng.fill_bytes(&mut peer_sk);
let peer = StaticSecret::from(peer_sk);
let ours = hidden.diffie_hellman(&PublicKey::from(&peer));
let theirs = peer.diffie_hellman(&PublicKey::from(*hidden.point()));
assert_eq!(
ours.as_bytes(),
theirs.as_bytes(),
"the torsion component must be annihilated by the peer's clamped scalar"
);
}
}
}