qualia_core_db/specialized_libs/cryptographic_library/
hashing.rs1use super::*;
4
5pub struct HashEngine {
7 hash_algorithms: HashMap<String, HashAlgorithmImpl>,
8 pub(super) hash_storage: HashStorage,
9 pub(super) performance_optimizer: HashPerformanceOptimizer,
10}
11
12#[derive(Debug, Clone)]
14pub struct HashAlgorithmImpl {
15 pub algorithm_id: String,
16 pub algorithm: String,
17 pub output_size: usize,
18 pub block_size: usize,
19 pub parameters: HashParameters,
20}
21
22#[derive(Debug, Clone)]
24pub struct HashParameters {
25 pub rounds: u32,
26 pub personalization: Option<Vec<u8>>,
27 pub salt: Option<Vec<u8>>,
28 pub custom_params: HashMap<String, Vec<u8>>,
29}
30
31pub struct HashStorage {
33 hashes: HashMap<String, HashResult>,
34 verification_records: HashMap<String, HashVerificationRecord>,
35 pub(super) audit_log: HashAuditLog,
36}
37
38#[derive(Debug, Clone)]
40pub struct HashRecord {
41 pub hash_id: String,
42 pub algorithm: String,
43 pub input_data: Vec<u8>,
44 pub hash_value: Vec<u8>,
45 pub timestamp: u64,
46 pub metadata: HashMetadata,
47}
48
49#[derive(Debug, Clone)]
51pub struct HashMetadata {
52 pub creator_id: String,
53 pub purpose: String,
54 pub context: Vec<String>,
55 pub data_size: usize,
56}
57
58#[derive(Debug, Clone)]
60pub struct HashVerificationRecord {
61 pub verification_id: String,
62 pub hash_id: String,
63 pub verifier_id: String,
64 pub result: HashVerificationResult,
65 pub timestamp: u64,
66}
67
68#[derive(Debug, Clone)]
70pub struct HashVerificationResult {
71 pub valid: bool,
72 pub error_message: Option<String>,
73 pub verification_time: u64,
74}
75
76pub struct HashAuditLog {
78 entries: Vec<HashAuditEntry>,
79 retention_policy: RetentionPolicy,
80}
81
82#[derive(Debug, Clone)]
84pub struct HashAuditEntry {
85 pub entry_id: String,
86 pub timestamp: u64,
87 pub hash_id: String,
88 pub operation: HashOperation,
89 pub user_id: String,
90 pub ip_address: String,
91 pub success: bool,
92}
93
94#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
96pub enum HashOperation {
97 Compute,
98 Verify,
99 Update,
100 Delete,
101}
102
103pub struct HashPerformanceOptimizer {
105 optimization_strategies: Vec<HashOptimizationStrategy>,
106 performance_metrics: HashPerformanceMetrics,
107}
108
109#[derive(Debug, Clone, PartialEq)]
111pub enum HashOptimizationStrategy {
112 BatchHashing,
113 ParallelProcessing,
114 HardwareAcceleration,
115 Caching,
116 MemoryOptimization,
117}
118
119#[derive(Debug, Clone)]
121pub struct HashPerformanceMetrics {
122 pub average_hash_time: f64,
123 pub throughput: f64,
124 pub memory_usage: u64,
125 pub cache_hit_rate: f64,
126}
127impl HashEngine {
128 pub fn new() -> Self {
130 Self {
131 hash_algorithms: HashMap::new(),
132 hash_storage: HashStorage::new(),
133 performance_optimizer: HashPerformanceOptimizer::new(),
134 }
135 }
136
137 pub fn initialize(&mut self) -> Result<(), CryptographicError> {
139 self.hash_storage.initialize()?;
140 self.performance_optimizer.initialize()?;
141 Ok(())
142 }
143
144 pub fn add_hash_algorithm(&mut self, name: String, implementation: HashAlgorithmImpl) {
146 self.hash_algorithms.insert(name, implementation);
147 }
148
149 pub fn get_hash_algorithm(&self, name: &str) -> Option<&HashAlgorithmImpl> {
151 self.hash_algorithms.get(name)
152 }
153
154 pub fn list_hash_algorithms(&self) -> impl Iterator<Item = &HashAlgorithmImpl> {
156 self.hash_algorithms.values()
157 }
158
159 pub fn compute_hash(
161 &mut self,
162 algorithm: &str,
163 data: &[u8],
164 ) -> Result<HashResult, CryptographicError> {
165 let start_time = std::time::Instant::now();
166
167 let hash_value = match algorithm {
169 "SHA256" => {
170 use sha2::{Digest, Sha256};
171 let mut hasher = Sha256::new();
172 hasher.update(data);
173 hasher.finalize().to_vec()
174 }
175 "SHA512" => {
176 use sha2::{Digest, Sha512};
177 let mut hasher = Sha512::new();
178 hasher.update(data);
179 hasher.finalize().to_vec()
180 }
181 "BLAKE3" => blake3::hash(data).as_bytes().to_vec(),
182 _ => {
183 return Err(CryptographicError::UnsupportedAlgorithm(
184 "Hash algorithm not supported".to_string(),
185 ))
186 }
187 };
188
189 let hash_result = HashResult {
190 hash_id: format!(
191 "hash_{}",
192 std::time::SystemTime::now()
193 .duration_since(std::time::UNIX_EPOCH)
194 .unwrap()
195 .as_secs()
196 ),
197 algorithm: algorithm.to_string(),
198 input_data: data.to_vec(),
199 hash_value,
200 timestamp: start_time.elapsed().as_millis() as u64,
201 };
202
203 self.hash_storage.store_hash(hash_result.clone())?;
205
206 self.hash_storage.audit_log.log_entry(
208 &hash_result.hash_id,
209 HashOperation::Compute,
210 "system",
211 true,
212 );
213
214 self.performance_optimizer
216 .record_hash_time(start_time.elapsed().as_millis() as f64);
217
218 Ok(hash_result)
219 }
220}
221
222impl HashStorage {
223 pub fn new() -> Self {
225 Self {
226 hashes: HashMap::new(),
227 verification_records: HashMap::new(),
228 audit_log: HashAuditLog::new(),
229 }
230 }
231
232 pub fn initialize(&mut self) -> Result<(), CryptographicError> {
234 Ok(())
235 }
236
237 pub fn store_hash(&mut self, hash: HashResult) -> Result<(), CryptographicError> {
239 self.hashes.insert(hash.hash_id.clone(), hash);
240 Ok(())
241 }
242
243 pub fn store_verification_record(
245 &mut self,
246 record: HashVerificationRecord,
247 ) -> Result<(), CryptographicError> {
248 self.verification_records
249 .insert(record.verification_id.clone(), record);
250 Ok(())
251 }
252
253 pub fn get_verification_record(&self, id: &str) -> Option<&HashVerificationRecord> {
255 self.verification_records.get(id)
256 }
257
258 pub fn list_verification_records(&self) -> impl Iterator<Item = &HashVerificationRecord> {
260 self.verification_records.values()
261 }
262}
263
264impl HashAuditLog {
265 pub fn new() -> Self {
267 Self {
268 entries: Vec::new(),
269 retention_policy: RetentionPolicy {
270 retention_days: 365,
271 auto_delete: true,
272 archive_before_delete: true,
273 },
274 }
275 }
276
277 pub fn log_entry(
279 &mut self,
280 hash_id: &str,
281 operation: HashOperation,
282 user_id: &str,
283 success: bool,
284 ) {
285 let timestamp = std::time::SystemTime::now()
286 .duration_since(std::time::UNIX_EPOCH)
287 .unwrap_or_default()
288 .as_secs();
289 let entry = HashAuditEntry {
290 entry_id: format!("hash_{}_{}", timestamp, self.entries.len()),
291 timestamp,
292 hash_id: hash_id.to_string(),
293 operation,
294 user_id: user_id.to_string(),
295 ip_address: String::new(),
296 success,
297 };
298 self.entries.push(entry);
299 let cutoff =
300 timestamp.saturating_sub((self.retention_policy.retention_days as u64) * 86400);
301 self.entries.retain(|e| e.timestamp >= cutoff);
302 }
303
304 pub fn entry_count(&self) -> usize {
306 self.entries.len()
307 }
308
309 pub fn entries(&self) -> &[HashAuditEntry] {
311 &self.entries
312 }
313}
314
315impl HashPerformanceOptimizer {
316 pub fn new() -> Self {
318 Self {
319 optimization_strategies: vec![
320 HashOptimizationStrategy::BatchHashing,
321 HashOptimizationStrategy::ParallelProcessing,
322 ],
323 performance_metrics: HashPerformanceMetrics {
324 average_hash_time: 0.0,
325 throughput: 0.0,
326 memory_usage: 0,
327 cache_hit_rate: 0.0,
328 },
329 }
330 }
331
332 pub fn initialize(&mut self) -> Result<(), CryptographicError> {
334 Ok(())
335 }
336
337 pub fn optimization_strategies(&self) -> &[HashOptimizationStrategy] {
339 &self.optimization_strategies
340 }
341
342 pub fn add_optimization_strategy(&mut self, strategy: HashOptimizationStrategy) {
344 if !self.optimization_strategies.contains(&strategy) {
345 self.optimization_strategies.push(strategy);
346 }
347 }
348
349 pub fn record_hash_time(&mut self, duration_ms: f64) {
351 let m = &mut self.performance_metrics;
352 if m.average_hash_time == 0.0 {
353 m.average_hash_time = duration_ms;
354 } else {
355 m.average_hash_time = 0.9 * m.average_hash_time + 0.1 * duration_ms;
356 }
357 if m.average_hash_time > 0.0 {
358 m.throughput = 1000.0 / m.average_hash_time;
359 }
360 }
361
362 pub fn metrics(&self) -> &HashPerformanceMetrics {
364 &self.performance_metrics
365 }
366}
367
368impl HashPerformanceMetrics {
369 pub fn new() -> Self {
371 Self {
372 average_hash_time: 0.0,
373 throughput: 0.0,
374 memory_usage: 0,
375 cache_hit_rate: 0.0,
376 }
377 }
378}