1use 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
11pub const PUBLIC_KEY_SIZE: usize = contracts::ML_DSA_65_PUBLIC_KEY_SIZE;
13pub const SECRET_KEY_SIZE: usize = 4_032;
15pub const SIGNATURE_SIZE: usize = contracts::ML_DSA_65_SIGNATURE_SIZE;
17
18#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
22pub enum MlDsaParameters {
23 MlDsa44,
25 MlDsa65,
27 MlDsa87,
29}
30
31impl MlDsaParameters {
32 #[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 #[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#[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 pub fn new_from_bytes(bytes: &[u8]) -> Result<Self> {
66 Ok(Self(copy_array(bytes, "ML-DSA-65 public key")?))
67 }
68
69 #[must_use]
71 pub const fn as_bytes(&self) -> &[u8; PUBLIC_KEY_SIZE] {
72 &self.0
73 }
74
75 #[must_use]
77 pub fn to_bytes(&self) -> [u8; PUBLIC_KEY_SIZE] {
78 self.0
79 }
80
81 #[must_use]
83 pub fn is_zero(&self) -> bool {
84 self.0.iter().all(|byte| *byte == 0)
85 }
86
87 #[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
103pub 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#[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 pub fn new_from_bytes(bytes: &[u8]) -> Result<Self> {
128 Ok(Self(copy_array(bytes, "ML-DSA-65 signature")?))
129 }
130
131 #[must_use]
133 pub const fn as_bytes(&self) -> &[u8; SIGNATURE_SIZE] {
134 &self.0
135 }
136
137 #[must_use]
139 pub fn to_bytes(&self) -> [u8; SIGNATURE_SIZE] {
140 self.0
141 }
142
143 #[must_use]
145 pub fn is_zero(&self) -> bool {
146 self.0.iter().all(|byte| *byte == 0)
147 }
148
149 #[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
165pub struct Keypair {
167 pub public_key: PublicKey,
169 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
183pub 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
196pub 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
208pub fn sign_hash(hash: &Hash, secret_key: &SecretKey) -> Result<Signature> {
210 sign(hash.as_bytes(), secret_key)
211}
212
213#[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#[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}