tentacli_crypto/
rc4.rs

1use std::fmt::{Debug, Formatter};
2
3use hmacsha::HmacSha;
4use sha1::Sha1;
5
6const ENCRYPTION_KEY: [u8; 16] = [
7    0xC2, 0xB3, 0x72, 0x3C, 0xC6, 0xAE, 0xD9, 0xB5, 0x34, 0x3C, 0x53, 0xEE, 0x2F, 0x43, 0x67, 0xCE
8];
9
10const DECRYPTION_KEY: [u8; 16] = [
11    0xCC, 0x98, 0xAE, 0x04, 0xE8, 0x97, 0xEA, 0xCA, 0x12, 0xDD, 0xC0, 0x93, 0x42, 0x91, 0x53, 0x57
12];
13
14pub struct Encryptor {
15    instance: RC4,
16}
17
18impl Encryptor {
19    pub fn new(secret: &[u8]) -> Self {
20        let mut sync = vec![0u8; 1024];
21
22        let mut encryptor = RC4::new(
23            HmacSha::new(&ENCRYPTION_KEY, secret, Sha1::default()).compute_digest().to_vec()
24        );
25
26        encryptor.encrypt(&mut sync);
27
28        Self {
29            instance: encryptor,
30        }
31    }
32
33    pub fn encrypt(&mut self, data: &mut [u8]) {
34        self.instance.encrypt(data);
35    }
36}
37
38impl Debug for Encryptor {
39    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
40        write!(f, "Encryptor")
41    }
42}
43
44pub struct Decryptor {
45    instance: RC4,
46}
47
48impl Decryptor {
49    pub fn new(secret: &[u8]) -> Self {
50        let mut sync = vec![0; 1024];
51
52        let mut decryptor = RC4::new(
53            HmacSha::new(&DECRYPTION_KEY, secret, Sha1::default()).compute_digest().to_vec()
54        );
55
56        decryptor.encrypt(&mut sync);
57
58        Self {
59            instance: decryptor,
60        }
61    }
62
63    pub fn decrypt(&mut self, data: &mut [u8]) {
64        self.instance.encrypt(data);
65    }
66}
67
68impl Debug for Decryptor {
69    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
70        write!(f, "Decryptor")
71    }
72}
73
74#[derive(Debug)]
75pub struct RC4 {
76    i: u8,
77    j: u8,
78    pub state: [u8; 256],
79}
80
81impl RC4 {
82    pub fn new(key: Vec<u8>) -> Self {
83        assert!(!key.is_empty() && key.len() <= 256);
84
85        let mut state = [0u8; 256];
86        let mut j: u8 = 0;
87
88        for (i, x) in state.iter_mut().enumerate() {
89            *x = i as u8;
90        }
91        for i in 0..256 {
92            j = j.wrapping_add(state[i]).wrapping_add(key[i % key.len()]);
93            state.swap(i, j as usize);
94        }
95
96        Self {
97            i: 0,
98            j: 0,
99            state,
100        }
101    }
102
103    // prga
104    pub fn next(&mut self) -> u8 {
105        self.i = self.i.wrapping_add(1);
106        self.j = self.j.wrapping_add(self.state[self.i as usize]);
107        self.state.swap(self.i as usize, self.j as usize);
108        self.state[(self.state[self.i as usize].wrapping_add(self.state[self.j as usize])) as usize]
109    }
110
111    pub fn encrypt(&mut self, data: &mut [u8]) {
112        for x in data.iter_mut() {
113            *x ^= self.next();
114        }
115    }
116}