Skip to main content

oa/crypto/pqc/device/
operations.gen.rs

1// @generated by tool/gen/fn/generate.py; DO NOT EDIT.
2// schema=crypto_pqc.json schema_version=1 generator_version=64
3// schema_sha256=ad5c52b92d5db6eea9bc0f3a0052a27bc622f590c2bf8aff4671611eeef37982
4//! Experimental device-secret PQC operations. No private value is a Matrix.
5//! The originating Runtime owns execution; Drop never submits or waits.
6use crate::crypto::entropy::Entropy;
7use crate::crypto::pqc::MlDsaParameters;
8use crate::runtime::{MlDsaDeviceKey, MlKemDeviceKey, MlKemSharedSecret, SecretErasure};
9use crate::{Error, Matrix, Result, Runtime};
10
11/// FIPS 203 device-key parameter set.
12#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
13pub enum MlKemParameters {
14	/// ML-KEM-512.
15	MlKem512,
16	/// ML-KEM-768.
17	MlKem768,
18	/// ML-KEM-1024.
19	MlKem1024,
20}
21
22impl MlKemParameters {
23	/// Private polynomial-vector width.
24	#[must_use]
25	pub(crate) const fn k(self) -> u32 {
26		match self {
27			Self::MlKem512 => 2,
28			Self::MlKem768 => 3,
29			Self::MlKem1024 => 4,
30		}
31	}
32	/// Encoded encapsulation-key bytes.
33	#[must_use]
34	pub const fn public_key_size(self) -> usize {
35		match self {
36			Self::MlKem512 => 800,
37			Self::MlKem768 => 1184,
38			Self::MlKem1024 => 1568,
39		}
40	}
41	/// Encoded ciphertext bytes.
42	#[must_use]
43	pub const fn ciphertext_size(self) -> usize {
44		match self {
45			Self::MlKem512 => 768,
46			Self::MlKem768 => 1088,
47			Self::MlKem1024 => 1568,
48		}
49	}
50}
51
52/// FIPS 204 HashML-DSA identity and exact digest extent.
53#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
54pub enum MlDsaPrehash {
55	/// SHA2-256, 32 digest bytes.
56	Sha256,
57	/// SHA2-384, 48 digest bytes.
58	Sha384,
59	/// SHA2-512, 64 digest bytes.
60	Sha512,
61	/// SHA2-224, 28 digest bytes.
62	Sha224,
63	/// SHA2-512/224, 28 digest bytes.
64	Sha512Truncated224,
65	/// SHA2-512/256, 32 digest bytes.
66	Sha512Truncated256,
67	/// SHA3-224, 28 digest bytes.
68	Sha3_224,
69	/// SHA3-256, 32 digest bytes.
70	Sha3_256,
71	/// SHA3-384, 48 digest bytes.
72	Sha3_384,
73	/// SHA3-512, 64 digest bytes.
74	Sha3_512,
75	/// SHAKE-128, 32 digest bytes.
76	Shake128,
77	/// SHAKE-256, 64 digest bytes.
78	Shake256,
79}
80
81impl MlDsaPrehash {
82	/// Private NIST OID suffix.
83	#[must_use]
84	pub(crate) const fn id(self) -> u32 {
85		match self {
86			Self::Sha256 => 1,
87			Self::Sha384 => 2,
88			Self::Sha512 => 3,
89			Self::Sha224 => 4,
90			Self::Sha512Truncated224 => 5,
91			Self::Sha512Truncated256 => 6,
92			Self::Sha3_224 => 7,
93			Self::Sha3_256 => 8,
94			Self::Sha3_384 => 9,
95			Self::Sha3_512 => 10,
96			Self::Shake128 => 11,
97			Self::Shake256 => 12,
98		}
99	}
100	/// Exact encoded digest bytes.
101	#[must_use]
102	pub const fn digest_bytes(self) -> usize {
103		match self {
104			Self::Sha256 => 32,
105			Self::Sha384 => 48,
106			Self::Sha512 => 64,
107			Self::Sha224 => 28,
108			Self::Sha512Truncated224 => 28,
109			Self::Sha512Truncated256 => 32,
110			Self::Sha3_224 => 28,
111			Self::Sha3_256 => 32,
112			Self::Sha3_384 => 48,
113			Self::Sha3_512 => 64,
114			Self::Shake128 => 32,
115			Self::Shake256 => 64,
116		}
117	}
118}
119
120/// Signing randomness policy. Deterministic signing uses FIPS 204's zero rnd.
121#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
122pub enum SigningMode {
123	/// Fresh operating-system entropy for every signature.
124	#[default]
125	Randomized,
126	/// Reproducible signatures for a fixed key, message, and context.
127	Deterministic,
128}
129
130/// Exact completion of explicit secret or transient-workspace erasure.
131/// Dropping the ticket neither waits nor cancels the retained command.
132#[must_use = "observe erasure completion before treating memory as erased"]
133pub struct DeviceErasure {
134	inner: SecretErasure,
135}
136
137impl DeviceErasure {
138	/// Check exact completion without submitting or waiting.
139	/// # Errors
140	/// Returns failure if execution or erasure could not be confirmed.
141	pub fn try_is_complete(&self) -> Result<bool> {
142		self.inner.try_is_complete()
143	}
144
145	/// Wait for this submission and confirm all included overwrites.
146	/// # Errors
147	/// Returns failure if execution or erasure could not be confirmed.
148	pub fn wait(&self) -> Result<()> {
149		self.inner.wait()
150	}
151}
152
153/// Unique retained ML-DSA key. No mapping, serialization, Clone, or Debug.
154/// Abandonment quarantines its secret allocation; use consuming `erase`.
155#[must_use = "explicitly erase the device key when its final consumer is recorded"]
156pub struct DeviceMlDsaKey {
157	inner: MlDsaDeviceKey,
158	parameters: MlDsaParameters,
159	public_key: Matrix,
160	cleanup: DeviceErasure,
161}
162
163impl DeviceMlDsaKey {
164	/// Parameter set retained with the generated key.
165	#[must_use]
166	pub const fn parameters(&self) -> MlDsaParameters {
167		self.parameters
168	}
169
170	/// Public encoded key, ready through the exact key-generation submission.
171	#[must_use]
172	pub const fn public_key(&self) -> &Matrix {
173		&self.public_key
174	}
175
176	/// Erasure of generation entropy and transient workspace, excluding the key.
177	#[must_use = "observe completion before reusing erased storage"]
178	pub const fn cleanup(&self) -> &DeviceErasure {
179		&self.cleanup
180	}
181
182	/// Consume the key and record erasure after all preceding consumers.
183	/// # Errors
184	/// Rejects capture or submission failure; unconfirmed memory stays quarantined.
185	pub fn erase(self) -> Result<DeviceErasure> {
186		Ok(DeviceErasure {
187			inner: self.inner.erase()?,
188		})
189	}
190}
191
192/// Unique retained ML-KEM decapsulation key; secret bytes never enter Matrix.
193#[must_use = "explicitly erase the device key after its final consumer"]
194pub struct DeviceMlKemKey {
195	inner: MlKemDeviceKey,
196	parameters: MlKemParameters,
197	public_key: Matrix,
198	cleanup: DeviceErasure,
199}
200
201impl DeviceMlKemKey {
202	/// Parameter set retained with the key.
203	#[must_use]
204	pub const fn parameters(&self) -> MlKemParameters {
205		self.parameters
206	}
207
208	/// Public encapsulation key, with exact generation readiness.
209	#[must_use]
210	pub const fn public_key(&self) -> &Matrix {
211		&self.public_key
212	}
213
214	/// Erasure of generation entropy/workspace, excluding the retained key.
215	#[must_use = "observe completion before reusing erased storage"]
216	pub const fn cleanup(&self) -> &DeviceErasure {
217		&self.cleanup
218	}
219
220	/// Consume the key and record ordered erasure.
221	/// # Errors
222	/// Rejects capture or submission failure; unconfirmed memory stays quarantined.
223	pub fn erase(self) -> Result<DeviceErasure> {
224		Ok(DeviceErasure {
225			inner: self.inner.erase()?,
226		})
227	}
228}
229
230/// Unique ML-KEM shared secret. No host read, export, or Matrix conversion.
231#[must_use = "explicitly erase the device shared secret after its final consumer"]
232pub struct DeviceSharedSecret {
233	inner: MlKemSharedSecret,
234}
235
236impl DeviceSharedSecret {
237	/// Consume the shared secret and record ordered erasure.
238	/// # Errors
239	/// Rejects capture or submission failure; unconfirmed memory stays quarantined.
240	pub fn erase(self) -> Result<DeviceErasure> {
241		Ok(DeviceErasure {
242			inner: self.inner.erase()?,
243		})
244	}
245}
246
247/// Public signing outcome. Status `U32[1]` is one on success, zero on failure.
248/// Signature bytes are zero on failure; observe status before using them.
249#[must_use]
250pub struct DeviceSignature {
251	/// Encoded public signature, U8[1, signature_size].
252	pub signature: Matrix,
253	/// Public success status, with no rejection-loop count.
254	pub status: Matrix,
255	/// Exact transient entropy/workspace erasure completion.
256	pub cleanup: DeviceErasure,
257}
258
259/// Public ciphertext plus an opaque shared secret and public-key validity.
260/// A zero status rejects the encapsulation key; it is not a ciphertext oracle.
261#[must_use]
262pub struct DeviceEncapsulation {
263	/// Opaque shared secret. Usable only when public-key status is one.
264	pub shared_secret: DeviceSharedSecret,
265	/// Public ciphertext, U8[1, ciphertext_size].
266	pub ciphertext: Matrix,
267	/// `U32[1]` canonical encapsulation-key status.
268	pub status: Matrix,
269	/// Transient entropy/workspace erasure completion, excluding shared_secret.
270	pub cleanup: DeviceErasure,
271}
272
273/// Deferred secret-execution batch owned by one Runtime.
274///
275/// While a scope is active, every runtime submission — secret or ordinary —
276/// records without queueing; `commit` submits the ordered batch once.
277/// Operation events and erasure tickets issued inside the scope stay pending
278/// until commit and fail on abandonment. The batch carries only secret
279/// classification metadata, never secret bytes.
280#[must_use = "commit submits the deferred batch; abandoning fails its completions"]
281pub struct PqcSecretScope {
282	inner: crate::runtime::SecretLoweringScope,
283}
284
285/// Begin a deferred secret-execution batch on `runtime`.
286/// # Errors
287/// Rejects an active capture or a second concurrent scope.
288pub fn begin_secret_scope(runtime: &Runtime) -> Result<PqcSecretScope> {
289	Ok(PqcSecretScope {
290		inner: runtime.handle().begin_secret_lowering()?,
291	})
292}
293
294/// Classification snapshot of one deferred scope node. Diagnostics observe
295/// flags and order only; no secret bytes or native handles are exposed.
296#[derive(Clone, Copy, Debug, PartialEq, Eq)]
297pub struct PqcSecretScopeNode {
298	/// The recorded submission consumes non-mappable secret storage.
299	pub uses_secret: bool,
300	/// The recorded submission schedules secret-erasure work.
301	pub records_erasure: bool,
302	/// The recorded submission retains ordinary public resources.
303	pub retains_public: bool,
304}
305
306impl PqcSecretScope {
307	/// Classification snapshot of the deferred nodes in recorded order.
308	pub fn nodes(&self) -> Vec<PqcSecretScopeNode> {
309		self
310			.inner
311			.nodes()
312			.into_iter()
313			.map(|node| PqcSecretScopeNode {
314				uses_secret: node.uses_secret,
315				records_erasure: node.records_erasure,
316				retains_public: node.retains_public,
317			})
318			.collect()
319	}
320
321	/// Submit the deferred batch in recorded order.
322	/// # Errors
323	/// Rejects an empty scope, submission, or retirement failure. Unsubmitted
324	/// nodes are freed and their completions fail; submitted nodes retire.
325	pub fn commit(self) -> Result<()> {
326		self.inner.commit().map(|_| ())
327	}
328}
329
330/// Opaque decapsulation result. Correct-size malformed ciphertexts follow
331/// implicit rejection entirely on device; no validity flag is exposed.
332#[must_use]
333pub struct DeviceDecapsulation {
334	/// Retained secret selected by the implicit-rejection algorithm.
335	pub shared_secret: DeviceSharedSecret,
336	/// Secret-derived workspace erasure completion, excluding shared_secret.
337	pub cleanup: DeviceErasure,
338}
339
340/// Public derivation outcome. `derived` is the only public value produced
341/// from the opaque shared secret inside the keyed-hash boundary.
342#[must_use]
343pub struct DeviceDerivation {
344	/// Public derived bytes, U8[1, length].
345	pub derived: Matrix,
346	/// Exact derivation-submission completion evidence.
347	pub cleanup: DeviceErasure,
348}
349
350/// Generate a retained ML-DSA-44/65/87 key from fresh OS entropy.
351/// # Errors
352/// Rejects unsupported kernels, capture, allocation, entropy, or submission errors.
353pub fn mldsa_keygen(runtime: &Runtime, parameters: MlDsaParameters) -> Result<DeviceMlDsaKey> {
354	let parameter = match parameters {
355		MlDsaParameters::MlDsa44 => 44,
356		MlDsaParameters::MlDsa65 => 65,
357		MlDsaParameters::MlDsa87 => 87,
358	};
359	let (inner, public_key, cleanup) = runtime
360		.handle()
361		.pqc_mldsa_keygen(parameter, Entropy::generate()?)?;
362	Ok(DeviceMlDsaKey {
363		inner,
364		parameters,
365		public_key,
366		cleanup: DeviceErasure { inner: cleanup },
367	})
368}
369
370/// Generate a retained ML-KEM-512/768/1024 key from fresh OS entropy.
371/// # Errors
372/// Rejects unsupported kernels, capture, allocation, entropy, or submission errors.
373pub fn mlkem_keygen(runtime: &Runtime, parameters: MlKemParameters) -> Result<DeviceMlKemKey> {
374	let (inner, public_key, cleanup) = runtime
375		.handle()
376		.pqc_mlkem_keygen(parameters.k(), Entropy::generate()?)?;
377	Ok(DeviceMlKemKey {
378		inner,
379		parameters,
380		public_key,
381		cleanup: DeviceErasure { inner: cleanup },
382	})
383}
384
385/// Import FIPS 204 signing-key bytes with their encoded public U8 key.
386/// The secret input range is locked best-effort and erased before return; its
387/// upload becomes the retained device secret. Importing does not prove that the
388/// secret and public halves form a consistent key pair.
389/// # Errors
390/// Rejects extent/ownership mismatches, capture, or submission errors.
391pub fn mldsa_import_key(
392	runtime: &Runtime,
393	parameters: MlDsaParameters,
394	secret_key: &mut [u8],
395	public_key: &Matrix,
396) -> Result<DeviceMlDsaKey> {
397	let parameter = match parameters {
398		MlDsaParameters::MlDsa44 => 44,
399		MlDsaParameters::MlDsa65 => 65,
400		MlDsaParameters::MlDsa87 => 87,
401	};
402	let secret = crate::crypto::SecureBuffer::new(secret_key);
403	let (inner, public_key, cleanup) =
404		runtime
405			.handle()
406			.pqc_mldsa_import(parameter, secret.as_slice(), public_key)?;
407	Ok(DeviceMlDsaKey {
408		inner,
409		parameters,
410		public_key,
411		cleanup: DeviceErasure { inner: cleanup },
412	})
413}
414
415/// Import FIPS 203 decapsulation-key bytes. The embedded encapsulation key
416/// supplies the retained public value; the secret input range is locked
417/// best-effort and erased before return. Importing does not prove that the
418/// decapsulation key is well-formed.
419/// # Errors
420/// Rejects extent mismatches, capture, or submission errors.
421pub fn mlkem_import_key(
422	runtime: &Runtime,
423	parameters: MlKemParameters,
424	decapsulation_key: &mut [u8],
425) -> Result<DeviceMlKemKey> {
426	let secret = crate::crypto::SecureBuffer::new(decapsulation_key);
427	let (inner, public_key, cleanup) = runtime
428		.handle()
429		.pqc_mlkem_import(parameters.k(), secret.as_slice())?;
430	Ok(DeviceMlKemKey {
431		inner,
432		parameters,
433		public_key,
434		cleanup: DeviceErasure { inner: cleanup },
435	})
436}
437
438/// Sign public U8 message bytes with the FIPS 204 context (at most 255 bytes).
439/// Inputs retain the key's Runtime; neither input is copied to host.
440/// # Errors
441/// Rejects dtype/ownership/alias/context errors, capture, or execution failure.
442pub fn mldsa_sign(
443	key: &DeviceMlDsaKey,
444	message: &Matrix,
445	context: &Matrix,
446	mode: SigningMode,
447) -> Result<DeviceSignature> {
448	if context.num_elements() > 255 {
449		return Err(Error::invalid_argument("ML-DSA context exceeds 255 bytes"));
450	}
451	let entropy = match mode {
452		SigningMode::Randomized => Entropy::generate()?,
453		SigningMode::Deterministic => Entropy::deterministic_signing()?,
454	};
455	let (signature, status, cleanup) = key
456		.inner
457		.runtime()
458		.pqc_mldsa_sign(&key.inner, message, context, None, entropy)?;
459	Ok(DeviceSignature {
460		signature,
461		status,
462		cleanup: DeviceErasure { inner: cleanup },
463	})
464}
465
466/// Hash and sign original public U8 message bytes on device (HashML-DSA).
467/// # Errors
468/// Rejects dtype/ownership/alias/context errors, capture, or execution failure.
469pub fn mldsa_sign_hash_message(
470	key: &DeviceMlDsaKey,
471	message: &Matrix,
472	context: &Matrix,
473	algorithm: MlDsaPrehash,
474	mode: SigningMode,
475) -> Result<DeviceSignature> {
476	if context.num_elements() > 255 {
477		return Err(Error::invalid_argument("ML-DSA context exceeds 255 bytes"));
478	}
479	let entropy = match mode {
480		SigningMode::Randomized => Entropy::generate()?,
481		SigningMode::Deterministic => Entropy::deterministic_signing()?,
482	};
483	let (signature, status, cleanup) = key.inner.runtime().pqc_mldsa_sign(
484		&key.inner,
485		message,
486		context,
487		Some(algorithm.id()),
488		entropy,
489	)?;
490	Ok(DeviceSignature {
491		signature,
492		status,
493		cleanup: DeviceErasure { inner: cleanup },
494	})
495}
496
497/// Sign an exact-length public digest with FIPS HashML-DSA OID framing.
498/// # Errors
499/// Rejects digest/context metadata, owner/alias mismatch, capture, or execution errors.
500pub fn mldsa_sign_prehashed(
501	key: &DeviceMlDsaKey,
502	digest: &Matrix,
503	context: &Matrix,
504	algorithm: MlDsaPrehash,
505	mode: SigningMode,
506) -> Result<DeviceSignature> {
507	if digest.num_elements() != algorithm.digest_bytes() || context.num_elements() > 255 {
508		return Err(Error::invalid_argument(
509			"HashML-DSA digest or context extent mismatch",
510		));
511	}
512	let entropy = match mode {
513		SigningMode::Randomized => Entropy::generate()?,
514		SigningMode::Deterministic => Entropy::deterministic_signing()?,
515	};
516	let (signature, status, cleanup) = key.inner.runtime().pqc_mldsa_sign_prehashed(
517		&key.inner,
518		digest,
519		context,
520		algorithm.id(),
521		entropy,
522	)?;
523	Ok(DeviceSignature {
524		signature,
525		status,
526		cleanup: DeviceErasure { inner: cleanup },
527	})
528}
529
530/// Encapsulate to a public U8 key. Canonicality is checked on device.
531/// # Errors
532/// Rejects key dtype/owner/extent, capture, entropy, or execution errors.
533pub fn mlkem_encapsulate(
534	public_key: &Matrix,
535	parameters: MlKemParameters,
536) -> Result<DeviceEncapsulation> {
537	if public_key.num_elements() != parameters.public_key_size() {
538		return Err(Error::invalid_argument("ML-KEM public key extent mismatch"));
539	}
540	let (inner, ciphertext, status, cleanup) =
541		public_key
542			.runtime()
543			.pqc_mlkem_encapsulate(parameters.k(), public_key, Entropy::generate()?)?;
544	Ok(DeviceEncapsulation {
545		shared_secret: DeviceSharedSecret { inner },
546		ciphertext,
547		status,
548		cleanup: DeviceErasure { inner: cleanup },
549	})
550}
551
552/// Decapsulate a correct-size public ciphertext using a retained device key.
553/// # Errors
554/// Rejects dtype/owner/extent, capture, or execution errors. Ciphertext content
555/// rejection produces an opaque replacement secret, never an error or flag.
556pub fn mlkem_decapsulate(key: &DeviceMlKemKey, ciphertext: &Matrix) -> Result<DeviceDecapsulation> {
557	if ciphertext.num_elements() != key.parameters.ciphertext_size() {
558		return Err(Error::invalid_argument("ML-KEM ciphertext extent mismatch"));
559	}
560	let (inner, cleanup) = key
561		.inner
562		.runtime()
563		.pqc_mlkem_decapsulate(&key.inner, ciphertext)?;
564	Ok(DeviceDecapsulation {
565		shared_secret: DeviceSharedSecret { inner },
566		cleanup: DeviceErasure { inner: cleanup },
567	})
568}
569
570/// Declassify public bytes derived from a device shared secret. The secret
571/// never leaves private storage; keyed SHAKE-256 output is the only result.
572/// `info` is public customization data absorbed after the secret; `length`
573/// must be a nonzero multiple of four within 4096 bytes.
574/// # Errors
575/// Rejects dtype/owner/extent errors, capture, or execution failure.
576pub fn mlkem_shared_derive(
577	secret: &DeviceSharedSecret,
578	info: &Matrix,
579	length: usize,
580) -> Result<DeviceDerivation> {
581	let output_len = u32::try_from(length)
582		.map_err(|_| Error::invalid_argument("shared-secret derivation extent exceeds u32"))?;
583	let (derived, cleanup) =
584		secret
585			.inner
586			.runtime()
587			.pqc_mlkem_derive(&secret.inner, info, output_len)?;
588	Ok(DeviceDerivation {
589		derived,
590		cleanup: DeviceErasure { inner: cleanup },
591	})
592}
593
594/// Verify HashML-DSA original-message batches with a typed hash identity.
595/// # Errors
596/// Rejects incompatible metadata; malformed signature rows produce zero status.
597#[expect(
598	clippy::too_many_arguments,
599	reason = "batch verifier preserves explicit zero-copy byte ranges"
600)]
601pub fn mldsa_verify_hash_message(
602	parameters: MlDsaParameters,
603	algorithm: MlDsaPrehash,
604	messages: &Matrix,
605	offsets: &Matrix,
606	lengths: &Matrix,
607	signatures: &Matrix,
608	public_keys: &Matrix,
609	context: std::ops::Range<usize>,
610) -> Result<Matrix> {
611	super::super::verification::verify_hash_message_batch(
612		parameters,
613		algorithm.id(),
614		messages,
615		offsets,
616		lengths,
617		signatures,
618		public_keys,
619		context,
620	)
621}
622
623/// Verify precomputed-digest batches with exact typed FIPS hash extents.
624/// # Errors
625/// Rejects incompatible metadata; invalid digest/signature rows produce zero.
626#[expect(
627	clippy::too_many_arguments,
628	reason = "batch verifier preserves explicit zero-copy byte ranges"
629)]
630pub fn mldsa_verify_prehashed(
631	parameters: MlDsaParameters,
632	algorithm: MlDsaPrehash,
633	digests: &Matrix,
634	offsets: &Matrix,
635	lengths: &Matrix,
636	signatures: &Matrix,
637	public_keys: &Matrix,
638	context: std::ops::Range<usize>,
639) -> Result<Matrix> {
640	super::super::verification::verify_prehashed_batch(
641		parameters,
642		algorithm.id(),
643		digests,
644		offsets,
645		lengths,
646		signatures,
647		public_keys,
648		context,
649	)
650}