Skip to main content

oa/crypto/pqc/
host.rs

1//! Host ML-DSA-65 values and operations, plus FIPS parameter metadata.
2
3use ml_dsa::{
4	Generate, Keypair as _, MlDsa65, Signature as MlSignature, Signer as _, SigningKey,
5	Verifier as _, VerifyingKey,
6};
7
8use crate::core::operation::crypto::pqc as contracts;
9use crate::{Error, Hash, Result};
10
11/// Encoded ML-DSA-65 public-key size.
12pub const PUBLIC_KEY_SIZE: usize = contracts::ML_DSA_65_PUBLIC_KEY_SIZE;
13/// Expanded ML-DSA-65 secret-key size used by the OA donor ABI.
14pub const SECRET_KEY_SIZE: usize = 4_032;
15/// Encoded ML-DSA-65 signature size.
16pub const SIGNATURE_SIZE: usize = contracts::ML_DSA_65_SIGNATURE_SIZE;
17
18/// FIPS 204 parameter set for device-resident batch verification.
19///
20/// Host key and signature types in this module continue to describe ML-DSA-65.
21#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
22pub enum MlDsaParameters {
23	/// ML-DSA-44, security category 2.
24	MlDsa44,
25	/// ML-DSA-65, security category 3.
26	MlDsa65,
27	/// ML-DSA-87, security category 5.
28	MlDsa87,
29}
30
31impl MlDsaParameters {
32	/// Encoded FIPS 204 public-key size, in bytes.
33	#[must_use]
34	pub const fn public_key_size(self) -> usize {
35		match self {
36			Self::MlDsa44 => contracts::ML_DSA_44_PUBLIC_KEY_SIZE,
37			Self::MlDsa65 => PUBLIC_KEY_SIZE,
38			Self::MlDsa87 => contracts::ML_DSA_87_PUBLIC_KEY_SIZE,
39		}
40	}
41
42	/// Encoded FIPS 204 signature size, in bytes.
43	#[must_use]
44	pub const fn signature_size(self) -> usize {
45		match self {
46			Self::MlDsa44 => contracts::ML_DSA_44_SIGNATURE_SIZE,
47			Self::MlDsa65 => SIGNATURE_SIZE,
48			Self::MlDsa87 => contracts::ML_DSA_87_SIGNATURE_SIZE,
49		}
50	}
51}
52
53/// An encoded ML-DSA-65 public key.
54#[derive(Clone, PartialEq, Eq, Hash)]
55pub struct PublicKey([u8; PUBLIC_KEY_SIZE]);
56
57impl Default for PublicKey {
58	fn default() -> Self {
59		Self([0; PUBLIC_KEY_SIZE])
60	}
61}
62
63impl PublicKey {
64	/// Parse exactly [`PUBLIC_KEY_SIZE`] bytes.
65	pub fn new_from_bytes(bytes: &[u8]) -> Result<Self> {
66		Ok(Self(copy_array(bytes, "ML-DSA-65 public key")?))
67	}
68
69	/// Return the fixed-size encoded key.
70	#[must_use]
71	pub const fn as_bytes(&self) -> &[u8; PUBLIC_KEY_SIZE] {
72		&self.0
73	}
74
75	/// Serialize the key to its fixed-size wire representation.
76	#[must_use]
77	pub fn to_bytes(&self) -> [u8; PUBLIC_KEY_SIZE] {
78		self.0
79	}
80
81	/// Return whether every encoded byte is zero.
82	#[must_use]
83	pub fn is_zero(&self) -> bool {
84		self.0.iter().all(|byte| *byte == 0)
85	}
86
87	/// Format the first 16 bytes as lowercase hexadecimal text.
88	#[must_use]
89	pub fn to_short_hex(&self) -> String {
90		short_hex(&self.0)
91	}
92}
93
94impl std::fmt::Debug for PublicKey {
95	fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
96		formatter
97			.debug_tuple("PublicKey")
98			.field(&self.to_short_hex())
99			.finish()
100	}
101}
102
103/// An ML-DSA-65 secret signing key.
104///
105/// The implementation stores the standard 32-byte seed plus its expanded
106/// signing state; both are zeroized by the RustCrypto dependency on drop.
107pub struct SecretKey(SigningKey<MlDsa65>);
108
109impl std::fmt::Debug for SecretKey {
110	fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
111		formatter.debug_struct("SecretKey").finish_non_exhaustive()
112	}
113}
114
115/// An encoded ML-DSA-65 signature.
116#[derive(Clone, PartialEq, Eq)]
117pub struct Signature([u8; SIGNATURE_SIZE]);
118
119impl Default for Signature {
120	fn default() -> Self {
121		Self([0; SIGNATURE_SIZE])
122	}
123}
124
125impl Signature {
126	/// Parse exactly [`SIGNATURE_SIZE`] bytes.
127	pub fn new_from_bytes(bytes: &[u8]) -> Result<Self> {
128		Ok(Self(copy_array(bytes, "ML-DSA-65 signature")?))
129	}
130
131	/// Return the fixed-size encoded signature.
132	#[must_use]
133	pub const fn as_bytes(&self) -> &[u8; SIGNATURE_SIZE] {
134		&self.0
135	}
136
137	/// Serialize the signature to its fixed-size wire representation.
138	#[must_use]
139	pub fn to_bytes(&self) -> [u8; SIGNATURE_SIZE] {
140		self.0
141	}
142
143	/// Return whether every encoded byte is zero.
144	#[must_use]
145	pub fn is_zero(&self) -> bool {
146		self.0.iter().all(|byte| *byte == 0)
147	}
148
149	/// Format the first 16 bytes as lowercase hexadecimal text.
150	#[must_use]
151	pub fn to_short_hex(&self) -> String {
152		short_hex(&self.0)
153	}
154}
155
156impl std::fmt::Debug for Signature {
157	fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
158		formatter
159			.debug_tuple("Signature")
160			.field(&self.to_short_hex())
161			.finish()
162	}
163}
164
165/// One generated ML-DSA-65 key pair.
166pub struct Keypair {
167	/// Public verification key.
168	pub public_key: PublicKey,
169	/// Secret signing key.
170	pub secret_key: SecretKey,
171}
172
173impl std::fmt::Debug for Keypair {
174	fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
175		formatter
176			.debug_struct("Keypair")
177			.field("public_key", &self.public_key)
178			.field("secret_key", &self.secret_key)
179			.finish()
180	}
181}
182
183/// Generate a random ML-DSA-65 key pair using the operating-system RNG.
184pub fn generate_keypair() -> Result<Keypair> {
185	let signing = SigningKey::<MlDsa65>::try_generate()
186		.map_err(|_| Error::internal("operating-system random generation failed"))?;
187	let encoded = signing.verifying_key().encode();
188	let mut public_key = [0_u8; PUBLIC_KEY_SIZE];
189	public_key.copy_from_slice(encoded.as_slice());
190	Ok(Keypair {
191		public_key: PublicKey(public_key),
192		secret_key: SecretKey(signing),
193	})
194}
195
196/// Sign an arbitrary message with ML-DSA-65.
197pub fn sign(message: &[u8], secret_key: &SecretKey) -> Result<Signature> {
198	let signature = secret_key
199		.0
200		.try_sign(message)
201		.map_err(|_| Error::internal("ML-DSA-65 signing failed"))?;
202	let encoded = signature.encode();
203	let mut bytes = [0_u8; SIGNATURE_SIZE];
204	bytes.copy_from_slice(encoded.as_slice());
205	Ok(Signature(bytes))
206}
207
208/// Sign a canonical OA hash with ML-DSA-65.
209pub fn sign_hash(hash: &Hash, secret_key: &SecretKey) -> Result<Signature> {
210	sign(hash.as_bytes(), secret_key)
211}
212
213/// Verify an ML-DSA-65 message signature. Malformed encodings fail closed.
214#[must_use]
215pub fn verify(message: &[u8], signature: &Signature, public_key: &PublicKey) -> bool {
216	let Some(signature) = MlSignature::<MlDsa65>::decode((&signature.0).into()) else {
217		return false;
218	};
219	let verifying_key = VerifyingKey::<MlDsa65>::decode((&public_key.0).into());
220	verifying_key.verify(message, &signature).is_ok()
221}
222
223/// Verify an ML-DSA-65 signature over a canonical OA hash.
224#[must_use]
225pub fn verify_hash(hash: &Hash, signature: &Signature, public_key: &PublicKey) -> bool {
226	verify(hash.as_bytes(), signature, public_key)
227}
228
229fn copy_array<const N: usize>(bytes: &[u8], label: &str) -> Result<[u8; N]> {
230	<[u8; N]>::try_from(bytes)
231		.map_err(|_| Error::invalid_argument(format!("{label} must contain exactly {N} bytes")))
232}
233
234fn short_hex(bytes: &[u8]) -> String {
235	const HEX: &[u8; 16] = b"0123456789abcdef";
236	let mut output = String::with_capacity(32);
237	for byte in bytes.iter().take(16) {
238		output.push(char::from(HEX[usize::from(byte >> 4)]));
239		output.push(char::from(HEX[usize::from(byte & 0x0f)]));
240	}
241	output
242}