From 38543feae7a9e7d6380eb28af6fb5ed780b078c3 Mon Sep 17 00:00:00 2001 From: iceiix <43691553+iceiix@users.noreply.github.com> Date: Thu, 1 Nov 2018 20:45:40 -0700 Subject: [PATCH] Switch to RustCrypto for Cfb8 symmetric crypto, instead of OpenSSL (#10) (#2) * Encrypt with both RustCrypto cfb8 and OpenSSL * Switch to RustCrypto for decrypting * Show encryption for both RustCrypto and OpenSSL, for comparison... * Correct off-by-one error in encryption, cfb8 doesn't need extra byte * Remove OpenSSL for symmetric crypto * Update Cargo.lock --- protocol/src/protocol/mod.rs | 37 ++++++++++++++++++------------------ 1 file changed, 19 insertions(+), 18 deletions(-) diff --git a/protocol/src/protocol/mod.rs b/protocol/src/protocol/mod.rs index 9785873..dddab91 100644 --- a/protocol/src/protocol/mod.rs +++ b/protocol/src/protocol/mod.rs @@ -14,7 +14,9 @@ #![allow(dead_code)] -use openssl::symm; +use aes::Aes128; +use cfb8::Cfb8; +use cfb8::stream_cipher::{NewStreamCipher, StreamCipher}; use serde_json; use reqwest; use openssl; @@ -745,6 +747,8 @@ impl ::std::fmt::Display for Error { } } +type Aes128Cfb = Cfb8; + pub struct Conn { stream: TcpStream, pub host: String, @@ -752,16 +756,13 @@ pub struct Conn { direction: Direction, pub state: State, - cipher: Option, + cipher: Option, compression_threshold: i32, compression_read: Option>>>, compression_write: Option>>>, } -// Needed because symm::Crypter isn't send -unsafe impl Send for Conn {} - impl Conn { pub fn new(target: &str) -> Result { // TODO SRV record support @@ -866,11 +867,8 @@ impl Conn { } } - pub fn enable_encyption(&mut self, key: &[u8], decrypt: bool) { - let cipher = symm::Crypter::new(symm::Cipher::aes_128_cfb8(), - if decrypt { symm::Mode::Decrypt } else { symm::Mode::Encrypt }, - key, - Some(key)).unwrap(); + pub fn enable_encyption(&mut self, key: &[u8], _decrypt: bool) { + let cipher = Aes128Cfb::new_var(key, key).unwrap(); self.cipher = Option::Some(cipher); } @@ -979,11 +977,8 @@ impl Read for Conn { Option::None => self.stream.read(buf), Option::Some(cipher) => { let ret = try!(self.stream.read(buf)); - let mut data = vec![0; ret + symm::Cipher::aes_128_cfb8().block_size()]; - let count = cipher.update(&buf[..ret], &mut data).unwrap(); - for i in 0..count { - buf[i] = data[i]; - } + cipher.decrypt(&mut buf[..ret]); + Ok(ret) } } @@ -995,9 +990,15 @@ impl Write for Conn { match self.cipher.as_mut() { Option::None => self.stream.write(buf), Option::Some(cipher) => { - let mut data = vec![0; buf.len() + symm::Cipher::aes_128_cfb8().block_size()]; - let count = cipher.update(buf, &mut data).unwrap(); - try!(self.stream.write_all(&data[..count])); + // TODO: avoid copying, but trait requires non-mutable buf + let mut data = vec![0; buf.len()]; + for i in 0..buf.len() { + data[i] = buf[i]; + } + + cipher.encrypt(&mut data); + + try!(self.stream.write_all(&data)); Ok(buf.len()) } }