libslug 0.9.1

A Rust Library For Cryptography Intended For Slug20 That Supports X59 Certificate Format and Post-Quantum Cryptography
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
//! # ML-DSA3 (Dilithium65)
//! 
//! ML-DSA Digital Signature Scheme using Level 3 security and the ML-DSA crate. Includes keypair, public key, secret key, signature.
//! 
//! Implements Zeroize and Serialize.
//! 
//! ### Sizes
//! 
//! Public Key Size: 1952
//! Secret Key Size: 4032
//! Signature Size: 3309
//! 
//! ### Features
//! 
//! - [X] Encoding
//!     - [X] IntoEncoding
//!         - [X] Public Key
//!         - [X] Secret Key
//!         - [X] Signature
//!     - [X] FromEncoding
//!         - [X] Public Key
//!         - [X] Secret Key
//!         - [X] Signature
//!     - [ ] IntoPem
use ml_dsa::{self, KeyGen};
use rand::rngs::OsRng;

use serde::{Serialize, Deserialize};
use serde_big_array::BigArray;
//use subtle_encoding::Hex;
use zeroize::{Zeroize, ZeroizeOnDrop};
use crate::errors::SlugErrors;
use crate::slugcrypt::traits::FromEncoding;
use crate::slugcrypt::traits::IntoEncoding;

use subtle_encoding::Encoding;
use subtle_encoding::hex;
use subtle_encoding::Error as HexError;
use slugencode::SlugEncodingUsage;
use slugencode::SlugEncodings;

//use hybrid_array::ArrayN;
use hybrid_array_new::ArrayN;

use rand::RngCore;
use rand::CryptoRng;

pub const MLDSA3_PUBLIC_KEY_SIZE: usize = 1952;
pub const MLDSA3_SECRET_KEY_SIZE: usize = 4032;
pub const MLDSA3_SIGNATURE_SIZE: usize = 3309;

pub mod protocol_info {
    pub const ALGORITHM: &str = "ML-DSA";
    pub const MLDSA3_PUBLIC_KEY_SIZE: usize = 1952;
    pub const MLDSA3_SECRET_KEY_SIZE: usize = 4032;
    pub const MLDSA3_SIGNATURE_SIZE: usize = 3309;
}

/// # MLDSA3: Public Key
/// 
/// The Public Key of MLDSA (Dilithium65)
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Zeroize, ZeroizeOnDrop, PartialOrd, Hash)]
pub struct MLDSA3PublicKey {
    #[serde(with = "BigArray")]
    pub pk: [u8; MLDSA3_PUBLIC_KEY_SIZE],
}

/// # MLDSA3: Secret Key
/// 
/// The Secret Key of MLDSA (Dilithium65)
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Zeroize, ZeroizeOnDrop, PartialOrd, Hash)]
pub struct MLDSA3SecretKey {
    #[serde(with = "BigArray")]
    pub sk: [u8; MLDSA3_SECRET_KEY_SIZE],
}

/// # MLDSA3: Signature
/// 
/// The Signature of MLDSA (Dilithium65)
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Zeroize, ZeroizeOnDrop, PartialOrd, Hash)]
pub struct MLDSA3Signature {
    #[serde(with = "BigArray")]
    pub signature: [u8; MLDSA3_SIGNATURE_SIZE],
}

/// # MLDSA3: Keypair (Public Key and Secret Key)
/// 
/// The MLDSA3 Keypair
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Zeroize, ZeroizeOnDrop, PartialOrd, Hash)]
pub struct MLDSA3Keypair {
    pub public_key: MLDSA3PublicKey,
    pub secret_key: MLDSA3SecretKey,
}

/// # SlugMLDSA3 (Dilithium65)
/// 
/// Includes Generation
pub struct SlugMLDSA3;

