Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Remove rust_sodium and replace encryptions with AES #255

Merged
merged 2 commits into from Dec 2, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
3 changes: 2 additions & 1 deletion Cargo.toml
Expand Up @@ -11,13 +11,14 @@ repository = "https://github.com/maidsafe/self_encryption"
version = "0.15.0"

[dependencies]
aes = "0.3.2"
block-modes = "0.3.3"
bincode = "~1.1.4"
brotli = "~3.3.0"
futures = "~0.1.28"
memmap = "~0.7.0"
rand = "~0.6.0"
rand_chacha = "~0.1.1"
rust_sodium = "~0.10.2"
serde = { version = "~1.0.97", features = ["derive"] }
tiny-keccak = "~1.5.0"
unwrap = "~1.2.1"
Expand Down
42 changes: 29 additions & 13 deletions src/encryption.rs
@@ -1,25 +1,41 @@
// Copyright 2018 MaidSafe.net limited.
// Copyright 2019 MaidSafe.net limited.
//
// This SAFE Network Software is licensed to you under The General Public License (GPL), version 3.
// Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed
// under the GPL Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. Please review the Licences for the specific language governing
// permissions and limitations relating to use of the SAFE Network Software.

// TODO(dirvine) Look at aessafe 256X8 cbc it should be very much faster :01/03/2015
use crate::sequential::{Iv, Key};
use crate::{SelfEncryptionError, StorageError};
use aes::Aes128;
use block_modes::block_padding::Pkcs7;
use block_modes::{BlockMode, Cbc};
type Aes128Cbc = Cbc<Aes128, Pkcs7>;

use rust_sodium::crypto::secretbox::{self, KEYBYTES, NONCEBYTES};
pub const KEY_SIZE: usize = 16;
pub const IV_SIZE: usize = 16;

pub use rust_sodium::crypto::secretbox::{Key, Nonce as Iv};
pub type DecryptionError = ();

pub const KEY_SIZE: usize = KEYBYTES;
pub const IV_SIZE: usize = NONCEBYTES;

