Skip to main content

nurtex_encrypt/
encrypt.rs

1use aes::Aes128;
2use aes::cipher::{BlockDecryptMut, BlockEncryptMut, KeyIvInit, inout::InOutBuf};
3use rand::{Rng, thread_rng};
4use sha1::{Digest, Sha1};
5
6pub type AesEncryptor = cfb8::Encryptor<Aes128>;
7pub type AesDecryptor = cfb8::Decryptor<Aes128>;
8
9fn generate_secret_key() -> [u8; 16] {
10  let mut key = [0u8; 16];
11  thread_rng().fill(&mut key);
12  key
13}
14
15pub fn digest_data(server_id: &[u8], public_key: &[u8], private_key: &[u8]) -> Vec<u8> {
16  let mut digest = Sha1::new();
17  digest.update(server_id);
18  digest.update(private_key);
19  digest.update(public_key);
20  digest.finalize().to_vec()
21}
22
23#[derive(Debug)]
24pub struct EncryptResult {
25  pub secret_key: [u8; 16],
26  pub encrypted_public_key: Vec<u8>,
27  pub encrypted_challenge: Vec<u8>,
28}
29
30pub fn encrypt(public_key: &[u8], challenge: &[u8]) -> Option<EncryptResult> {
31  let secret_key = generate_secret_key();
32
33  let encrypted_public_key = rsa_public_encrypt_pkcs1::encrypt(public_key, &secret_key).ok()?;
34  let encrypted_challenge = rsa_public_encrypt_pkcs1::encrypt(public_key, challenge).ok()?;
35
36  Some(EncryptResult {
37    secret_key,
38    encrypted_public_key,
39    encrypted_challenge,
40  })
41}
42
43pub fn create_cipher(key: &[u8]) -> (AesEncryptor, AesDecryptor) {
44  (AesEncryptor::new_from_slices(key, key).unwrap(), AesDecryptor::new_from_slices(key, key).unwrap())
45}
46
47pub fn encrypt_packet(cipher: &mut AesEncryptor, packet: &mut [u8]) {
48  let (chunks, _) = InOutBuf::from(packet).into_chunks();
49  cipher.encrypt_blocks_inout_mut(chunks);
50}
51
52pub fn decrypt_packet(cipher: &mut AesDecryptor, packet: &mut [u8]) {
53  let (chunks, _) = InOutBuf::from(packet).into_chunks();
54  cipher.decrypt_blocks_inout_mut(chunks);
55}