impl IntoEncoding for MLDSA3PublicKey {
    fn to_base32(&self) -> Result<String,slugencode::prelude::SlugEncodingError> {
        let encoder = SlugEncodingUsage::new(SlugEncodings::Base32);
        let output = encoder.encode(self.as_bytes());
        return output
    }
    fn to_base32_unpadded(&self) -> Result<String,slugencode::prelude::SlugEncodingError> {
        let encoder = SlugEncodingUsage::new(SlugEncodings::Base32unpadded);
        let output = encoder.encode(self.as_bytes());
        return output
    }
    fn to_base58(&self) -> Result<String,slugencode::prelude::SlugEncodingError> {
        let encoder = SlugEncodingUsage::new(SlugEncodings::Base58);
        let output = encoder.encode(self.as_bytes());
        return output
    }
    fn to_base64(&self) -> Result<String,slugencode::prelude::SlugEncodingError> {
        let encoder = SlugEncodingUsage::new(SlugEncodings::Base64);
        let output = encoder.encode(self.as_bytes());
        return output
    }
    fn to_base64_url_safe(&self) -> Result<String,slugencode::prelude::SlugEncodingError> {
        let encoder = SlugEncodingUsage::new(SlugEncodings::Base64urlsafe);
        let output = encoder.encode(self.as_bytes());
        return output
    }
    fn to_hex(&self) -> Result<String,slugencode::prelude::SlugEncodingError> {
        let encoder = SlugEncodingUsage::new(SlugEncodings::Hex);
        let output = encoder.encode(self.as_bytes());
        return output
    }
}

impl IntoEncoding for MLDSA3SecretKey {
    fn to_base32(&self) -> Result<String,slugencode::prelude::SlugEncodingError> {
        let encoder = SlugEncodingUsage::new(SlugEncodings::Base32);
        let output = encoder.encode(self.as_bytes());
        return output
    }
    fn to_base32_unpadded(&self) -> Result<String,slugencode::prelude::SlugEncodingError> {
        let encoder = SlugEncodingUsage::new(SlugEncodings::Base32unpadded);
        let output = encoder.encode(self.as_bytes());
        return output
    }
    fn to_base58(&self) -> Result<String,slugencode::prelude::SlugEncodingError> {
        let encoder = SlugEncodingUsage::new(SlugEncodings::Base58);
        let output = encoder.encode(self.as_bytes());
        return output
    }
    fn to_base64(&self) -> Result<String,slugencode::prelude::SlugEncodingError> {
        let encoder = SlugEncodingUsage::new(SlugEncodings::Base64);
        let output = encoder.encode(self.as_bytes());
        return output
    }
    fn to_base64_url_safe(&self) -> Result<String,slugencode::prelude::SlugEncodingError> {
        let encoder = SlugEncodingUsage::new(SlugEncodings::Base64urlsafe);
        let output = encoder.encode(self.as_bytes());
        return output
    }
    fn to_hex(&self) -> Result<String,slugencode::prelude::SlugEncodingError> {
        let encoder = SlugEncodingUsage::new(SlugEncodings::Hex);
        let output = encoder.encode(self.as_bytes());
        return output
    }
}

impl IntoEncoding  for MLDSA3Signature {
    fn to_base32(&self) -> Result<String,slugencode::prelude::SlugEncodingError> {
        let encoder = SlugEncodingUsage::new(SlugEncodings::Base32);
        let output = encoder.encode(self.as_bytes());
        return output
    }
    fn to_base32_unpadded(&self) -> Result<String,slugencode::prelude::SlugEncodingError> {
        let encoder = SlugEncodingUsage::new(SlugEncodings::Base32unpadded);
        let output = encoder.encode(self.as_bytes());
        return output
    }
    fn to_base58(&self) -> Result<String,slugencode::prelude::SlugEncodingError> {
        let encoder = SlugEncodingUsage::new(SlugEncodings::Base58);
        let output = encoder.encode(self.as_bytes());
        return output
    }
    fn to_base64(&self) -> Result<String,slugencode::prelude::SlugEncodingError> {
        let encoder = SlugEncodingUsage::new(SlugEncodings::Base64);
        let output = encoder.encode(self.as_bytes());
        return output
    }
    fn to_base64_url_safe(&self) -> Result<String,slugencode::prelude::SlugEncodingError> {
        let encoder = SlugEncodingUsage::new(SlugEncodings::Base64urlsafe);
        let output = encoder.encode(self.as_bytes());
        return output
    }
    fn to_hex(&self) -> Result<String,slugencode::prelude::SlugEncodingError> {
        let encoder = SlugEncodingUsage::new(SlugEncodings::Hex);
        let output = encoder.encode(self.as_bytes());
        return output
    }
}