pub fn encrypt(data: &[u8], key: &Key, iv: &Iv) -> Vec<u8> {
secretbox::seal(data, iv, key)
pub fn encrypt<E>(data: &[u8], key: &Key, iv: &Iv) -> Result<Vec<u8>, SelfEncryptionError<E>>
where
E: StorageError,
{
let cipher = Aes128Cbc::new_var(key.0.as_ref(), iv.0.as_ref())
.map_err(|e| SelfEncryptionError::Cipher(format!("{:?}", e)))?;
Ok(cipher.encrypt_vec(data))
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Much nicer

}

pub fn decrypt(encrypted_data: &[u8], key: &Key, iv: &Iv) -> Result<Vec<u8>, DecryptionError> {
secretbox::open(encrypted_data, iv, key)
pub fn decrypt<E>(
encrypted_data: &[u8],
key: &Key,
iv: &Iv,
) -> Result<Vec<u8>, SelfEncryptionError<E>>
where
E: StorageError,
{
let cipher = Aes128Cbc::new_var(key.0.as_ref(), iv.0.as_ref())
.map_err(|err| SelfEncryptionError::Cipher(format!("{:?}", err)))?;
cipher
.decrypt_vec(encrypted_data)
.map_err(|err| SelfEncryptionError::Decryption(format!("{:?}", err)))
}
30 changes: 19 additions & 11 deletions src/error.rs
Expand Up @@ -6,7 +6,7 @@
// KIND, either express or implied. Please review the Licences for the specific language governing
// permissions and limitations relating to use of the SAFE Network Software.

use crate::{encryption::DecryptionError, storage::StorageError};
use crate::storage::StorageError;
use std::{
error::Error as StdError,
fmt::{self, Display, Formatter},
Expand All @@ -18,8 +18,12 @@ use std::{
pub enum SelfEncryptionError<E: StorageError> {
/// An error during compression or decompression.
Compression,
/// An error within the symmetric encryption or decryption process.
Decryption,
/// An error during initializing CBC-AES cipher instance.
Cipher(String),
/// An error within the symmetric encryption process.
Encryption,
/// An error within the symmetric decryption process.
Decryption(String),
/// A generic I/O error, likely arising from use of memmap.
Io(IoError),
/// An error in putting or retrieving chunks from the storage object.
Expand All @@ -32,7 +36,15 @@ impl<E: StorageError> Display for SelfEncryptionError<E> {
SelfEncryptionError::Compression => {
write!(formatter, "Error while compressing or decompressing")
}
SelfEncryptionError::Decryption => write!(formatter, "Symmetric decryption error"),
SelfEncryptionError::Cipher(ref error) => write!(
formatter,
"Error while creating cipher instance: {:?}",
error
),
SelfEncryptionError::Decryption(ref error) => {
write!(formatter, "Symmetric decryption error: {:?}", error)
}
SelfEncryptionError::Encryption => write!(formatter, "Symmetric encryption error"),
SelfEncryptionError::Io(ref error) => {
write!(formatter, "Internal I/O error: {}", error)
}
Expand All @@ -47,19 +59,15 @@ impl<E: StorageError> StdError for SelfEncryptionError<E> {
fn description(&self) -> &str {
match *self {
SelfEncryptionError::Compression => "Compression error",
SelfEncryptionError::Decryption => "Symmetric decryption error",
SelfEncryptionError::Cipher(_) => "Cipher error",
SelfEncryptionError::Decryption(_) => "Symmetric decryption error",
SelfEncryptionError::Encryption => "Symmetric encryption error",
SelfEncryptionError::Io(_) => "I/O error",
SelfEncryptionError::Storage(ref error) => error.description(),
}
}
}

impl<E: StorageError> From<DecryptionError> for SelfEncryptionError<E> {
fn from(_error: DecryptionError) -> SelfEncryptionError<E> {
SelfEncryptionError::Decryption
}
}

impl<E: StorageError> From<IoError> for SelfEncryptionError<E> {
fn from(error: IoError) -> SelfEncryptionError<E> {
SelfEncryptionError::Io(error)
Expand Down
14 changes: 4 additions & 10 deletions src/self_encryptor.rs
Expand Up @@ -11,13 +11,13 @@ use super::{
};
use crate::{
data_map::{ChunkDetails, DataMap},
encryption::{self, Iv, Key, IV_SIZE, KEY_SIZE},
encryption::{self, IV_SIZE, KEY_SIZE},
sequencer::{Sequencer, MAX_IN_MEMORY_SIZE},
sequential::{Iv, Key},
util::{BoxFuture, FutureExt},
};
use brotli::{self, enc::BrotliEncoderParams};
use futures::{future, Future};
use rust_sodium;
use std::{
cell::RefCell,
cmp,
Expand Down Expand Up @@ -78,7 +78,6 @@ where
storage: S,
data_map: DataMap,
) -> Result<SelfEncryptor<S>, SelfEncryptionError<S::Error>> {
initialise_rust_sodium();
let file_size = data_map.len();
let mut sequencer = if file_size <= MAX_IN_MEMORY_SIZE as u64 {
Sequencer::new_as_vector()
Expand Down Expand Up @@ -404,7 +403,6 @@ where
let pos = get_start_end_positions(self.file_size, i as u32).0 as usize;

assert!(this_size > 0);

let pki = get_pad_key_and_iv(i as u32, &new_map, self.file_size);
let content = match encrypt_chunk(&(*self.sequencer)[pos..pos + this_size], pki) {
Ok(content) => content,
Expand Down Expand Up @@ -587,7 +585,7 @@ where
.map_err(SelfEncryptionError::Storage)
.and_then(move |content| {
let xor_result = xor(&content, &pad);
encryption::decrypt(&xor_result, &key, &iv).map_err(|_| SelfEncryptionError::Decryption)
encryption::decrypt(&xor_result, &key, &iv)
})
.and_then(|decrypted| {
let mut decompressed = vec![];
Expand All @@ -610,7 +608,7 @@ fn encrypt_chunk<E: StorageError>(
if result.is_err() {
return Err(SelfEncryptionError::Compression);
}
let encrypted = encryption::encrypt(&compressed, &key, &iv);
let encrypted = encryption::encrypt(&compressed, &key, &iv)?;
Ok(xor(&encrypted, &pad))
}

Expand Down Expand Up @@ -806,10 +804,6 @@ impl<S: Storage> Debug for SelfEncryptor<S> {
}
}

fn initialise_rust_sodium() {
assert!(rust_sodium::init().is_ok());
}

#[cfg(test)]
mod tests {
use super::{
Expand Down
3 changes: 1 addition & 2 deletions src/sequential/encryptor.rs
Expand Up @@ -10,7 +10,7 @@ use super::{
large_encryptor::{self, LargeEncryptor},
medium_encryptor::{self, MediumEncryptor},
small_encryptor::SmallEncryptor,
utils, SelfEncryptionError, Storage,
SelfEncryptionError, Storage,
};
use crate::{
data_map::DataMap,
Expand Down Expand Up @@ -130,7 +130,6 @@ where
storage: S,
data_map: Option<DataMap>,
) -> BoxFuture<Encryptor<S>, SelfEncryptionError<S::Error>> {
utils::initialise_rust_sodium();
match data_map {
Some(DataMap::Content(content)) => SmallEncryptor::new(storage, content)
.map(State::from)
Expand Down
2 changes: 2 additions & 0 deletions src/sequential/mod.rs
Expand Up @@ -22,3 +22,5 @@ pub const HASH_SIZE: usize = 32;
pub const PAD_SIZE: usize = (HASH_SIZE * 3) - KEY_SIZE - IV_SIZE;

pub struct Pad(pub [u8; PAD_SIZE]);
pub struct Key(pub [u8; KEY_SIZE]);
pub struct Iv(pub [u8; IV_SIZE]);
10 changes: 3 additions & 7 deletions src/sequential/utils.rs
Expand Up @@ -9,12 +9,12 @@
use super::{Pad, SelfEncryptionError, StorageError, COMPRESSION_QUALITY, PAD_SIZE};
use crate::{
data_map::ChunkDetails,
encryption::{self, Iv, Key, IV_SIZE, KEY_SIZE},
encryption::{self, IV_SIZE, KEY_SIZE},
sequential::{Iv, Key},
};
use brotli::{self, enc::BrotliEncoderParams};
#[cfg(test)]
use rand::Rng;
use rust_sodium;
#[cfg(test)]
use std::cmp;
use std::io::Cursor;
Expand Down Expand Up @@ -60,7 +60,7 @@ pub fn encrypt_chunk<E: StorageError>(
if result.is_err() {
return Err(SelfEncryptionError::Compression);
}
let encrypted = encryption::encrypt(&compressed, &key, &iv);
let encrypted = encryption::encrypt(&compressed, &key, &iv)?;
Ok(xor(&encrypted, &pad))
}

Expand All @@ -87,10 +87,6 @@ pub fn xor(data: &[u8], &Pad(pad): &Pad) -> Vec<u8> {
.collect()
}

pub fn initialise_rust_sodium() {
assert!(rust_sodium::init().is_ok());
}

#[cfg(test)]
pub fn make_random_pieces<'a, T: Rng>(
rng: &mut T,
Expand Down
9 changes: 3 additions & 6 deletions tests/lib.rs
Expand Up @@ -293,12 +293,9 @@ fn write_random_sizes_out_of_sequence_with_gaps_and_overlaps() {
fn cross_platform_check() {
#[rustfmt::skip]
static EXPECTED_HASHES: [[u8; 32]; 3] = [
[98, 4, 121, 14, 80, 44, 103, 243, 182, 251, 248, 171, 11, 254, 131, 103, 156, 178, 138,
217, 103, 136, 72, 247, 125, 195, 212, 138, 115, 116, 227, 114],
[167, 132, 31, 67, 233, 190, 215, 173, 208, 106, 242, 71, 1, 114, 195, 50, 127, 158, 143,
187, 72, 11, 106, 107, 65, 219, 4, 243, 46, 43, 29, 116],
[133, 35, 122, 193, 107, 25, 207, 120, 214, 149, 158, 221, 143, 155, 90, 97, 5, 77, 94,
52, 235, 252, 6, 150, 80, 188, 143, 146, 116, 221, 107, 107],
[90, 123, 178, 77, 189, 56, 250, 228, 43, 186, 33, 61, 74, 91, 212, 16, 157, 230, 227, 31, 132, 167, 178, 127, 44, 33, 184, 3, 80, 29, 195, 41],
jeanphilippeD marked this conversation as resolved.
Show resolved Hide resolved
[28, 140, 54, 94, 73, 131, 229, 215, 75, 243, 169, 19, 239, 219, 112, 252, 107, 16, 114, 249, 219, 17, 212, 110, 99, 192, 86, 182, 30, 208, 213, 64],
[148, 67, 120, 59, 152, 244, 232, 6, 37, 187, 230, 153, 188, 190, 244, 156, 218, 116, 25, 129, 208, 78, 180, 236, 123, 14, 82, 255, 209, 231, 22, 129],
];

let mut chars0 = Vec::<u8>::new();
Expand Down