1use super::*;
4
5pub struct SignatureEngine {
7 signing_algorithms: HashMap<KeyAlgorithm, SigningAlgorithm>,
8 verification_algorithms: HashMap<KeyAlgorithm, VerificationAlgorithm>,
9 pub(super) signature_storage: SignatureStorage,
10 pub(super) performance_optimizer: SignaturePerformanceOptimizer,
11}
12
13#[derive(Debug, Clone)]
15pub struct SigningAlgorithm {
16 pub algorithm_id: String,
17 pub key_algorithm: KeyAlgorithm,
18 pub hash_function: String,
19 pub parameters: SigningParameters,
20}
21
22#[derive(Debug, Clone)]
24pub struct SigningParameters {
25 pub padding: Option<String>,
26 pub salt_length: Option<usize>,
27 pub deterministic: bool,
28 pub custom_params: HashMap<String, Vec<u8>>,
29}
30
31#[derive(Debug, Clone)]
33pub struct VerificationAlgorithmConfig {
34 pub algorithm_id: String,
35 pub key_algorithm: KeyAlgorithm,
36 pub hash_function: String,
37 pub parameters: VerificationParameters,
38}
39
40#[derive(Debug, Clone)]
42pub struct VerificationParameters {
43 pub strict_verification: bool,
44 pub allow_weak_hashes: bool,
45 pub custom_params: HashMap<String, Vec<u8>>,
46}
47
48pub struct SignatureStorage {
50 signatures: HashMap<String, Signature>,
51 verification_records: HashMap<String, VerificationRecord>,
52 pub(super) audit_log: SignatureAuditLog,
53}
54
55#[derive(Debug, Clone)]
57pub struct SignatureRecord {
58 pub signature_id: String,
59 pub key_id: String,
60 pub algorithm: KeyAlgorithm,
61 pub data_hash: Vec<u8>,
62 pub signature: Vec<u8>,
63 pub timestamp: u64,
64 pub metadata: SignatureMetadata,
65}
66
67#[derive(Debug, Clone)]
69pub struct SignatureMetadata {
70 pub signer_id: String,
71 pub purpose: String,
72 pub context: Vec<String>,
73 pub validity_period: Option<(u64, u64)>,
74}
75
76#[derive(Debug, Clone)]
78pub struct VerificationRecord {
79 pub verification_id: String,
80 pub signature_id: String,
81 pub verifier_id: String,
82 pub result: VerificationResult,
83 pub timestamp: u64,
84}
85
86#[derive(Debug, Clone)]
88pub struct VerificationResult {
89 pub valid: bool,
90 pub error_message: Option<String>,
91 pub verification_time: u64,
92 pub confidence: f64,
93}
94
95pub struct SignatureAuditLog {
97 entries: Vec<SignatureAuditEntry>,
98 retention_policy: RetentionPolicy,
99}
100
101#[derive(Debug, Clone)]
103pub struct SignatureAuditEntry {
104 pub entry_id: String,
105 pub timestamp: u64,
106 pub signature_id: String,
107 pub operation: SignatureOperation,
108 pub user_id: String,
109 pub ip_address: String,
110 pub success: bool,
111}
112
113#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
115pub enum SignatureOperation {
116 Sign,
117 Verify,
118 Revoke,
119 Renew,
120}
121
122pub struct SignaturePerformanceOptimizer {
124 optimization_strategies: Vec<SignatureOptimizationStrategy>,
125 performance_metrics: SignaturePerformanceMetrics,
126}
127
128#[derive(Debug, Clone, PartialEq)]
130pub enum SignatureOptimizationStrategy {
131 BatchSigning,
132 Precomputation,
133 ParallelVerification,
134 Caching,
135 HardwareAcceleration,
136}
137
138#[derive(Debug, Clone)]
140pub struct SignaturePerformanceMetrics {
141 pub average_signing_time: f64,
142 pub average_verification_time: f64,
143 pub throughput: f64,
144 pub error_rate: f64,
145 pub cache_hit_rate: f64,
146}
147impl SignatureEngine {
148 pub fn new() -> Self {
150 Self {
151 signing_algorithms: HashMap::new(),
152 verification_algorithms: HashMap::new(),
153 signature_storage: SignatureStorage::new(),
154 performance_optimizer: SignaturePerformanceOptimizer::new(),
155 }
156 }
157
158 pub fn initialize(&mut self) -> Result<(), CryptographicError> {
160 self.signature_storage.initialize()?;
161 self.performance_optimizer.initialize()?;
162 Ok(())
163 }
164
165 pub fn add_signing_algorithm(&mut self, algorithm: SigningAlgorithm) {
167 self.signing_algorithms
168 .insert(algorithm.key_algorithm, algorithm);
169 }
170
171 pub fn get_signing_algorithm(&self, algorithm: &KeyAlgorithm) -> Option<&SigningAlgorithm> {
173 self.signing_algorithms.get(algorithm)
174 }
175
176 pub fn list_signing_algorithms(&self) -> impl Iterator<Item = &SigningAlgorithm> {
178 self.signing_algorithms.values()
179 }
180
181 pub fn add_verification_algorithm(
183 &mut self,
184 key_algorithm: KeyAlgorithm,
185 algorithm: VerificationAlgorithm,
186 ) {
187 self.verification_algorithms
188 .insert(key_algorithm, algorithm);
189 }
190
191 pub fn get_verification_algorithm(
193 &self,
194 algorithm: &KeyAlgorithm,
195 ) -> Option<&VerificationAlgorithm> {
196 self.verification_algorithms.get(algorithm)
197 }
198
199 pub fn list_verification_algorithms(&self) -> impl Iterator<Item = &VerificationAlgorithm> {
201 self.verification_algorithms.values()
202 }
203
204 fn fiduciary_context() -> CryptoContext {
207 CryptoContext {
208 domain: "qualia.fiduciary".to_string(),
209 purpose: "sign".to_string(),
210 timestamp: 0,
211 nonce: [0u8; 32],
212 }
213 }
214
215 pub fn sign_data(
217 &mut self,
218 private_key: &Key,
219 data: &[u8],
220 ) -> Result<Signature, CryptographicError> {
221 let start_time = std::time::Instant::now();
222
223 let signature_data = match private_key.key_algorithm {
224 KeyAlgorithm::MLDSA => {
225 let ctx = Self::fiduciary_context();
228 let sig = MlDsaSigner::sign_with_secret(&private_key.key_data, data, &ctx)
229 .map_err(|e| {
230 CryptographicError::SignatureError(format!("ML-DSA sign failed: {e}"))
231 })?;
232 sig.sig_bytes
233 }
234 KeyAlgorithm::SPHINCS => {
235 use fips205::slh_dsa_sha2_256s;
236 use fips205::traits::{SerDes, Signer};
237 let sk_arr: [u8; slh_dsa_sha2_256s::SK_LEN] =
238 private_key.key_data.as_slice().try_into().map_err(|_| {
239 CryptographicError::InvalidKey(format!(
240 "SPHINCS secret key must be {} bytes",
241 slh_dsa_sha2_256s::SK_LEN
242 ))
243 })?;
244 let sk = slh_dsa_sha2_256s::PrivateKey::try_from_bytes(&sk_arr)
245 .map_err(|e| CryptographicError::SignatureError(e.to_string()))?;
246 let sig = sk
247 .try_sign(data, b"", true)
248 .map_err(|e| CryptographicError::SignatureError(e.to_string()))?;
249 sig.to_vec()
250 }
251 KeyAlgorithm::ECDSA => {
252 #[cfg(feature = "interop-crypto")]
253 {
254 use crate::fiduciary_crypto::InteropEcdsaSigner;
255 let signer = InteropEcdsaSigner::from_secret_key(&private_key.key_data)
256 .map_err(|e| CryptographicError::SignatureError(e.to_string()))?;
257 let sig = signer
258 .sign(data)
259 .map_err(|e| CryptographicError::SignatureError(e.to_string()))?;
260 sig.sig_bytes
261 }
262 #[cfg(not(feature = "interop-crypto"))]
263 {
264 return Err(CryptographicError::UnsupportedAlgorithm(
265 "ECDSA requires interop-crypto feature".to_string(),
266 ));
267 }
268 }
269 KeyAlgorithm::RSA => {
270 #[cfg(feature = "interop-crypto")]
271 {
272 use rsa::pkcs1v15::SigningKey;
273 use rsa::sha2::Sha256;
274 use rsa::signature::{SignatureEncoding, Signer};
275 use rsa::{RsaPrivateKey, pkcs8::DecodePrivateKey};
276 let priv_key = RsaPrivateKey::from_pkcs8_der(&private_key.key_data)
277 .map_err(|e| CryptographicError::SignatureError(e.to_string()))?;
278 let signing_key = SigningKey::<Sha256>::new(priv_key);
279 signing_key.sign(data).to_bytes().to_vec()
280 }
281 #[cfg(not(feature = "interop-crypto"))]
282 {
283 return Err(CryptographicError::UnsupportedAlgorithm(
284 "RSA requires interop-crypto feature".to_string(),
285 ));
286 }
287 }
288 KeyAlgorithm::X25519 | KeyAlgorithm::Kyber | KeyAlgorithm::NTRU => {
289 return Err(CryptographicError::UnsupportedAlgorithm(
290 "key agreement keys cannot sign or verify".into(),
291 ));
292 }
293 _ => {
294 let hash = self.compute_data_hash(data)?;
296 self.sign_hash(&private_key, &hash)?
297 }
298 };
299
300 let signature = Signature {
301 signature_id: format!(
302 "sig_{}",
303 std::time::SystemTime::now()
304 .duration_since(std::time::UNIX_EPOCH)
305 .unwrap()
306 .as_secs()
307 ),
308 key_id: private_key.key_id.clone(),
309 algorithm: private_key.key_algorithm.clone(),
310 data: data.to_vec(),
311 signature: signature_data,
312 timestamp: start_time.elapsed().as_millis() as u64,
313 };
314
315 self.signature_storage.store_signature(signature.clone())?;
317
318 self.signature_storage.audit_log.log_entry(
320 &signature.signature_id,
321 SignatureOperation::Sign,
322 "system",
323 true,
324 );
325
326 self.performance_optimizer
328 .record_signing_time(start_time.elapsed().as_millis() as f64);
329
330 Ok(signature)
331 }
332
333 pub fn verify_signature(
335 &mut self,
336 public_key: &Key,
337 signature: &Signature,
338 data: &[u8],
339 ) -> Result<bool, CryptographicError> {
340 let start_time = std::time::Instant::now();
341
342 let is_valid = match public_key.key_algorithm {
343 KeyAlgorithm::MLDSA => {
344 let ctx = Self::fiduciary_context();
345 let sig = MlDsaSignature {
346 sig_bytes: signature.signature.clone(),
347 };
348 MlDsaSigner::verify_with_public(&public_key.key_data, data, &sig, &ctx).map_err(
349 |e| CryptographicError::SignatureError(format!("ML-DSA verify failed: {e}")),
350 )?
351 }
352 KeyAlgorithm::SPHINCS => {
353 use fips205::slh_dsa_sha2_256s;
354 use fips205::traits::{SerDes, Verifier};
355 let pk_arr: [u8; slh_dsa_sha2_256s::PK_LEN] =
356 public_key.key_data.as_slice().try_into().map_err(|_| {
357 CryptographicError::InvalidKey(format!(
358 "SPHINCS public key must be {} bytes",
359 slh_dsa_sha2_256s::PK_LEN
360 ))
361 })?;
362 let pk = slh_dsa_sha2_256s::PublicKey::try_from_bytes(&pk_arr)
363 .map_err(|e| CryptographicError::SignatureError(e.to_string()))?;
364 if signature.signature.len() != slh_dsa_sha2_256s::SIG_LEN {
365 return Ok(false);
366 }
367 let mut sig_arr = [0u8; slh_dsa_sha2_256s::SIG_LEN];
368 sig_arr.copy_from_slice(&signature.signature);
369 pk.verify(data, &sig_arr, b"")
370 }
371 KeyAlgorithm::ECDSA => {
372 #[cfg(feature = "interop-crypto")]
373 {
374 use crate::fiduciary_crypto::{InteropEcdsaSignature, InteropEcdsaSigner};
375 let signer = InteropEcdsaSigner::from_public_key(&public_key.key_data)
376 .map_err(|e| CryptographicError::SignatureError(e.to_string()))?;
377 let sig = InteropEcdsaSignature {
378 sig_bytes: signature.signature.clone(),
379 };
380 signer
381 .verify(data, &sig)
382 .map_err(|e| CryptographicError::SignatureError(e.to_string()))?
383 }
384 #[cfg(not(feature = "interop-crypto"))]
385 {
386 return Err(CryptographicError::UnsupportedAlgorithm(
387 "ECDSA requires interop-crypto feature".to_string(),
388 ));
389 }
390 }
391 KeyAlgorithm::RSA => {
392 #[cfg(feature = "interop-crypto")]
393 {
394 use rsa::pkcs1v15::{Signature as RsaSignature, VerifyingKey};
395 use rsa::sha2::Sha256;
396 use rsa::signature::Verifier;
397 use rsa::{RsaPublicKey, pkcs8::DecodePublicKey};
398 let pub_key = RsaPublicKey::from_public_key_der(&public_key.key_data)
399 .map_err(|e| CryptographicError::SignatureError(e.to_string()))?;
400 let verifying_key = VerifyingKey::<Sha256>::new(pub_key);
401 let sig = RsaSignature::try_from(signature.signature.as_slice())
402 .map_err(|e| CryptographicError::SignatureError(e.to_string()))?;
403 verifying_key.verify(data, &sig).is_ok()
404 }
405 #[cfg(not(feature = "interop-crypto"))]
406 {
407 return Err(CryptographicError::UnsupportedAlgorithm(
408 "RSA requires interop-crypto feature".to_string(),
409 ));
410 }
411 }
412 KeyAlgorithm::X25519 | KeyAlgorithm::Kyber | KeyAlgorithm::NTRU => {
413 return Err(CryptographicError::UnsupportedAlgorithm(
414 "key agreement keys cannot sign or verify".into(),
415 ));
416 }
417 _ => {
418 let hash = self.compute_data_hash(data)?;
419 self.verify_hash_signature(&public_key, &signature.signature, &hash)?
420 }
421 };
422
423 let verification_record = VerificationRecord {
425 verification_id: format!(
426 "verif_{}",
427 std::time::SystemTime::now()
428 .duration_since(std::time::UNIX_EPOCH)
429 .unwrap()
430 .as_secs()
431 ),
432 signature_id: signature.signature_id.clone(),
433 verifier_id: "system".to_string(),
434 result: VerificationResult {
435 valid: is_valid,
436 error_message: None,
437 verification_time: start_time.elapsed().as_millis() as u64,
438 confidence: 1.0,
439 },
440 timestamp: start_time.elapsed().as_millis() as u64,
441 };
442
443 self.signature_storage
444 .store_verification_record(verification_record)?;
445
446 self.signature_storage.audit_log.log_entry(
448 &signature.signature_id,
449 SignatureOperation::Verify,
450 "system",
451 is_valid,
452 );
453
454 self.performance_optimizer
456 .record_verification_time(start_time.elapsed().as_millis() as f64);
457 if !is_valid {
458 self.performance_optimizer.record_error();
459 }
460
461 Ok(is_valid)
462 }
463
464 fn compute_data_hash(&self, data: &[u8]) -> Result<Vec<u8>, CryptographicError> {
465 use sha2::{Digest, Sha256};
467 let mut hasher = Sha256::new();
468 hasher.update(data);
469 Ok(hasher.finalize().to_vec())
470 }
471
472 fn sign_hash(&self, private_key: &Key, hash: &[u8]) -> Result<Vec<u8>, CryptographicError> {
473 use ed25519_dalek::{Signer, SigningKey};
474 if private_key.key_data.len() < 32 {
475 return Err(CryptographicError::InvalidKey(
476 "Private key too short for signing".to_string(),
477 ));
478 }
479 let mut seed = [0u8; 32];
480 seed.copy_from_slice(&private_key.key_data[..32]);
481 let signing_key = SigningKey::from_bytes(&seed);
482 let sig = signing_key.sign(hash);
483 Ok(sig.to_bytes().to_vec())
484 }
485
486 fn verify_hash_signature(
487 &self,
488 public_key: &Key,
489 signature: &[u8],
490 hash: &[u8],
491 ) -> Result<bool, CryptographicError> {
492 use ed25519_dalek::{Signature, Verifier, VerifyingKey};
493 if public_key.key_data.len() < 32 {
494 return Err(CryptographicError::InvalidKey(
495 "Public key too short for verification".to_string(),
496 ));
497 }
498 let mut key_bytes = [0u8; 32];
499 key_bytes.copy_from_slice(&public_key.key_data[..32]);
500 let verifying_key = VerifyingKey::from_bytes(&key_bytes)
501 .map_err(|e| CryptographicError::InvalidKey(e.to_string()))?;
502 if signature.len() != 64 {
503 return Ok(false);
504 }
505 let mut sig_bytes = [0u8; 64];
506 sig_bytes.copy_from_slice(signature);
507 let sig = Signature::from_bytes(&sig_bytes);
508 Ok(verifying_key.verify(hash, &sig).is_ok())
509 }
510}
511
512impl SignatureStorage {
513 pub fn new() -> Self {
515 Self {
516 signatures: HashMap::new(),
517 verification_records: HashMap::new(),
518 audit_log: SignatureAuditLog::new(),
519 }
520 }
521
522 pub fn initialize(&mut self) -> Result<(), CryptographicError> {
524 Ok(())
525 }
526
527 pub fn store_signature(&mut self, signature: Signature) -> Result<(), CryptographicError> {
529 self.signatures
530 .insert(signature.signature_id.clone(), signature);
531 Ok(())
532 }
533
534 pub fn store_verification_record(
536 &mut self,
537 record: VerificationRecord,
538 ) -> Result<(), CryptographicError> {
539 self.verification_records
540 .insert(record.verification_id.clone(), record);
541 Ok(())
542 }
543}
544
545impl SignatureAuditLog {
546 pub fn new() -> Self {
548 Self {
549 entries: Vec::new(),
550 retention_policy: RetentionPolicy {
551 retention_days: 365,
552 auto_delete: true,
553 archive_before_delete: true,
554 },
555 }
556 }
557
558 pub fn log_entry(
560 &mut self,
561 signature_id: &str,
562 operation: SignatureOperation,
563 user_id: &str,
564 success: bool,
565 ) {
566 let timestamp = std::time::SystemTime::now()
567 .duration_since(std::time::UNIX_EPOCH)
568 .unwrap_or_default()
569 .as_secs();
570 let entry = SignatureAuditEntry {
571 entry_id: format!("sig_{}_{}", timestamp, self.entries.len()),
572 timestamp,
573 signature_id: signature_id.to_string(),
574 operation,
575 user_id: user_id.to_string(),
576 ip_address: String::new(),
577 success,
578 };
579 self.entries.push(entry);
580 let cutoff =
581 timestamp.saturating_sub((self.retention_policy.retention_days as u64) * 86400);
582 self.entries.retain(|e| e.timestamp >= cutoff);
583 }
584
585 pub fn entry_count(&self) -> usize {
587 self.entries.len()
588 }
589
590 pub fn entries(&self) -> &[SignatureAuditEntry] {
592 &self.entries
593 }
594}
595
596impl SignaturePerformanceOptimizer {
597 pub fn new() -> Self {
599 Self {
600 optimization_strategies: vec![
601 SignatureOptimizationStrategy::BatchSigning,
602 SignatureOptimizationStrategy::Caching,
603 ],
604 performance_metrics: SignaturePerformanceMetrics {
605 average_signing_time: 0.0,
606 average_verification_time: 0.0,
607 throughput: 0.0,
608 error_rate: 0.0,
609 cache_hit_rate: 0.0,
610 },
611 }
612 }
613
614 pub fn initialize(&mut self) -> Result<(), CryptographicError> {
616 Ok(())
617 }
618
619 pub fn optimization_strategies(&self) -> &[SignatureOptimizationStrategy] {
621 &self.optimization_strategies
622 }
623
624 pub fn add_optimization_strategy(&mut self, strategy: SignatureOptimizationStrategy) {
626 if !self.optimization_strategies.contains(&strategy) {
627 self.optimization_strategies.push(strategy);
628 }
629 }
630
631 pub fn record_signing_time(&mut self, duration_ms: f64) {
633 let m = &mut self.performance_metrics;
634 if m.average_signing_time == 0.0 {
635 m.average_signing_time = duration_ms;
636 } else {
637 m.average_signing_time = 0.9 * m.average_signing_time + 0.1 * duration_ms;
639 }
640 if duration_ms > 0.0 {
641 m.throughput = 1000.0 / m.average_signing_time;
642 }
643 }
644
645 pub fn record_verification_time(&mut self, duration_ms: f64) {
647 let m = &mut self.performance_metrics;
648 if m.average_verification_time == 0.0 {
649 m.average_verification_time = duration_ms;
650 } else {
651 m.average_verification_time = 0.9 * m.average_verification_time + 0.1 * duration_ms;
652 }
653 }
654
655 pub fn record_error(&mut self) {
657 let m = &mut self.performance_metrics;
658 m.error_rate = 0.95 * m.error_rate + 0.05;
660 }
661
662 pub fn metrics(&self) -> &SignaturePerformanceMetrics {
664 &self.performance_metrics
665 }
666}
667
668impl SignaturePerformanceMetrics {
669 pub fn new() -> Self {
671 Self {
672 average_signing_time: 0.0,
673 average_verification_time: 0.0,
674 throughput: 0.0,
675 error_rate: 0.0,
676 cache_hit_rate: 0.0,
677 }
678 }
679}