impl FromEncoding for MLDSA3PublicKey {
    fn from_base32<T: AsRef<str>>(s: T) -> Result<MLDSA3PublicKey, SlugErrors> {
        let decoder = SlugEncodingUsage::new(SlugEncodings::Base32);
        let output = decoder.decode(s.as_ref())?;
        let key = MLDSA3PublicKey::from_bytes(&output)?;
        return Ok(key)
    }
    fn from_base32_unpadded<T: AsRef<str>>(s: T) -> Result<MLDSA3PublicKey, SlugErrors> {
        let decoder = SlugEncodingUsage::new(SlugEncodings::Base32unpadded);
        let output = decoder.decode(s.as_ref())?;
        let key = MLDSA3PublicKey::from_bytes(&output)?;
        return Ok(key)
    }
    fn from_base58<T: AsRef<str>>(s: T) -> Result<MLDSA3PublicKey, SlugErrors> {
        let decoder = SlugEncodingUsage::new(SlugEncodings::Base58);
        let output = decoder.decode(s.as_ref())?;
        let key = MLDSA3PublicKey::from_bytes(&output)?;
        return Ok(key)
    }
    fn from_base64<T: AsRef<str>>(s: T) -> Result<MLDSA3PublicKey, SlugErrors> {
        let decoder = SlugEncodingUsage::new(SlugEncodings::Base64);
        let output = decoder.decode(s.as_ref())?;
        let key = MLDSA3PublicKey::from_bytes(&output)?;
        return Ok(key)
    }
    fn from_base64_url_safe<T: AsRef<str>>(s: T) -> Result<MLDSA3PublicKey, SlugErrors> {
        let decoder = SlugEncodingUsage::new(SlugEncodings::Base64urlsafe);
        let output = decoder.decode(s.as_ref())?;
        let key = MLDSA3PublicKey::from_bytes(&output)?;
        return Ok(key)
    }
    fn from_hex<T: AsRef<str>>(s: T) -> Result<Self, SlugErrors> {
        let decoder = SlugEncodingUsage::new(SlugEncodings::Hex);
        let output = decoder.decode(s.as_ref())?;
        let key = MLDSA3PublicKey::from_bytes(&output)?;
        return Ok(key)
    }
}

impl FromEncoding for MLDSA3SecretKey {
    fn from_base32<T: AsRef<str>>(s: T) -> Result<MLDSA3SecretKey, SlugErrors> {
        let decoder = SlugEncodingUsage::new(SlugEncodings::Base32);
        let output = decoder.decode(s.as_ref())?;
        let key = MLDSA3SecretKey::from_bytes(&output)?;
        return Ok(key)
    }
    fn from_base32_unpadded<T: AsRef<str>>(s: T) -> Result<MLDSA3SecretKey, SlugErrors> {
        let decoder = SlugEncodingUsage::new(SlugEncodings::Base32unpadded);
        let output = decoder.decode(s.as_ref())?;
        let key = MLDSA3SecretKey::from_bytes(&output)?;
        return Ok(key)
    }
    fn from_base58<T: AsRef<str>>(s: T) -> Result<MLDSA3SecretKey, SlugErrors> {
        let decoder = SlugEncodingUsage::new(SlugEncodings::Base58);
        let output = decoder.decode(s.as_ref())?;
        let key = MLDSA3SecretKey::from_bytes(&output)?;
        return Ok(key)
    }
    fn from_base64<T: AsRef<str>>(s: T) -> Result<MLDSA3SecretKey, SlugErrors> {
        let decoder = SlugEncodingUsage::new(SlugEncodings::Base64);
        let output = decoder.decode(s.as_ref())?;
        let key = MLDSA3SecretKey::from_bytes(&output)?;
        return Ok(key)
    }
    fn from_base64_url_safe<T: AsRef<str>>(s: T) -> Result<MLDSA3SecretKey, SlugErrors> {
        let decoder = SlugEncodingUsage::new(SlugEncodings::Base64urlsafe);
        let output = decoder.decode(s.as_ref())?;
        let key = MLDSA3SecretKey::from_bytes(&output)?;
        return Ok(key)
    }
    fn from_hex<T: AsRef<str>>(s: T) -> Result<MLDSA3SecretKey, SlugErrors> {
        let decoder = SlugEncodingUsage::new(SlugEncodings::Hex);
        let output = decoder.decode(s.as_ref())?;
        let key = MLDSA3SecretKey::from_bytes(&output)?;
        return Ok(key)
    }
}

