Skip to main content

rustf/utils/
crypto.rs

1//! Cryptographic utilities for RustF framework
2//!
3//! This module provides cryptographic functions commonly used in web development,
4//! including various hash functions, password utilities, and simple encryption/decryption operations.
5//!
6//! # Security Notice
7//! - MD5 and SHA1 are considered cryptographically broken for security purposes
8//! - Use SHA256 or higher for security-sensitive applications
9//! - These functions are provided for compatibility and non-security use cases
10
11use md5::Md5;
12use sha1::Sha1;
13use sha2::{Digest, Sha256, Sha512};
14use std::collections::hash_map::DefaultHasher;
15use std::hash::{Hash, Hasher};
16
17/// Generate a hash of the input string
18///
19/// Uses a fast hash function suitable for general purposes (not cryptographically secure).
20///
21/// # Arguments
22/// * `input` - String to hash
23///
24/// # Example
25/// ```rust,ignore
26/// let hash = hash_string("hello world");
27/// println!("Hash: {}", hash);
28/// ```
29pub fn hash_string(input: &str) -> u64 {
30    let mut hasher = DefaultHasher::new();
31    input.hash(&mut hasher);
32    hasher.finish()
33}
34
35/// Generate a hash of bytes
36///
37/// # Arguments
38/// * `input` - Bytes to hash
39///
40/// # Example
41/// ```rust,ignore
42/// let hash = hash_bytes(&[1, 2, 3, 4, 5]);
43/// println!("Hash: {}", hash);
44/// ```
45pub fn hash_bytes(input: &[u8]) -> u64 {
46    let mut hasher = DefaultHasher::new();
47    input.hash(&mut hasher);
48    hasher.finish()
49}
50
51/// Simple XOR encryption/decryption
52///
53/// WARNING: This is NOT cryptographically secure and should only be used
54/// for obfuscation or educational purposes. Use proper encryption libraries
55/// for sensitive data.
56///
57/// # Arguments
58/// * `data` - Data to encrypt/decrypt
59/// * `key` - Key for XOR operation
60///
61/// # Example
62/// ```rust,ignore
63/// let encrypted = xor_encrypt("hello", "key");
64/// let decrypted = xor_decrypt(&encrypted, "key");
65/// assert_eq!(decrypted, "hello");
66/// ```
67pub fn xor_encrypt(data: &str, key: &str) -> Vec<u8> {
68    xor_bytes(data.as_bytes(), key.as_bytes())
69}
70
71/// Simple XOR decryption to string
72///
73/// # Arguments
74/// * `data` - Encrypted bytes
75/// * `key` - Key for XOR operation
76///
77/// # Example
78/// ```rust,ignore
79/// let encrypted = xor_encrypt("hello", "key");
80/// let decrypted = xor_decrypt(&encrypted, "key");
81/// assert_eq!(decrypted, "hello");
82/// ```
83pub fn xor_decrypt(data: &[u8], key: &str) -> String {
84    let decrypted_bytes = xor_bytes(data, key.as_bytes());
85    String::from_utf8_lossy(&decrypted_bytes).to_string()
86}
87
88/// XOR operation on bytes
89///
90/// # Arguments
91/// * `data` - Data bytes
92/// * `key` - Key bytes
93fn xor_bytes(data: &[u8], key: &[u8]) -> Vec<u8> {
94    if key.is_empty() {
95        return data.to_vec();
96    }
97
98    data.iter()
99        .enumerate()
100        .map(|(i, &byte)| byte ^ key[i % key.len()])
101        .collect()
102}
103
104/// Generate a simple checksum for data integrity
105///
106/// This is a simple checksum, not suitable for security purposes.
107/// Use for data integrity checks in non-security contexts.
108///
109/// # Arguments
110/// * `data` - Data to checksum
111///
112/// # Example
113/// ```rust,ignore
114/// let checksum = simple_checksum("important data");
115/// println!("Checksum: {}", checksum);
116/// ```
117pub fn simple_checksum(data: &str) -> u32 {
118    data.bytes().map(|b| b as u32).sum()
119}
120
121/// Constant-time string comparison
122///
123/// Compares two strings in constant time to prevent timing attacks.
124/// Always use this for comparing sensitive data like passwords or tokens.
125///
126/// # Arguments
127/// * `a` - First string
128/// * `b` - Second string
129///
130/// # Example
131/// ```rust,ignore
132/// let is_equal = constant_time_compare("secret", "secret");
133/// assert!(is_equal);
134/// ```
135pub fn constant_time_compare(a: &str, b: &str) -> bool {
136    constant_time_compare_bytes(a.as_bytes(), b.as_bytes())
137}
138
139/// Constant-time byte comparison
140///
141/// # Arguments
142/// * `a` - First byte slice
143/// * `b` - Second byte slice
144pub fn constant_time_compare_bytes(a: &[u8], b: &[u8]) -> bool {
145    if a.len() != b.len() {
146        return false;
147    }
148
149    let mut result = 0u8;
150    for (x, y) in a.iter().zip(b.iter()) {
151        result |= x ^ y;
152    }
153
154    result == 0
155}
156
157/// Generate a simple obfuscated string
158///
159/// This is basic obfuscation, not encryption. Don't use for sensitive data.
160///
161/// # Arguments
162/// * `input` - String to obfuscate
163/// * `offset` - Character offset for obfuscation
164///
165/// # Example
166/// ```rust,ignore
167/// let obfuscated = obfuscate_string("hello", 3);
168/// let deobfuscated = deobfuscate_string(&obfuscated, 3);
169/// assert_eq!(deobfuscated, "hello");
170/// ```
171pub fn obfuscate_string(input: &str, offset: u8) -> String {
172    input
173        .chars()
174        .map(|c| {
175            if c.is_ascii_alphabetic() {
176                let base = if c.is_ascii_lowercase() { b'a' } else { b'A' };
177                let shifted = ((c as u8 - base + offset) % 26) + base;
178                shifted as char
179            } else {
180                c
181            }
182        })
183        .collect()
184}
185
186/// Deobfuscate a string
187///
188/// # Arguments
189/// * `input` - Obfuscated string
190/// * `offset` - Character offset used for obfuscation
191pub fn deobfuscate_string(input: &str, offset: u8) -> String {
192    input
193        .chars()
194        .map(|c| {
195            if c.is_ascii_alphabetic() {
196                let base = if c.is_ascii_lowercase() { b'a' } else { b'A' };
197                let shifted = ((c as u8 - base + 26 - (offset % 26)) % 26) + base;
198                shifted as char
199            } else {
200                c
201            }
202        })
203        .collect()
204}
205
206// Cryptographic Hash Functions
207
208/// Generate MD5 hash of input string
209///
210/// **Security Warning**: MD5 is cryptographically broken and should not be used
211/// for security purposes. Use SHA256 or higher for security applications.
212///
213/// # Arguments
214/// * `input` - String to hash
215///
216/// # Example
217/// ```rust,ignore
218/// let hash = md5("hello world");
219/// assert_eq!(hash, "5eb63bbbe01eeed093cb22bb8f5acdc3");
220/// ```
221pub fn md5(input: &str) -> String {
222    md5_bytes(input.as_bytes())
223}
224
225/// Generate MD5 hash of byte slice
226///
227/// **Security Warning**: MD5 is cryptographically broken and should not be used
228/// for security purposes.
229///
230/// # Arguments
231/// * `input` - Bytes to hash
232///
233/// # Example
234/// ```rust,ignore
235/// let hash = md5_bytes(b"hello world");
236/// assert_eq!(hash, "5eb63bbbe01eeed093cb22bb8f5acdc3");
237/// ```
238pub fn md5_bytes(input: &[u8]) -> String {
239    let mut hasher = Md5::new();
240    hasher.update(input);
241    format!("{:x}", hasher.finalize())
242}
243
244/// Generate SHA1 hash of input string
245///
246/// **Security Warning**: SHA1 is cryptographically broken and should not be used
247/// for security purposes. Use SHA256 or higher for security applications.
248///
249/// # Arguments
250/// * `input` - String to hash
251///
252/// # Example
253/// ```rust,ignore
254/// let hash = sha1("hello world");
255/// assert_eq!(hash, "2aae6c35c94fcfb415dbe95f408b9ce91ee846ed");
256/// ```
257pub fn sha1(input: &str) -> String {
258    sha1_bytes(input.as_bytes())
259}
260
261/// Generate SHA1 hash of byte slice
262///
263/// **Security Warning**: SHA1 is cryptographically broken and should not be used
264/// for security purposes.
265///
266/// # Arguments
267/// * `input` - Bytes to hash
268///
269/// # Example
270/// ```rust,ignore
271/// let hash = sha1_bytes(b"hello world");
272/// assert_eq!(hash, "2aae6c35c94fcfb415dbe95f408b9ce91ee846ed");
273/// ```
274pub fn sha1_bytes(input: &[u8]) -> String {
275    let mut hasher = Sha1::new();
276    hasher.update(input);
277    format!("{:x}", hasher.finalize())
278}
279
280/// Generate SHA256 hash of input string
281///
282/// This is a secure hash function suitable for security applications.
283///
284/// # Arguments
285/// * `input` - String to hash
286///
287/// # Example
288/// ```rust,ignore
289/// let hash = sha256("hello world");
290/// assert_eq!(hash, "b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9");
291/// ```
292pub fn sha256(input: &str) -> String {
293    sha256_bytes(input.as_bytes())
294}
295
296/// Generate SHA256 hash of byte slice
297///
298/// This is a secure hash function suitable for security applications.
299///
300/// # Arguments
301/// * `input` - Bytes to hash
302///
303/// # Example
304/// ```rust,ignore
305/// let hash = sha256_bytes(b"hello world");
306/// assert_eq!(hash, "b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9");
307/// ```
308pub fn sha256_bytes(input: &[u8]) -> String {
309    let mut hasher = Sha256::new();
310    hasher.update(input);
311    format!("{:x}", hasher.finalize())
312}
313
314/// Generate SHA512 hash of input string
315///
316/// This is a secure hash function suitable for security applications.
317///
318/// # Arguments
319/// * `input` - String to hash
320///
321/// # Example
322/// ```rust,ignore
323/// let hash = sha512("hello world");
324/// println!("SHA512: {}", hash);
325/// ```
326pub fn sha512(input: &str) -> String {
327    sha512_bytes(input.as_bytes())
328}
329
330/// Generate SHA512 hash of byte slice
331///
332/// This is a secure hash function suitable for security applications.
333///
334/// # Arguments
335/// * `input` - Bytes to hash
336///
337/// # Example
338/// ```rust,ignore
339/// let hash = sha512_bytes(b"hello world");
340/// println!("SHA512: {}", hash);
341/// ```
342pub fn sha512_bytes(input: &[u8]) -> String {
343    let mut hasher = Sha512::new();
344    hasher.update(input);
345    format!("{:x}", hasher.finalize())
346}
347
348#[cfg(test)]
349mod tests {
350    use super::*;
351
352    #[test]
353    fn test_hash_string() {
354        let hash1 = hash_string("hello");
355        let hash2 = hash_string("hello");
356        let hash3 = hash_string("world");
357
358        // Same input should produce same hash
359        assert_eq!(hash1, hash2);
360
361        // Different input should produce different hash (with high probability)
362        assert_ne!(hash1, hash3);
363    }
364
365    #[test]
366    fn test_hash_bytes() {
367        let hash1 = hash_bytes(&[1, 2, 3]);
368        let hash2 = hash_bytes(&[1, 2, 3]);
369        let hash3 = hash_bytes(&[3, 2, 1]);
370
371        assert_eq!(hash1, hash2);
372        assert_ne!(hash1, hash3);
373    }
374
375    #[test]
376    fn test_xor_encryption() {
377        let original = "Hello, World!";
378        let key = "secret";
379
380        let encrypted = xor_encrypt(original, key);
381        let decrypted = xor_decrypt(&encrypted, key);
382
383        assert_eq!(decrypted, original);
384
385        // Encrypted data should be different from original
386        assert_ne!(encrypted, original.as_bytes());
387    }
388
389    #[test]
390    fn test_simple_checksum() {
391        let checksum1 = simple_checksum("hello");
392        let checksum2 = simple_checksum("hello");
393        let checksum3 = simple_checksum("world");
394
395        assert_eq!(checksum1, checksum2);
396        assert_ne!(checksum1, checksum3);
397    }
398
399    #[test]
400    fn test_constant_time_compare() {
401        assert!(constant_time_compare("hello", "hello"));
402        assert!(!constant_time_compare("hello", "world"));
403        assert!(!constant_time_compare("hello", "hello!"));
404        assert!(!constant_time_compare("hello!", "hello"));
405    }
406
407    #[test]
408    fn test_constant_time_compare_bytes() {
409        assert!(constant_time_compare_bytes(b"hello", b"hello"));
410        assert!(!constant_time_compare_bytes(b"hello", b"world"));
411        assert!(!constant_time_compare_bytes(b"hello", b"hello!"));
412    }
413
414    #[test]
415    fn test_obfuscation() {
416        let original = "Hello World";
417        let offset = 5;
418
419        let obfuscated = obfuscate_string(original, offset);
420        let deobfuscated = deobfuscate_string(&obfuscated, offset);
421
422        assert_eq!(deobfuscated, original);
423        assert_ne!(obfuscated, original);
424
425        // Test with numbers and special characters (should remain unchanged)
426        let mixed = "Hello123!";
427        let obf_mixed = obfuscate_string(mixed, 3);
428        let deobf_mixed = deobfuscate_string(&obf_mixed, 3);
429        assert_eq!(deobf_mixed, mixed);
430    }
431
432    // Tests for cryptographic hash functions
433
434    #[test]
435    fn test_md5() {
436        // Test with known test vectors
437        assert_eq!(md5(""), "d41d8cd98f00b204e9800998ecf8427e");
438        assert_eq!(md5("a"), "0cc175b9c0f1b6a831c399e269772661");
439        assert_eq!(md5("abc"), "900150983cd24fb0d6963f7d28e17f72");
440        assert_eq!(md5("hello world"), "5eb63bbbe01eeed093cb22bb8f5acdc3");
441        assert_eq!(
442            md5("The quick brown fox jumps over the lazy dog"),
443            "9e107d9d372bb6826bd81d3542a419d6"
444        );
445
446        // Test consistency
447        let hash1 = md5("test");
448        let hash2 = md5("test");
449        assert_eq!(hash1, hash2);
450    }
451
452    #[test]
453    fn test_md5_bytes() {
454        // Test with known test vectors
455        assert_eq!(md5_bytes(b""), "d41d8cd98f00b204e9800998ecf8427e");
456        assert_eq!(md5_bytes(b"abc"), "900150983cd24fb0d6963f7d28e17f72");
457        assert_eq!(
458            md5_bytes(b"hello world"),
459            "5eb63bbbe01eeed093cb22bb8f5acdc3"
460        );
461
462        // Test that string and bytes variants produce same result
463        assert_eq!(md5("test"), md5_bytes(b"test"));
464    }
465
466    #[test]
467    fn test_sha1() {
468        // Test with known test vectors
469        assert_eq!(sha1(""), "da39a3ee5e6b4b0d3255bfef95601890afd80709");
470        assert_eq!(sha1("abc"), "a9993e364706816aba3e25717850c26c9cd0d89d");
471        assert_eq!(
472            sha1("hello world"),
473            "2aae6c35c94fcfb415dbe95f408b9ce91ee846ed"
474        );
475        assert_eq!(
476            sha1("The quick brown fox jumps over the lazy dog"),
477            "2fd4e1c67a2d28fced849ee1bb76e7391b93eb12"
478        );
479
480        // Test consistency
481        let hash1 = sha1("test");
482        let hash2 = sha1("test");
483        assert_eq!(hash1, hash2);
484    }
485
486    #[test]
487    fn test_sha1_bytes() {
488        // Test with known test vectors
489        assert_eq!(sha1_bytes(b""), "da39a3ee5e6b4b0d3255bfef95601890afd80709");
490        assert_eq!(
491            sha1_bytes(b"abc"),
492            "a9993e364706816aba3e25717850c26c9cd0d89d"
493        );
494        assert_eq!(
495            sha1_bytes(b"hello world"),
496            "2aae6c35c94fcfb415dbe95f408b9ce91ee846ed"
497        );
498
499        // Test that string and bytes variants produce same result
500        assert_eq!(sha1("test"), sha1_bytes(b"test"));
501    }
502
503    #[test]
504    fn test_sha256() {
505        // Test with known test vectors
506        assert_eq!(
507            sha256(""),
508            "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
509        );
510        assert_eq!(
511            sha256("abc"),
512            "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
513        );
514        assert_eq!(
515            sha256("hello world"),
516            "b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9"
517        );
518        assert_eq!(
519            sha256("The quick brown fox jumps over the lazy dog"),
520            "d7a8fbb307d7809469ca9abcb0082e4f8d5651e46d3cdb762d02d0bf37c9e592"
521        );
522
523        // Test consistency
524        let hash1 = sha256("test");
525        let hash2 = sha256("test");
526        assert_eq!(hash1, hash2);
527    }
528
529    #[test]
530    fn test_sha256_bytes() {
531        // Test with known test vectors
532        assert_eq!(
533            sha256_bytes(b""),
534            "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
535        );
536        assert_eq!(
537            sha256_bytes(b"abc"),
538            "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
539        );
540        assert_eq!(
541            sha256_bytes(b"hello world"),
542            "b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9"
543        );
544
545        // Test that string and bytes variants produce same result
546        assert_eq!(sha256("test"), sha256_bytes(b"test"));
547    }
548
549    #[test]
550    fn test_sha512() {
551        // Test with known test vectors
552        assert_eq!(sha512(""), "cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e");
553        assert_eq!(sha512("abc"), "ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a2192992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f");
554        assert_eq!(sha512("hello world"), "309ecc489c12d6eb4cc40f50c902f2b4d0ed77ee511a7c7a9bcd3ca86d4cd86f989dd35bc5ff499670da34255b45b0cfd830e81f605dcf7dc5542e93ae9cd76f");
555
556        // Test consistency
557        let hash1 = sha512("test");
558        let hash2 = sha512("test");
559        assert_eq!(hash1, hash2);
560    }
561
562    #[test]
563    fn test_sha512_bytes() {
564        // Test with known test vectors
565        assert_eq!(sha512_bytes(b""), "cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e");
566        assert_eq!(sha512_bytes(b"abc"), "ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a2192992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f");
567
568        // Test that string and bytes variants produce same result
569        assert_eq!(sha512("test"), sha512_bytes(b"test"));
570    }
571
572    #[test]
573    fn test_hash_uniqueness() {
574        // Test that different inputs produce different hashes
575        let input1 = "hello";
576        let input2 = "world";
577
578        assert_ne!(md5(input1), md5(input2));
579        assert_ne!(sha1(input1), sha1(input2));
580        assert_ne!(sha256(input1), sha256(input2));
581        assert_ne!(sha512(input1), sha512(input2));
582    }
583
584    #[test]
585    fn test_hash_lengths() {
586        let input = "test";
587
588        // MD5 produces 32 character hex string (128 bits)
589        assert_eq!(md5(input).len(), 32);
590
591        // SHA1 produces 40 character hex string (160 bits)
592        assert_eq!(sha1(input).len(), 40);
593
594        // SHA256 produces 64 character hex string (256 bits)
595        assert_eq!(sha256(input).len(), 64);
596
597        // SHA512 produces 128 character hex string (512 bits)
598        assert_eq!(sha512(input).len(), 128);
599    }
600
601    #[test]
602    fn test_empty_input_handling() {
603        // All hash functions should handle empty input gracefully
604        assert!(!md5("").is_empty());
605        assert!(!sha1("").is_empty());
606        assert!(!sha256("").is_empty());
607        assert!(!sha512("").is_empty());
608    }
609}