lib.rs
cdk-rsx/crates/crypto/fourq/src/lib.rs
1//! Research-only portable64 cofactor ECDH on FourQ.2//!3//! Upstream is unmaintained. This port has no production security or compiled4//! constant-time qualification. Variable-time public-point decoding/encoding5//! remains. Raw shared-coordinate output requires a transcript-bound KDF before6//! use; ECDH does not authenticate peers or provide forward secrecy by itself.7#![no_std]89pub const RESEARCH_ONLY: bool = true;10pub const KEY_BYTES: usize = 32;1112#[derive(Clone, Copy, Debug, Eq, PartialEq)]13pub enum Error {14 ZeroSecret,15 InvalidPublicKey,16 WeakSharedSecret,17}1819unsafe extern "C" {20 fn rsx_fourq_validate(bytes: *const u8) -> i32;21 fn rsx_fourq_public(secret: *const u8, out: *mut u8) -> i32;22 fn rsx_fourq_agree(secret: *const u8, peer: *const u8, out: *mut u8) -> i32;23}2425/// Caller-owned uniformly random scalar bytes. No Debug, Clone or implicit RNG.26pub struct SecretKey([u8; KEY_BYTES]);27#[derive(Clone, Copy, Debug, Eq, PartialEq)]28pub struct PublicKey([u8; KEY_BYTES]);29pub struct SharedSecret([u8; KEY_BYTES]);3031fn wipe(bytes: &mut [u8]) {32 for byte in bytes {33 // SAFETY: valid exclusive bytes; volatile prevents DSE.34 unsafe { core::ptr::write_volatile(byte, 0) };35 }36 core::sync::atomic::compiler_fence(core::sync::atomic::Ordering::SeqCst);37}38impl Drop for SecretKey {39 fn drop(&mut self) {40 wipe(&mut self.0)41 }42}43impl Drop for SharedSecret {44 fn drop(&mut self) {45 wipe(&mut self.0)46 }47}4849impl SecretKey {50 pub fn from_bytes(bytes: [u8; KEY_BYTES]) -> Result<Self, Error> {51 if bytes.iter().all(|b| *b == 0) {52 return Err(Error::ZeroSecret);53 }54 Ok(Self(bytes))55 }56 pub fn public_key(&self) -> Result<PublicKey, Error> {57 let mut out = [0; KEY_BYTES];58 // SAFETY: exact live regions; adapter copies to aligned bounded scratch.59 if unsafe { rsx_fourq_public(self.0.as_ptr(), out.as_mut_ptr()) } == 1 {60 Ok(PublicKey(out))61 } else {62 Err(Error::WeakSharedSecret)63 }64 }65 pub fn agree(&self, peer: &PublicKey) -> Result<SharedSecret, Error> {66 let mut out = SharedSecret([0; KEY_BYTES]);67 // SAFETY: owned valid buffers, no retained pointers or heap allocations.68 if unsafe { rsx_fourq_agree(self.0.as_ptr(), peer.0.as_ptr(), out.0.as_mut_ptr()) } == 1 {69 Ok(out)70 } else {71 Err(Error::WeakSharedSecret)72 }73 }74}75impl PublicKey {76 /// Requires canonical compressed encoding and a non-neutral curve point.77 /// ECDH additionally clears the cofactor and rejects a neutral result.78 pub fn from_bytes(bytes: [u8; KEY_BYTES]) -> Result<Self, Error> {79 // SAFETY: exact live region, copied before all native word accesses.80 if unsafe { rsx_fourq_validate(bytes.as_ptr()) } == 1 {81 Ok(Self(bytes))82 } else {83 Err(Error::InvalidPublicKey)84 }85 }86 pub fn as_bytes(&self) -> &[u8; KEY_BYTES] {87 &self.088 }89}90impl SharedSecret {91 pub fn as_bytes(&self) -> &[u8; KEY_BYTES] {92 &self.093 }94}9596#[cfg(test)]97mod tests {98 use super::*;99 unsafe extern "C" {100 fn rsx_fourq_upstream_doubling_test() -> i32;101 }102 #[test]103 fn upstream_known_answer() {104 assert_eq!(unsafe { rsx_fourq_upstream_doubling_test() }, 1);105 }106 #[test]107 fn symmetric_ecdh_and_checked_encodings() {108 for i in 1..=64u8 {109 let a = SecretKey::from_bytes([i; 32]).unwrap();110 let b = SecretKey::from_bytes([i ^ 0xa5; 32]).unwrap();111 let ap = a.public_key().unwrap();112 let bp = b.public_key().unwrap();113 assert_eq!(PublicKey::from_bytes(*ap.as_bytes()).unwrap(), ap);114 assert_eq!(115 a.agree(&bp).unwrap().as_bytes(),116 b.agree(&ap).unwrap().as_bytes()117 );118 let mut malformed = *bp.as_bytes();119 malformed[15] |= 128;120 assert_eq!(121 PublicKey::from_bytes(malformed).err(),122 Some(Error::InvalidPublicKey)123 );124 }125 assert_eq!(126 SecretKey::from_bytes([0; 32]).err(),127 Some(Error::ZeroSecret)128 );129 let mut neutral = [0; 32];130 neutral[0] = 1;131 assert!(PublicKey::from_bytes(neutral).is_err());132 assert!(PublicKey::from_bytes([255; 32]).is_err());133 let mut field_p = [255; 32];134 field_p[15] = 127;135 field_p[16..].fill(0);136 assert!(PublicKey::from_bytes(field_p).is_err());137 field_p[..16].fill(0);138 field_p[16..].fill(255);139 field_p[31] = 127;140 assert!(PublicKey::from_bytes(field_p).is_err());141 // A canonical small-order point may parse, but never yields a secret.142 if let Ok(small_order) = PublicKey::from_bytes([0; 32]) {143 let scalar = SecretKey::from_bytes([23; 32]).unwrap();144 assert!(scalar.agree(&small_order).is_err());145 }146 }147}