Skip to main content

umbera_core/
primitives.rs

1// umbera_core::primitives — 1:1 crypto primitives (KMP-prep phase 6).
2//
3// These move the personal (1:1) message/file/backup crypto OFF the JVM-only
4// BouncyCastle provider and into this shared Rust core, so Android (uniffi→Kotlin)
5// today and iOS (uniffi→Swift) later run the SAME battle-tested implementations.
6//
7// Only mature RustCrypto/dalek crates are used — no hand-rolled primitives, no
8// weakened parameters. Where an algorithm is a fixed standard (Argon2id, AES-GCM,
9// HKDF, X25519, secp256k1/RFC6979, Ed25519, SHA-256/PBKDF2), the output is
10// byte-identical to the previous BouncyCastle output, which the golden vectors
11// assert cross-implementation. PQ algorithms (ML-KEM / ML-DSA) are migrated to the
12// FINAL FIPS standard and their new byte formats are re-captured + documented.
13
14use aes_gcm::{aead::Aead, aead::Payload, Aes256Gcm, KeyInit, Nonce};
15use argon2::{Algorithm, Argon2, Params, Version};
16use hmac::Hmac;
17use k256::ecdsa::signature::hazmat::{PrehashSigner, PrehashVerifier};
18use k256::ecdsa::{Signature as EcdsaSignature, SigningKey, VerifyingKey};
19use sha2::{Digest, Sha256};
20
21/// Errors surfaced across the FFI. Mapped to a Kotlin/Swift exception by UniFFI.
22#[derive(Debug, thiserror::Error, uniffi::Error)]
23pub enum PrimitiveError {
24    #[error("aead: {0}")]
25    Aead(String),
26    #[error("key: {0}")]
27    Key(String),
28}
29
30fn to_arr32(v: &[u8], what: &str) -> Result<[u8; 32], PrimitiveError> {
31    v.try_into()
32        .map_err(|_| PrimitiveError::Key(format!("{what} must be 32 bytes, got {}", v.len())))
33}
34
35/// Argon2id key derivation. Fixed parameters, matching the previous BouncyCastle
36/// call exactly so existing backups (and the golden vector) verify unchanged:
37///   Algorithm = Argon2id, Version = 0x13 (19), m = 65536 KiB (64 MiB),
38///   t = 3 iterations, p = 4 lanes, output = `key_length` bytes.
39///
40/// CONTRACT (iOS must reproduce): password is UTF-8 bytes, salt is raw bytes,
41/// no associated data, no secret key.
42#[uniffi::export]
43pub fn argon2id_derive(password: String, salt: Vec<u8>, key_length: u32) -> Result<Vec<u8>, PrimitiveError> {
44    let params = Params::new(65536, 3, 4, Some(key_length as usize))
45        .map_err(|e| PrimitiveError::Key(format!("argon2 params: {e}")))?;
46    let a2 = Argon2::new(Algorithm::Argon2id, Version::V0x13, params);
47    let mut out = vec![0u8; key_length as usize];
48    a2.hash_password_into(password.as_bytes(), &salt, &mut out)
49        .map_err(|e| PrimitiveError::Key(format!("argon2id: {e}")))?;
50    Ok(out)
51}
52
53/// SHA-256 digest. Fixed standard → byte-identical to the previous
54/// BouncyCastle SHA256Digest output.
55#[uniffi::export]
56pub fn sha256(data: Vec<u8>) -> Vec<u8> {
57    let mut h = Sha256::new();
58    h.update(&data);
59    h.finalize().to_vec()
60}
61
62/// PBKDF2-HMAC-SHA256. Matches the previous BouncyCastle
63/// PKCS5S2ParametersGenerator(SHA256Digest) exactly: password is UTF-8 bytes,
64/// `iterations` rounds, `key_length` output bytes. Used for the zero-knowledge
65/// password hash the server verifies, so the output MUST stay byte-stable.
66#[uniffi::export]
67pub fn pbkdf2_hmac_sha256(password: String, salt: Vec<u8>, iterations: u32, key_length: u32) -> Result<Vec<u8>, PrimitiveError> {
68    let mut out = vec![0u8; key_length as usize];
69    pbkdf2::pbkdf2::<Hmac<Sha256>>(password.as_bytes(), &salt, iterations, &mut out)
70        .map_err(|e| PrimitiveError::Key(format!("pbkdf2: {e}")))?;
71    Ok(out)
72}
73
74/// HKDF-SHA256 (RFC 5869) extract-then-expand. Byte-identical to the previous
75/// BouncyCastle HKDFBytesGenerator(SHA256Digest).
76#[uniffi::export]
77pub fn hkdf_sha256(ikm: Vec<u8>, salt: Vec<u8>, info: Vec<u8>, length: u32) -> Result<Vec<u8>, PrimitiveError> {
78    let hk = hkdf::Hkdf::<Sha256>::new(Some(&salt), &ikm);
79    let mut out = vec![0u8; length as usize];
80    hk.expand(&info, &mut out)
81        .map_err(|e| PrimitiveError::Key(format!("hkdf: {e}")))?;
82    Ok(out)
83}
84
85/// HMAC-SHA256 (RFC 2104). Same output as javax.crypto.Mac("HmacSHA256") for
86/// any key length. Used for the file/chunk key schedule in FileEncryption.
87#[uniffi::export]
88pub fn hmac_sha256(key: Vec<u8>, data: Vec<u8>) -> Vec<u8> {
89    use hmac::Mac as _;
90    let mut m = <Hmac<Sha256> as hmac::KeyInit>::new_from_slice(&key)
91        .expect("HMAC-SHA256 accepts keys of any length");
92    m.update(&data);
93    m.finalize().into_bytes().to_vec()
94}
95
96/// HKDF-SHA256 EXPAND-ONLY (RFC 5869 §2.3): `prk` is used directly as the
97/// pseudorandom key, no extract step. Byte-identical to BC's
98/// `HKDFParameters.skipExtractParameters(prk, info)`.
99#[uniffi::export]
100pub fn hkdf_sha256_expand(prk: Vec<u8>, info: Vec<u8>, length: u32) -> Result<Vec<u8>, PrimitiveError> {
101    let hk = hkdf::Hkdf::<Sha256>::from_prk(&prk)
102        .map_err(|e| PrimitiveError::Key(format!("hkdf-expand prk: {e}")))?;
103    let mut out = vec![0u8; length as usize];
104    hk.expand(&info, &mut out)
105        .map_err(|e| PrimitiveError::Key(format!("hkdf-expand: {e}")))?;
106    Ok(out)
107}
108
109/// AES-256-GCM encrypt. Returns `ciphertext || tag(16)`, exactly the layout the
110/// JCA `Cipher("AES/GCM/NoPadding").doFinal` produced, so the wire format is
111/// unchanged. `aad` empty = no associated data (identical to a null AAD in JCA).
112#[uniffi::export]
113pub fn aes256_gcm_encrypt(key: Vec<u8>, iv: Vec<u8>, plaintext: Vec<u8>, aad: Vec<u8>) -> Result<Vec<u8>, PrimitiveError> {
114    let cipher = Aes256Gcm::new_from_slice(&key).map_err(|e| PrimitiveError::Aead(e.to_string()))?;
115    // Typed error, not a panic: the wire format always uses 96-bit nonces, and
116    // a hostile peer must not be able to panic the FFI with a bad IV length.
117    if iv.len() != 12 {
118        return Err(PrimitiveError::Aead(format!("iv must be 12 bytes, got {}", iv.len())));
119    }
120    let nonce = &Nonce::try_from(iv.as_slice()).map_err(|_| PrimitiveError::Aead("iv must be 12 bytes".into()))?;
121    cipher
122        .encrypt(nonce, Payload { msg: &plaintext, aad: &aad })
123        .map_err(|e| PrimitiveError::Aead(e.to_string()))
124}
125
126/// AES-256-GCM decrypt. Consumes `ciphertext || tag(16)` (the JCA layout) and
127/// fails (like JCA's AEADBadTagException) on tag/AAD mismatch.
128#[uniffi::export]
129pub fn aes256_gcm_decrypt(key: Vec<u8>, iv: Vec<u8>, ciphertext_with_tag: Vec<u8>, aad: Vec<u8>) -> Result<Vec<u8>, PrimitiveError> {
130    let cipher = Aes256Gcm::new_from_slice(&key).map_err(|e| PrimitiveError::Aead(e.to_string()))?;
131    // Typed error, not a panic — the IV arrives from the wire (hostile input).
132    if iv.len() != 12 {
133        return Err(PrimitiveError::Aead(format!("iv must be 12 bytes, got {}", iv.len())));
134    }
135    let nonce = &Nonce::try_from(iv.as_slice()).map_err(|_| PrimitiveError::Aead("iv must be 12 bytes".into()))?;
136    cipher
137        .decrypt(nonce, Payload { msg: &ciphertext_with_tag, aad: &aad })
138        .map_err(|e| PrimitiveError::Aead(e.to_string()))
139}
140
141/// X25519 public-key derivation (RFC 7748 scalar mult by the basepoint).
142/// Raw 32-byte keys. The bare `x25519()` function clamps the scalar on use,
143/// exactly like BouncyCastle's X25519PrivateKeyParameters.generatePublicKey(),
144/// so the derived public key is byte-identical.
145#[uniffi::export]
146pub fn x25519_public_key(private_key: Vec<u8>) -> Result<Vec<u8>, PrimitiveError> {
147    let sk = to_arr32(&private_key, "x25519 private key")?;
148    Ok(x25519_dalek::x25519(sk, x25519_dalek::X25519_BASEPOINT_BYTES).to_vec())
149}
150
151/// X25519 ECDH (RFC 7748). Raw scalar multiplication, byte-identical to
152/// BouncyCastle's X25519Agreement. Low-order-point rejection and the all-zero
153/// shared-secret check stay in the Kotlin caller (crypto/X25519.kt), which
154/// validates BEFORE calling in — same defense-in-depth as before.
155#[uniffi::export]
156pub fn x25519_shared_secret(private_key: Vec<u8>, public_key: Vec<u8>) -> Result<Vec<u8>, PrimitiveError> {
157    let sk = to_arr32(&private_key, "x25519 private key")?;
158    let pk = to_arr32(&public_key, "x25519 public key")?;
159    Ok(x25519_dalek::x25519(sk, pk).to_vec())
160}
161
162/// secp256k1 public-key derivation. Input is the raw 32-byte scalar, output is
163/// the SEC1 UNCOMPRESSED point (65 bytes, 0x04 || X || Y) — the exact encoding
164/// BC's `q.getEncoded(false)` produced. Errors (instead of panicking) if the
165/// scalar is zero or >= the group order, which is also how a caller-side
166/// rejection-sampling keygen detects the ~2^-128 invalid draw.
167#[uniffi::export]
168pub fn secp256k1_public_key(private_key: Vec<u8>) -> Result<Vec<u8>, PrimitiveError> {
169    let sk = SigningKey::from_slice(&private_key)
170        .map_err(|e| PrimitiveError::Key(format!("secp256k1 private key: {e}")))?;
171    Ok(sk.verifying_key().to_sec1_point(false).as_bytes().to_vec())
172}
173
174/// secp256k1 ECDSA over a 32-byte prehash. RFC 6979 deterministic nonce
175/// (HMAC-SHA-256) + low-S normalization (BIP-62) — identical to the previous
176/// BC ECDSASigner(HMacDSAKCalculator(SHA256Digest)) + normalizeS path, so the
177/// signature is byte-exact (proven by the golden vector). Returns r||s (64 bytes,
178/// both fixed 32-byte big-endian).
179#[uniffi::export]
180pub fn secp256k1_sign_hash(hash: Vec<u8>, private_key: Vec<u8>) -> Result<Vec<u8>, PrimitiveError> {
181    if hash.len() != 32 {
182        return Err(PrimitiveError::Key(format!("hash must be 32 bytes, got {}", hash.len())));
183    }
184    let sk = SigningKey::from_slice(&private_key)
185        .map_err(|e| PrimitiveError::Key(format!("secp256k1 private key: {e}")))?;
186    let sig: EcdsaSignature = sk
187        .sign_prehash(&hash)
188        .map_err(|e| PrimitiveError::Key(format!("secp256k1 sign: {e}")))?;
189    // k256 already emits low-S; normalize defensively so the invariant is explicit.
190    let sig = sig.normalize_s();
191    Ok(sig.to_bytes().to_vec())
192}
193
194/// secp256k1 ECDSA verify over a 32-byte prehash. `signature` is r||s (64 bytes),
195/// `public_key` is any SEC1 point encoding (compressed or uncompressed — BC's
196/// decodePoint accepted both). High-S signatures are normalized before verifying,
197/// matching BC's verifier which imposed no low-S policy. Any parse failure
198/// returns false, exactly like the previous Kotlin catch-all.
199#[uniffi::export]
200pub fn secp256k1_verify_hash(hash: Vec<u8>, signature: Vec<u8>, public_key: Vec<u8>) -> bool {
201    if hash.len() != 32 {
202        return false;
203    }
204    let Ok(vk) = VerifyingKey::from_sec1_bytes(&public_key) else { return false };
205    let Ok(sig) = EcdsaSignature::from_slice(&signature) else { return false };
206    let sig = sig.normalize_s();
207    vk.verify_prehash(&hash, &sig).is_ok()
208}
209
210/// Ed25519 signature verification (RFC 8032). Used for the Key Transparency
211/// STH and the signed federation server directory — the client only VERIFIES;
212/// signing keys live server-side. Cofactorless verification with canonical-S
213/// rejection, same as BC's Ed25519Signer. Any malformed key/signature returns
214/// false, matching the previous Kotlin catch-all/length-check behavior.
215#[uniffi::export]
216pub fn ed25519_verify(public_key: Vec<u8>, message: Vec<u8>, signature: Vec<u8>) -> bool {
217    let Ok(pk_arr): Result<[u8; 32], _> = public_key.as_slice().try_into() else { return false };
218    let Ok(sig_arr): Result<[u8; 64], _> = signature.as_slice().try_into() else { return false };
219    let Ok(vk) = ed25519_dalek::VerifyingKey::from_bytes(&pk_arr) else { return false };
220    let sig = ed25519_dalek::Signature::from_bytes(&sig_arr);
221    use ed25519_dalek::Verifier;
222    vk.verify(&message, &sig).is_ok()
223}
224
225/// Ed25519 public key from a 32-byte seed (RFC 8032 §5.1.5).
226///
227/// AUDIT K-2 — the inbox READ capability. A self-inbox rendezvous id is derived
228/// from data the anonymous directory publishes, so anyone can address it (that is
229/// how a stranger sends you a contact request) and, until this key existed, anyone
230/// could also READ it. The account publishes this public half; only the holder of
231/// the seed can sign a fetch. The seed is derived on-device and never leaves it.
232#[uniffi::export]
233pub fn ed25519_public_from_seed(seed: Vec<u8>) -> Result<Vec<u8>, PrimitiveError> {
234    let seed_arr = to_arr32(&seed, "ed25519 seed")?;
235    let sk = ed25519_dalek::SigningKey::from_bytes(&seed_arr);
236    Ok(sk.verifying_key().to_bytes().to_vec())
237}
238
239/// Ed25519 signature over [message] with the 32-byte seed (audit K-2).
240#[uniffi::export]
241pub fn ed25519_sign(message: Vec<u8>, seed: Vec<u8>) -> Result<Vec<u8>, PrimitiveError> {
242    let seed_arr = to_arr32(&seed, "ed25519 seed")?;
243    let sk = ed25519_dalek::SigningKey::from_bytes(&seed_arr);
244    use ed25519_dalek::Signer;
245    Ok(sk.sign(&message).to_bytes().to_vec())
246}
247
248// ---------------------------------------------------------------------------
249// Post-quantum: FINAL FIPS 203 (ML-KEM-1024) + FIPS 204 (ML-DSA-65).
250//
251// This REPLACES the BouncyCastle round-3 Kyber/Dilithium implementations and
252// their X.509/PKCS8-DER key encodings. New byte contract (documented for iOS
253// below; wire-break accepted, goldens re-captured):
254//   ML-KEM-1024: public key = raw ek (1568 B), private key = SEED d||z (64 B,
255//     FIPS 203 §7.1 storage form), ciphertext = raw (1568 B), shared key 32 B.
256//   ML-DSA-65:   public key = raw vk (1952 B), private key = SEED xi (32 B,
257//     FIPS 204 approved private-key form), signature = raw (3309 B),
258//     pure mode (no pre-hash), empty context string, deterministic variant.
259// All randomness (key seeds, encapsulation m) comes from the OS via getrandom,
260// exactly the values the FIPS KeyGen/Encaps algorithms draw internally.
261// ---------------------------------------------------------------------------
262
263use ml_kem::{Decapsulate as _, KeyExport as _};
264
265/// A generated PQ key pair. `private_key` is the compact FIPS seed form
266/// (64 B for ML-KEM-1024, 32 B for ML-DSA-65), NOT the expanded key.
267#[derive(uniffi::Record)]
268pub struct PqKeyPair {
269    pub public_key: Vec<u8>,
270    pub private_key: Vec<u8>,
271}
272
273/// Result of ML-KEM encapsulation.
274#[derive(uniffi::Record)]
275pub struct KemEncapsulation {
276    pub ciphertext: Vec<u8>,
277    pub shared_secret: Vec<u8>,
278}
279
280pub(crate) fn os_random<const N: usize>() -> [u8; N] {
281    let mut out = [0u8; N];
282    getrandom::fill(&mut out).expect("OS RNG is always available on Android/iOS");
283    out
284}
285
286pub(crate) fn mlkem_dk_from_seed(private_key_seed: &[u8]) -> Result<ml_kem::DecapsulationKey1024, PrimitiveError> {
287    let seed: [u8; 64] = private_key_seed
288        .try_into()
289        .map_err(|_| PrimitiveError::Key(format!("ml-kem seed must be 64 bytes, got {}", private_key_seed.len())))?;
290    Ok(ml_kem::DecapsulationKey1024::from_seed(seed.into()))
291}
292
293pub(crate) fn mlkem_ek_from_bytes(public_key: &[u8]) -> Result<ml_kem::EncapsulationKey1024, PrimitiveError> {
294    let arr: [u8; 1568] = public_key
295        .try_into()
296        .map_err(|_| PrimitiveError::Key(format!("ml-kem public key must be 1568 bytes, got {}", public_key.len())))?;
297    ml_kem::EncapsulationKey1024::new(&arr.into())
298        .map_err(|_| PrimitiveError::Key("ml-kem public key failed FIPS 203 modulus validation".into()))
299}
300
301/// ML-KEM-1024 key generation (FIPS 203). Returns the raw 1568-byte
302/// encapsulation key and the 64-byte d||z seed as the private key.
303#[uniffi::export]
304pub fn mlkem1024_generate_keypair() -> PqKeyPair {
305    let seed: [u8; 64] = os_random();
306    let dk = ml_kem::DecapsulationKey1024::from_seed(seed.into());
307    PqKeyPair {
308        public_key: dk.encapsulation_key().to_bytes().to_vec(),
309        private_key: seed.to_vec(),
310    }
311}
312
313/// Derive the ML-KEM-1024 public (encapsulation) key from a stored 64-byte seed.
314#[uniffi::export]
315pub fn mlkem1024_public_key(private_key_seed: Vec<u8>) -> Result<Vec<u8>, PrimitiveError> {
316    Ok(mlkem_dk_from_seed(&private_key_seed)?.encapsulation_key().to_bytes().to_vec())
317}
318
319/// ML-KEM-1024 encapsulation (FIPS 203 Encaps). The 32-byte randomness m is
320/// drawn from the OS RNG — identical to `encapsulate_with_rng`.
321#[uniffi::export]
322pub fn mlkem1024_encapsulate(public_key: Vec<u8>) -> Result<KemEncapsulation, PrimitiveError> {
323    let ek = mlkem_ek_from_bytes(&public_key)?;
324    let m: [u8; 32] = os_random();
325    let (ct, k) = ek.encapsulate_deterministic(&m.into());
326    Ok(KemEncapsulation { ciphertext: ct.to_vec(), shared_secret: k.to_vec() })
327}
328
329/// ML-KEM-1024 decapsulation (FIPS 203 Decaps). Implicit rejection per the
330/// standard: a forged/corrupt ciphertext of the right length yields a
331/// pseudorandom shared key, not an error.
332#[uniffi::export]
333pub fn mlkem1024_decapsulate(ciphertext: Vec<u8>, private_key_seed: Vec<u8>) -> Result<Vec<u8>, PrimitiveError> {
334    let dk = mlkem_dk_from_seed(&private_key_seed)?;
335    let ct: [u8; 1568] = ciphertext
336        .as_slice()
337        .try_into()
338        .map_err(|_| PrimitiveError::Key(format!("ml-kem ciphertext must be 1568 bytes, got {}", ciphertext.len())))?;
339    Ok(dk.decapsulate(&ct.into()).to_vec())
340}
341
342/// Check that bytes are a valid ML-KEM-1024 encapsulation key (length + the
343/// FIPS 203 modulus check).
344#[uniffi::export]
345pub fn mlkem1024_validate_public_key(public_key: Vec<u8>) -> bool {
346    mlkem_ek_from_bytes(&public_key).is_ok()
347}
348
349/// ML-DSA-65 (crate ml-dsa 0.1) keeps polynomial matrices and vectors on the STACK: signing in a release
350/// build takes ~400–512 KiB, in debug ~768 KiB. The calling thread is not ours: a JVM thread (desktop, Android —
351/// 1 MiB, part of which is already used by Kotlin/JNA frames), a GCD thread on iOS — 512 KiB. Not enough means
352/// SIGSEGV in the core and an app crash (the desktop window crashed while signing in republishPublicKeys). So
353/// all ML-DSA work runs on a dedicated short-lived thread with a guaranteed stack; a panic is propagated
354/// back to the caller, the result is identical byte for byte.
355pub(crate) const PQ_STACK_BYTES: usize = 4 * 1024 * 1024;
356
357pub(crate) fn on_pq_stack<T: Send>(f: impl FnOnce() -> T + Send) -> T {
358    std::thread::scope(|s| {
359        let h = std::thread::Builder::new()
360            .name("typex-pq".into())
361            .stack_size(PQ_STACK_BYTES)
362            .spawn_scoped(s, f)
363            .expect("spawn ML-DSA worker thread");
364        match h.join() {
365            Ok(v) => v,
366            Err(panic) => std::panic::resume_unwind(panic),
367        }
368    })
369}
370
371pub(crate) fn mldsa_sk_from_seed(private_key_seed: &[u8]) -> Result<ml_dsa::SigningKey<ml_dsa::MlDsa65>, PrimitiveError> {
372    let seed: [u8; 32] = private_key_seed
373        .try_into()
374        .map_err(|_| PrimitiveError::Key(format!("ml-dsa seed must be 32 bytes, got {}", private_key_seed.len())))?;
375    Ok(ml_dsa::SigningKey::from_seed(&seed.into()))
376}
377
378/// ML-DSA-65 key generation (FIPS 204). Returns the raw 1952-byte verifying
379/// key and the 32-byte xi seed as the private key.
380#[uniffi::export]
381pub fn mldsa65_generate_keypair() -> PqKeyPair {
382    on_pq_stack(|| {
383        let seed: [u8; 32] = os_random();
384        let sk = ml_dsa::SigningKey::<ml_dsa::MlDsa65>::from_seed(&seed.into());
385        PqKeyPair {
386            public_key: sk.expanded_key().verifying_key().encode().to_vec(),
387            private_key: seed.to_vec(),
388        }
389    })
390}
391
392/// Derive the ML-DSA-65 public (verifying) key from a stored 32-byte seed.
393#[uniffi::export]
394pub fn mldsa65_public_key(private_key_seed: Vec<u8>) -> Result<Vec<u8>, PrimitiveError> {
395    on_pq_stack(|| Ok(mldsa_sk_from_seed(&private_key_seed)?.expanded_key().verifying_key().encode().to_vec()))
396}
397
398/// ML-DSA-65 signature (FIPS 204, pure mode, empty context, DETERMINISTIC
399/// variant §3.4 — like Ed25519, same message → same signature). 3309 bytes.
400#[uniffi::export]
401pub fn mldsa65_sign(message: Vec<u8>, private_key_seed: Vec<u8>) -> Result<Vec<u8>, PrimitiveError> {
402    on_pq_stack(|| {
403        let sk = mldsa_sk_from_seed(&private_key_seed)?;
404        let sig = sk
405            .expanded_key()
406            .sign_deterministic(&message, b"")
407            .map_err(|e| PrimitiveError::Key(format!("ml-dsa sign: {e}")))?;
408        Ok(sig.encode().to_vec())
409    })
410}
411
412/// ML-DSA-65 verification (FIPS 204, pure mode, empty context). Wrong-length
413/// or malformed key/signature returns false, never panics.
414#[uniffi::export]
415pub fn mldsa65_verify(message: Vec<u8>, signature: Vec<u8>, public_key: Vec<u8>) -> bool {
416    let Ok(pk_arr): Result<[u8; 1952], _> = public_key.as_slice().try_into() else { return false };
417    let Ok(sig_arr): Result<[u8; 3309], _> = signature.as_slice().try_into() else { return false };
418    on_pq_stack(|| {
419        let vk = ml_dsa::VerifyingKey::<ml_dsa::MlDsa65>::decode(&pk_arr.into());
420        let Some(sig) = ml_dsa::Signature::<ml_dsa::MlDsa65>::decode(&sig_arr.into()) else { return false };
421        vk.verify_with_context(&message, b"", &sig)
422    })
423}
424
425#[cfg(test)]
426mod tests {
427    use super::*;
428
429    /// RFC 8032 §7.1 TEST 1 — the standard Ed25519 vector. Signing was added for the
430    /// self-inbox read capability (audit K-2) and the Go server verifies these
431    /// signatures, so a drift here would lock every user out of their own inbox.
432    #[test]
433    fn ed25519_sign_matches_rfc8032_test1() {
434        let seed =
435            hex_decode("9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60");
436        let want_pub = "d75a980182b10ab7d54bfed3c964073a0ee172f3daa62325af021a68f707511a";
437        let want_sig = "e5564300c360ac729086e2cc806e828a84877f1eb8e5d974d873e065224901555fb8821590a33bacc61e39701cf9b46bd25bf5f0595bbe24655141438e7a100b";
438
439        let pk = ed25519_public_from_seed(seed.clone()).expect("derive");
440        assert_eq!(hex_encode(&pk), want_pub);
441
442        let sig = ed25519_sign(Vec::new(), seed).expect("sign");
443        assert_eq!(hex_encode(&sig), want_sig);
444        assert!(ed25519_verify(pk, Vec::new(), sig));
445    }
446
447    /// A wrong-sized seed must be a typed error, never a panic across the FFI.
448    #[test]
449    fn ed25519_rejects_malformed_seed() {
450        assert!(ed25519_public_from_seed(vec![0u8; 31]).is_err());
451        assert!(ed25519_sign(b"msg".to_vec(), vec![0u8; 33]).is_err());
452    }
453
454    fn hex_decode(s: &str) -> Vec<u8> {
455        (0..s.len())
456            .step_by(2)
457            .map(|i| u8::from_str_radix(&s[i..i + 2], 16).unwrap())
458            .collect()
459    }
460
461    fn hex_encode(b: &[u8]) -> String {
462        b.iter().map(|x| format!("{x:02x}")).collect()
463    }
464
465    fn seed32(label: &str) -> Vec<u8> {
466        let mut h = Sha256::new();
467        h.update(format!("nyxel-golden-{label}").as_bytes());
468        h.finalize().to_vec()
469    }
470
471    #[test]
472    fn sha256_and_pbkdf2_match_bouncycastle_golden() {
473        // Golden values captured from BouncyCastle at step 0.
474        assert_eq!(
475            hex::encode(sha256(b"nyxel".to_vec())),
476            "341d83ef0cb6f854e03c3e7a6b8d27371ec0d3b3c019d7c364a1bec86a5214fe"
477        );
478        // PBKDF2-100k (password "Str0ngPass!123", salt = sha256("nyxel-golden-kdf-salt"))
479        let salt = seed32("kdf-salt");
480        assert_eq!(
481            hex::encode(pbkdf2_hmac_sha256("Str0ngPass!123".to_string(), salt, 100000, 32).unwrap()),
482            "25b5a55043bc5eb90d860e95bd1d556eb1bc9a15c94bd8a5bc4e526157903dc1"
483        );
484    }
485
486    #[test]
487    fn aesgcm_and_hkdf_match_bouncycastle_golden() {
488        // HKDF golden (shared = sha256("nyxel-golden-aes-shared"))
489        let shared = seed32("aes-shared");
490        // deriveKeyHKDF(shared, "typex-hybrid-v1", "key-derivation")
491        assert_eq!(
492            hex::encode(hkdf_sha256(shared.clone(), b"typex-hybrid-v1".to_vec(), b"key-derivation".to_vec(), 32).unwrap()),
493            "0fa9fd4c01255dc0ebd201f3a5e62677cfd244896b44d9b0fa4f5c50fc5c1a38"
494        );
495        // deriveKey(shared): salt = sha256("Typex-AES-Key-Derivation-v1"), info = "aes-key"
496        let salt = sha256(b"Typex-AES-Key-Derivation-v1".to_vec());
497        assert_eq!(
498            hex::encode(hkdf_sha256(shared, salt, b"aes-key".to_vec(), 32).unwrap()),
499            "250f129c33aee2f657521ac51fd26cf61b3016cdb3f19dace1e370fc62438c7f"
500        );
501
502        // HMAC-SHA256: RFC 4231 test case 2 known-answer.
503        assert_eq!(
504            hex::encode(hmac_sha256(b"Jefe".to_vec(), b"what do ya want for nothing?".to_vec())),
505            "5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843"
506        );
507
508        // HKDF expand-only (BC skipExtractParameters equivalent): RFC 5869 A.1
509        // PRK/OKM known-answer.
510        let prk = hex::decode("077709362c2e32df0ddc3f0dc47bba6390b6c73bb50f9c3122ec844ad7c2b3e5").unwrap();
511        let info = hex::decode("f0f1f2f3f4f5f6f7f8f9").unwrap();
512        assert_eq!(
513            hex::encode(hkdf_sha256_expand(prk, info, 42).unwrap()),
514            "3cb25f25faacd57a90434f64d0362f2a2d2d0a90cf1a5a4c5db02d56ecc4c5bf34007208d5b887185865"
515        );
516
517        // AES-256-GCM golden (fixed key/iv/plaintext) → ct || tag
518        let key = hex::decode("84c8d785a6bde1ef6a3edd523d2012e10f22652aae2dcc977ecb7db1b0ed5d96").unwrap();
519        let iv = hex::decode("fecf1704cb8d25bbbc33a4a2").unwrap();
520        let pt = hex::decode("476f6c64656e204145532d47434d20d0b2d0b5d0bad182d0bed18020f09f9a80").unwrap();
521        let ct_tag = aes256_gcm_encrypt(key.clone(), iv.clone(), pt.clone(), vec![]).unwrap();
522        let ct = &ct_tag[..ct_tag.len() - 16];
523        let tag = &ct_tag[ct_tag.len() - 16..];
524        assert_eq!(hex::encode(ct), "796f5592e87ea9828c2172f9fe546b99c8d0b9e79452a7abfa54e3a457e755a7");
525        assert_eq!(hex::encode(tag), "bd324b4be30ebd262d3d631387703043");
526        // roundtrip
527        assert_eq!(aes256_gcm_decrypt(key, iv, ct_tag, vec![]).unwrap(), pt);
528    }
529
530    #[test]
531    fn x25519_matches_bouncycastle_golden() {
532        // Golden from app/src/androidTest/assets/golden/primitives.json (x25519):
533        // priv_a = sha256("nyxel-golden-x25519-a"), priv_b = sha256("nyxel-golden-x25519-b").
534        let priv_a = seed32("x25519-a");
535        let priv_b = seed32("x25519-b");
536        assert_eq!(hex::encode(&priv_a), "baf85156061ca0a4bce59e3a4e7326f0d37eaa8245b612fb2166dc1d8141ae65");
537
538        let pub_a = x25519_public_key(priv_a.clone()).unwrap();
539        let pub_b = x25519_public_key(priv_b.clone()).unwrap();
540        assert_eq!(hex::encode(&pub_a), "9243caff4580359ac499e2c4f5af355b11e2554ce82cbf3683f03f7529dd6346");
541        assert_eq!(hex::encode(&pub_b), "b006817088e3e556316d434c5a1ef3fbd33a24be67d6f917066902d537f41f15");
542
543        let shared_ab = x25519_shared_secret(priv_a, pub_b).unwrap();
544        let shared_ba = x25519_shared_secret(priv_b, pub_a).unwrap();
545        assert_eq!(shared_ab, shared_ba);
546        assert_eq!(hex::encode(&shared_ab), "c754757d72fcc3284709b37244e2ab466a170e4813bb10cb2f8bc3bbf853b41a");
547
548        // Wrong-length keys must error, not panic across the FFI.
549        assert!(x25519_public_key(vec![0u8; 31]).is_err());
550        assert!(x25519_shared_secret(vec![0u8; 32], vec![0u8; 33]).is_err());
551    }
552
553    #[test]
554    fn secp256k1_matches_bouncycastle_golden() {
555        // Golden from app/src/androidTest/assets/golden/primitives.json (secp256k1):
556        // priv = sha256("nyxel-golden-secp256k1"), message "nyxel golden secp256k1 message".
557        let priv_key = seed32("secp256k1");
558        assert_eq!(hex::encode(&priv_key), "29bbc813047bffa96baaabfaed510d1dc5783ccc5e25d7b7ab0cc9e65e4fb596");
559
560        let pub_key = secp256k1_public_key(priv_key.clone()).unwrap();
561        assert_eq!(
562            hex::encode(&pub_key),
563            "04c63dc4414c49fe286fa82635bbe33509f7c68e3bcb6ac003dc3ae993c24cf546f5cb6b5309e4aa231ace61634557297997184f3c95e5b3b752f0cf448ab817b9"
564        );
565
566        // The Kotlin wrapper hashes the message with SHA-256 before signing.
567        let hash = sha256(b"nyxel golden secp256k1 message".to_vec());
568        let sig = secp256k1_sign_hash(hash.clone(), priv_key).unwrap();
569        assert_eq!(
570            hex::encode(&sig),
571            "6cd34c12f6cbfc78b84d62066aaa8468824efc7631fbb41409c75ec2248d8590171209bfefe39c67cb9a6b76ed0f788b00f4286cdbbf0204d12b81a8cad0859c"
572        );
573
574        assert!(secp256k1_verify_hash(hash.clone(), sig.clone(), pub_key.clone()));
575        // Tampered message must fail.
576        assert!(!secp256k1_verify_hash(sha256(b"tampered".to_vec()), sig.clone(), pub_key.clone()));
577        // BC's verifier accepted high-S signatures — ours must too (s' = n - s).
578        let n = hex::decode("fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141").unwrap();
579        let mut high_s = sig.clone();
580        let mut borrow = 0i16;
581        for i in (0..32).rev() {
582            let d = n[i] as i16 - sig[32 + i] as i16 - borrow;
583            borrow = if d < 0 { 1 } else { 0 };
584            high_s[32 + i] = (d & 0xff) as u8;
585        }
586        assert!(secp256k1_verify_hash(hash.clone(), high_s, pub_key.clone()));
587        // Garbage inputs return false, never panic.
588        assert!(!secp256k1_verify_hash(hash, vec![0u8; 64], pub_key));
589    }
590
591    #[test]
592    fn ed25519_matches_bouncycastle_golden() {
593        // Golden from primitives.json (key_transparency): STH message signed by
594        // the BC Ed25519Signer with priv = sha256("nyxel-golden-kt-ed25519").
595        let pub_key = hex::decode("bb285d8fc24b89c1946dc20594665139980a4f1d5c954a0fc8cb8e9795846b42").unwrap();
596        let msg = b"KT-STH-v1|2|57198f35d3dd5baff384d33c1ac3bb4e0b99979123071a141d091baf4bb8ba24|1750000000000".to_vec();
597        let sig = hex::decode("c837c2522777d5054ed3896494f481e85ff545831165f96d150ecdd2c9f3c7c5d22975ec83544579f376bae0839da3863ae8fda4966db6c30ce2c96006042500").unwrap();
598
599        assert!(ed25519_verify(pub_key.clone(), msg.clone(), sig.clone()));
600
601        // Tampered message / signature / wrong key must fail.
602        let mut tampered = msg.clone();
603        tampered[0] ^= 1;
604        assert!(!ed25519_verify(pub_key.clone(), tampered, sig.clone()));
605        let mut bad_sig = sig.clone();
606        bad_sig[0] ^= 1;
607        assert!(!ed25519_verify(pub_key.clone(), msg.clone(), bad_sig));
608        // Malformed inputs return false, never panic.
609        assert!(!ed25519_verify(vec![0u8; 31], msg.clone(), sig.clone()));
610        assert!(!ed25519_verify(pub_key, msg, vec![0u8; 63]));
611    }
612
613    #[test]
614    fn argon2id_matches_bouncycastle_golden() {
615        // Golden captured from the BouncyCastle Argon2id (step 0):
616        // password "Str0ngPass!123", salt = sha256("nyxel-golden-kdf-salt").
617        let salt = seed32("kdf-salt");
618        assert_eq!(
619            hex::encode(&salt),
620            "15d08088d333b971dba0ee899f2494051a4bf59f1db2ae42869d4cc8f4dfac9a"
621        );
622        let out = argon2id_derive("Str0ngPass!123".to_string(), salt, 32).unwrap();
623        assert_eq!(
624            hex::encode(out),
625            "5993fde73c0fc6dfa02bc96fb5ec405bb6a62f9f87ca647c875d517d97a509a2"
626        );
627    }
628}
629
630#[cfg(test)]
631mod pq_tests {
632    use super::*;
633
634    fn seed32(label: &str) -> Vec<u8> {
635        sha256(format!("nyxel-golden-{label}").as_bytes().to_vec())
636    }
637
638    // SELF-GOLDEN (iOS contract anchors): all PQ inputs are deterministic from
639    // fixed seeds, so these byte-anchor the FINAL-FIPS formats. If a future
640    // crate update changes any of these hashes, the wire format broke — stop.
641    #[test]
642    fn mlkem1024_fips203_self_golden_and_roundtrip() {
643        let kem_seed = [seed32("mlkem-d"), seed32("mlkem-z")].concat(); // 64-byte d||z
644        let pk = mlkem1024_public_key(kem_seed.clone()).unwrap();
645        assert_eq!(pk.len(), 1568);
646        assert_eq!(
647            hex::encode(sha256(pk.clone())),
648            "d0f9b0bb537d7f66d4e687edb450aed1875d1e5ba5b50489b12e0e6cce76a5c5"
649        );
650
651        // Deterministic Encaps with fixed m — anchors ciphertext + shared key bytes.
652        let m: [u8; 32] = seed32("mlkem-m").try_into().unwrap();
653        let ek = mlkem_ek_from_bytes(&pk).unwrap();
654        let (ct, k) = ek.encapsulate_deterministic(&m.into());
655        assert_eq!(ct.len(), 1568);
656        assert_eq!(
657            hex::encode(sha256(ct.to_vec())),
658            "4b3616bed3b1d0e9a354d660710818bc7d8fe548a60a2859ce14047eb157b23a"
659        );
660        assert_eq!(
661            hex::encode(&k),
662            "1abd9c7d449b01c4e7c71a710d8b8ca96e24478114ff736b4baa2cb4b477f1c7"
663        );
664        assert_eq!(mlkem1024_decapsulate(ct.to_vec(), kem_seed.clone()).unwrap(), k.to_vec());
665
666        // FIPS 203 implicit rejection: corrupt ct of the right length yields a
667        // DIFFERENT pseudorandom key, not an error.
668        let mut bad = ct.to_vec();
669        bad[0] ^= 1;
670        let k2 = mlkem1024_decapsulate(bad, kem_seed.clone()).unwrap();
671        assert_eq!(k2.len(), 32);
672        assert_ne!(k2, k.to_vec());
673
674        // Random-keypair roundtrip through the exported API.
675        let kp = mlkem1024_generate_keypair();
676        assert_eq!(kp.public_key.len(), 1568);
677        assert_eq!(kp.private_key.len(), 64);
678        let enc = mlkem1024_encapsulate(kp.public_key.clone()).unwrap();
679        assert_eq!(
680            mlkem1024_decapsulate(enc.ciphertext, kp.private_key).unwrap(),
681            enc.shared_secret
682        );
683        assert!(mlkem1024_validate_public_key(kp.public_key));
684        // Coefficients >= q fail the FIPS 203 modulus check; wrong length fails too.
685        assert!(!mlkem1024_validate_public_key(vec![0xffu8; 1568]));
686        assert!(!mlkem1024_validate_public_key(vec![0u8; 1567]));
687        assert!(mlkem1024_decapsulate(vec![0u8; 1568], vec![0u8; 63]).is_err());
688        assert!(mlkem1024_decapsulate(vec![0u8; 1567], kem_seed).is_err());
689    }
690
691    #[test]
692    fn mldsa65_fips204_self_golden_and_roundtrip() {
693        let dsa_seed = seed32("mldsa-xi"); // 32-byte xi
694        let pk = mldsa65_public_key(dsa_seed.clone()).unwrap();
695        assert_eq!(pk.len(), 1952);
696        assert_eq!(
697            hex::encode(sha256(pk.clone())),
698            "230b6006a6591511b6609862bd9e0cdc91679ba865a47a054d989159d4bd3eaa"
699        );
700
701        // Deterministic variant → byte-exact signature from a fixed seed+message.
702        let msg = b"nyxel golden ml-dsa message".to_vec();
703        let sig = mldsa65_sign(msg.clone(), dsa_seed.clone()).unwrap();
704        assert_eq!(sig.len(), 3309);
705        assert_eq!(
706            hex::encode(sha256(sig.clone())),
707            "89b659b70d4d1553d2d92f7b86d24120ab2e55de6d9098b82c049d3368c1404d"
708        );
709
710        assert!(mldsa65_verify(msg.clone(), sig.clone(), pk.clone()));
711        // Tampered message / signature must fail.
712        let mut tampered = msg.clone();
713        tampered[0] ^= 1;
714        assert!(!mldsa65_verify(tampered, sig.clone(), pk.clone()));
715        let mut bad_sig = sig.clone();
716        bad_sig[100] ^= 1;
717        assert!(!mldsa65_verify(msg.clone(), bad_sig, pk.clone()));
718        // Malformed lengths return false / error, never panic.
719        assert!(!mldsa65_verify(msg.clone(), sig.clone(), vec![0u8; 1951]));
720        assert!(!mldsa65_verify(msg.clone(), vec![0u8; 3308], pk.clone()));
721        assert!(mldsa65_sign(msg.clone(), vec![0u8; 31]).is_err());
722
723        // Random-keypair roundtrip through the exported API.
724        let kp = mldsa65_generate_keypair();
725        assert_eq!(kp.public_key.len(), 1952);
726        assert_eq!(kp.private_key.len(), 32);
727        let sig2 = mldsa65_sign(msg.clone(), kp.private_key.clone()).unwrap();
728        assert!(mldsa65_verify(msg.clone(), sig2.clone(), kp.public_key.clone()));
729        // Signature bound to its key: does not verify under the golden key.
730        assert!(!mldsa65_verify(msg, sig2, pk));
731    }
732}