1use crate::crypto::entropy::Entropy;
7use crate::crypto::pqc::MlDsaParameters;
8use crate::runtime::{MlDsaDeviceKey, MlKemDeviceKey, MlKemSharedSecret, SecretErasure};
9use crate::{Error, Matrix, Result, Runtime};
10
11#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
13pub enum MlKemParameters {
14 MlKem512,
16 MlKem768,
18 MlKem1024,
20}
21
22impl MlKemParameters {
23 #[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 #[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 #[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#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
54pub enum MlDsaPrehash {
55 Sha256,
57 Sha384,
59 Sha512,
61 Sha224,
63 Sha512Truncated224,
65 Sha512Truncated256,
67 Sha3_224,
69 Sha3_256,
71 Sha3_384,
73 Sha3_512,
75 Shake128,
77 Shake256,
79}
80
81impl MlDsaPrehash {
82 #[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 #[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#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
122pub enum SigningMode {
123 #[default]
125 Randomized,
126 Deterministic,
128}
129
130#[must_use = "observe erasure completion before treating memory as erased"]
133pub struct DeviceErasure {
134 inner: SecretErasure,
135}
136
137impl DeviceErasure {
138 pub fn try_is_complete(&self) -> Result<bool> {
142 self.inner.try_is_complete()
143 }
144
145 pub fn wait(&self) -> Result<()> {
149 self.inner.wait()
150 }
151}
152
153#[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 #[must_use]
166 pub const fn parameters(&self) -> MlDsaParameters {
167 self.parameters
168 }
169
170 #[must_use]
172 pub const fn public_key(&self) -> &Matrix {
173 &self.public_key
174 }
175
176 #[must_use = "observe completion before reusing erased storage"]
178 pub const fn cleanup(&self) -> &DeviceErasure {
179 &self.cleanup
180 }
181
182 pub fn erase(self) -> Result<DeviceErasure> {
186 Ok(DeviceErasure {
187 inner: self.inner.erase()?,
188 })
189 }
190}
191
192#[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 #[must_use]
204 pub const fn parameters(&self) -> MlKemParameters {
205 self.parameters
206 }
207
208 #[must_use]
210 pub const fn public_key(&self) -> &Matrix {
211 &self.public_key
212 }
213
214 #[must_use = "observe completion before reusing erased storage"]
216 pub const fn cleanup(&self) -> &DeviceErasure {
217 &self.cleanup
218 }
219
220 pub fn erase(self) -> Result<DeviceErasure> {
224 Ok(DeviceErasure {
225 inner: self.inner.erase()?,
226 })
227 }
228}
229
230#[must_use = "explicitly erase the device shared secret after its final consumer"]
232pub struct DeviceSharedSecret {
233 inner: MlKemSharedSecret,
234}
235
236impl DeviceSharedSecret {
237 pub fn erase(self) -> Result<DeviceErasure> {
241 Ok(DeviceErasure {
242 inner: self.inner.erase()?,
243 })
244 }
245}
246
247#[must_use]
250pub struct DeviceSignature {
251 pub signature: Matrix,
253 pub status: Matrix,
255 pub cleanup: DeviceErasure,
257}
258
259#[must_use]
262pub struct DeviceEncapsulation {
263 pub shared_secret: DeviceSharedSecret,
265 pub ciphertext: Matrix,
267 pub status: Matrix,
269 pub cleanup: DeviceErasure,
271}
272
273#[must_use = "commit submits the deferred batch; abandoning fails its completions"]
281pub struct PqcSecretScope {
282 inner: crate::runtime::SecretLoweringScope,
283}
284
285pub fn begin_secret_scope(runtime: &Runtime) -> Result<PqcSecretScope> {
289 Ok(PqcSecretScope {
290 inner: runtime.handle().begin_secret_lowering()?,
291 })
292}
293
294#[derive(Clone, Copy, Debug, PartialEq, Eq)]
297pub struct PqcSecretScopeNode {
298 pub uses_secret: bool,
300 pub records_erasure: bool,
302 pub retains_public: bool,
304}
305
306impl PqcSecretScope {
307 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 pub fn commit(self) -> Result<()> {
326 self.inner.commit().map(|_| ())
327 }
328}
329
330#[must_use]
333pub struct DeviceDecapsulation {
334 pub shared_secret: DeviceSharedSecret,
336 pub cleanup: DeviceErasure,
338}
339
340#[must_use]
343pub struct DeviceDerivation {
344 pub derived: Matrix,
346 pub cleanup: DeviceErasure,
348}
349
350pub 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
370pub 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
385pub 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
415pub 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
438pub 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
466pub 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
497pub 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
530pub 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
552pub 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
570pub 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#[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#[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}