impl FromEncoding for MLDSA3Signature {
    fn from_base32<T: AsRef<str>>(s: T) -> Result<MLDSA3Signature, SlugErrors> {
        let decoder = SlugEncodingUsage::new(SlugEncodings::Base32);
        let output = decoder.decode(s.as_ref())?;
        let key = MLDSA3Signature::from_bytes(&output)?;
        return Ok(key)
    }
    fn from_base32_unpadded<T: AsRef<str>>(s: T) -> Result<MLDSA3Signature, SlugErrors> {
        let decoder = SlugEncodingUsage::new(SlugEncodings::Base32unpadded);
        let output = decoder.decode(s.as_ref())?;
        let key = MLDSA3Signature::from_bytes(&output)?;
        return Ok(key)
    }
    fn from_base58<T: AsRef<str>>(s: T) -> Result<MLDSA3Signature, SlugErrors> {
        let decoder = SlugEncodingUsage::new(SlugEncodings::Base58);
        let output = decoder.decode(s.as_ref())?;
        let key = MLDSA3Signature::from_bytes(&output)?;
        return Ok(key)
    }
    fn from_base64<T: AsRef<str>>(s: T) -> Result<MLDSA3Signature, SlugErrors> {
        let decoder = SlugEncodingUsage::new(SlugEncodings::Base64);
        let output = decoder.decode(s.as_ref())?;
        let key = MLDSA3Signature::from_bytes(&output)?;
        return Ok(key)
    }
    fn from_base64_url_safe<T: AsRef<str>>(s: T) -> Result<MLDSA3Signature, SlugErrors> {
        let decoder = SlugEncodingUsage::new(SlugEncodings::Base64urlsafe);
        let output = decoder.decode(s.as_ref())?;
        let key = MLDSA3Signature::from_bytes(&output)?;
        return Ok(key)
    }
    fn from_hex<T: AsRef<str>>(s: T) -> Result<MLDSA3Signature, SlugErrors> {
        let decoder = SlugEncodingUsage::new(SlugEncodings::Hex);
        let output = decoder.decode(s.as_ref())?;
        let key = MLDSA3Signature::from_bytes(&output)?;
        return Ok(key)
    }
}

impl SlugMLDSA3 {
    /// Generate Keypair using Operating System Randomness
    pub fn generate() -> MLDSA3Keypair {
        let mut rng: OsRng = OsRng::default();
        let kp: ml_dsa::KeyPair<ml_dsa::MlDsa65> = ml_dsa::MlDsa65::key_gen(&mut rng);

        let mut pk_output: [u8; 1952] = [0u8; 1952];
        let mut sk_output: [u8; 4032] = [0u8; 4032];
        pk_output.copy_from_slice(kp.verifying_key().encode().as_ref());
        sk_output.copy_from_slice(kp.signing_key().encode().as_ref());

        let public_key: MLDSA3PublicKey = MLDSA3PublicKey { pk: pk_output };
        let secret_key: MLDSA3SecretKey = MLDSA3SecretKey { sk: sk_output };

        return MLDSA3Keypair {
            public_key,
            secret_key,
        }
    }
}

impl MLDSA3Keypair {
    /// Retrieve Public Key
    pub fn public_key(&self) -> &MLDSA3PublicKey {
        &self.public_key
    }
    /// Retrieve Secret Key
    pub fn secret_key(&self) -> &MLDSA3SecretKey {
        &self.secret_key
    }
    /// # Sign (with Context) (MLDSA3/Dilithium65)
    /// 
    /// Sign with Context
    pub fn sign<T: AsRef<[u8]>>(&self, message: T, ctx: T) -> Result<MLDSA3Signature, ml_dsa::Error> {
        self.secret_key.sign(message, ctx)
    }
    /// # Verify (MLDSA65)
    /// 
    /// Verify with Context
    pub fn verify<T: AsRef<[u8]>>(&self, message: T, ctx: T, signature: &MLDSA3Signature) -> Result<bool, ml_dsa::Error> {
        self.public_key.verify(message, ctx, signature)
    }
}

