myph-v2~ rust shellcode loader with evasive capabilities |
| git clone https://github.com/djnnvx/myph-v2.git |
| log | files | refs | archive | README |
xor_cipher.rs (2965B)
1 use super::Encryptor; 2 3 /// XOR cipher implementation 4 pub struct XorEncryptor { 5 key: Vec<u8>, 6 } 7 8 impl XorEncryptor { 9 /// Creates a new XOR encryptor with the given key 10 pub fn new(key: &str) -> Self { 11 Self { 12 key: key.as_bytes().to_vec(), 13 } 14 } 15 } 16 17 impl Encryptor for XorEncryptor { 18 fn encrypt(&self, data: &[u8]) -> Result<Vec<u8>, String> { 19 if self.key.is_empty() { 20 return Err("Key cannot be empty".to_string()); 21 } 22 23 Ok(data 24 .iter() 25 .enumerate() 26 .map(|(i, &byte)| byte ^ self.key[i % self.key.len()]) 27 .collect()) 28 } 29 30 fn decrypt(&self, data: &[u8]) -> Result<Vec<u8>, String> { 31 // XOR encryption is symmetric 32 self.encrypt(data) 33 } 34 35 fn key_size(&self) -> usize { 36 self.key.len() 37 } 38 39 fn algorithm_name(&self) -> &'static str { 40 "XOR" 41 } 42 43 fn uses_iv(&self) -> bool { 44 false // XOR doesn't use IV 45 } 46 47 fn generate_decrypt_code(&self) -> &'static str { 48 r#"/// Decrypts XOR encrypted data using the provided key 49 /// 50 /// Returns decrypted bytes. 51 pub fn decrypt_xor(data: &[u8], key: &[u8]) -> Vec<u8> { 52 xor_bytes(data, key) 53 }"# 54 } 55 } 56 57 #[cfg(test)] 58 mod tests { 59 use super::*; 60 61 #[test] 62 fn test_xor_encrypt_decrypt() { 63 let encryptor = XorEncryptor::new("secret-key"); 64 let plaintext = b"Hello, World!"; 65 66 let encrypted = encryptor.encrypt(plaintext).unwrap(); 67 assert_ne!(encrypted, plaintext); 68 69 let decrypted = encryptor.decrypt(&encrypted).unwrap(); 70 assert_eq!(decrypted, plaintext); 71 } 72 73 #[test] 74 fn test_xor_different_keys() { 75 let encryptor1 = XorEncryptor::new("key1"); 76 let encryptor2 = XorEncryptor::new("key2"); 77 let plaintext = b"Test data"; 78 79 let encrypted1 = encryptor1.encrypt(plaintext).unwrap(); 80 let encrypted2 = encryptor2.encrypt(plaintext).unwrap(); 81 82 assert_ne!(encrypted1, encrypted2); 83 } 84 85 #[test] 86 fn test_xor_empty_data() { 87 let encryptor = XorEncryptor::new("key"); 88 let empty: &[u8] = &[]; 89 90 let encrypted = encryptor.encrypt(empty).unwrap(); 91 assert_eq!(encrypted.len(), 0); 92 93 let decrypted = encryptor.decrypt(&encrypted).unwrap(); 94 assert_eq!(decrypted.len(), 0); 95 } 96 97 #[test] 98 fn test_xor_empty_key() { 99 let encryptor = XorEncryptor::new(""); 100 let data = b"test"; 101 102 let result = encryptor.encrypt(data); 103 assert!(result.is_err()); 104 } 105 106 #[test] 107 fn test_xor_long_data() { 108 let encryptor = XorEncryptor::new("short"); 109 let plaintext = b"This is a much longer message that exceeds the key length"; 110 111 let encrypted = encryptor.encrypt(plaintext).unwrap(); 112 assert_ne!(encrypted, plaintext); 113 114 let decrypted = encryptor.decrypt(&encrypted).unwrap(); 115 assert_eq!(decrypted, plaintext); 116 } 117 }