impl MLDSA3PublicKey {
    /// From Bytes (1952 bytes)
    pub fn from_bytes(bytes: &[u8]) -> Result<Self, SlugErrors> {
        let mut pk_array: [u8; 1952] = [0u8; 1952];

        if bytes.len() == 1952 {
            pk_array.copy_from_slice(bytes);
            Ok(Self { pk: pk_array })
        } else {
            Err(SlugErrors::InvalidLengthFromBytes)
        }
    }
    /// From Hexadecimal (Upper)
    /*
    pub fn from_hex<T: AsRef<str>>(s_hex: T) -> Result<Vec<u8>,HexError> {
        let decoded = hex::decode_upper(s_hex.as_ref().as_bytes())?;
        Ok(decoded)
    }
    */
    /// as bytes (1952)
    pub fn as_bytes(&self) -> &[u8] {
        &self.pk
    }
    /// to byte array (of 1952 bytes)
    pub fn to_bytes(&self) -> [u8;1952] {
        return self.pk
    }
    /// to usable type
    pub fn to_usable_type(&self) -> ml_dsa::VerifyingKey<ml_dsa::MlDsa65> {
        let hybrid = hybrid_array_new::ArrayN::<u8, 1952>::from_slice(&self.pk);
        let usable: ml_dsa::VerifyingKey<ml_dsa::MlDsa65> = ml_dsa::VerifyingKey::decode(hybrid);
        return usable;
    }
    /// # Verify (With Context) (MLDSA65)
    /// 
    /// Verifies a given message with certain context given a signature and public key
    pub fn verify<T: AsRef<[u8]>>(&self, message: T, ctx: T, signature: &MLDSA3Signature) -> Result<bool, ml_dsa::Error> {
        let vk = self.to_usable_type();
        let sig = signature.to_usable_type();
        Ok(vk.verify_with_context(message.as_ref(), ctx.as_ref(), &sig))
    }
}

impl MLDSA3SecretKey {
    /// From Bytes (4032 bytes)
    pub fn from_bytes(bytes: &[u8]) -> Result<Self, SlugErrors> {
        let mut sk_array: [u8; 4032] = [0u8; 4032];

        if bytes.len() == 4032 {
            sk_array.copy_from_slice(bytes);
            Ok(Self { sk: sk_array })
        } else {
            Err(SlugErrors::InvalidLengthFromBytes)
        }
    }
    /*
    /// From Hexadecimal (Upper)
    pub fn from_hex<T: AsRef<str>>(s_hex: T) -> Result<Vec<u8>,HexError> {
        let decoded = hex::decode_upper(s_hex.as_ref().as_bytes())?;
        Ok(decoded)
    }
    */
    /// as bytes (4032 bytes)
    pub fn as_bytes(&self) -> &[u8] {
        &self.sk
    }
    /// to usable type
    pub fn to_usable_type(&self) -> ml_dsa::SigningKey<ml_dsa::MlDsa65> {
        let hybrid = hybrid_array_new::ArrayN::<u8, 4032>::from_slice(&self.sk);
        let usable: ml_dsa::SigningKey<ml_dsa::MlDsa65> = ml_dsa::SigningKey::decode(hybrid);
        return usable;
    }
    /// # Sign (with context) (MLDSA65)
    /// 
    /// Signs with context
    pub fn sign<T: AsRef<[u8]>>(&self, message: T, ctx: T) -> Result<MLDSA3Signature, ml_dsa::Error> {
        let sk = self.to_usable_type();
        let mut rng = OsRng::default();
        let d = sk.sign_randomized(message.as_ref(), ctx.as_ref(), &mut rng)?;
        
        let sig = MLDSA3Signature::from_bytes(d.encode().as_ref()).unwrap();
        Ok(sig)

    }
}

impl MLDSA3Signature {
    /// From Bytes (3309 bytes)
    pub fn from_bytes(bytes: &[u8]) -> Result<Self, SlugErrors> {
        let mut sig_array: [u8; 3309] = [0u8; 3309];

        if bytes.len() == 3309 {
            sig_array.copy_from_slice(bytes);
            Ok(Self { signature: sig_array })
        } 
        else {
            Err(SlugErrors::InvalidLengthFromBytes)
        }
    }
    /// From Hexadecimal (Upper)
    /*
    pub fn from_hex<T: AsRef<str>>(s_hex: T) -> Result<Vec<u8>,HexError> {
        let decoded = hex::decode_upper(s_hex.as_ref().as_bytes())?;
        Ok(decoded)
    }
    */
    /// as bytes (3309 bytes)
    pub fn as_bytes(&self) -> &[u8] {
        &self.signature
    }
    /// to usable type
    pub fn to_usable_type(&self) -> ml_dsa::Signature<ml_dsa::MlDsa65> {
        let hybrid = hybrid_array_new::ArrayN::<u8, 3309>::from_slice(&self.signature);
        let usable: ml_dsa::Signature<ml_dsa::MlDsa65> = ml_dsa::Signature::decode(hybrid).unwrap();
        return usable;
    }
}

#[test]
fn gen() {
    let keypair = SlugMLDSA3::generate();
    let signature = keypair.sign("Hello, ML_DSA3!", "Context").unwrap();
    let is_valid = keypair.verify("Hello, ML_DSA3!", "Context", &signature);

    println!("Is_Valid: {}", is_valid.unwrap());


}