Skip to content

Commit

Permalink
fix: Fix various clippy and fmt warnings (#16)
Browse files Browse the repository at this point in the history
* fix: Fix various clippy warnings

* chore: Run rustfmt
  • Loading branch information
rajivshah3 authored Nov 17, 2020
1 parent c4ba6ec commit fd4a2b6
Show file tree
Hide file tree
Showing 7 changed files with 122 additions and 54 deletions.
30 changes: 19 additions & 11 deletions src/ciphers/aes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,10 @@ use crate::Error;

pub mod AES_256_GCM {
use super::*;
use aes_gcm::Aes256Gcm;
use aes_gcm::aead::{AeadMutInPlace, NewAead, generic_array::GenericArray};
use aes_gcm::{
aead::{generic_array::GenericArray, AeadMutInPlace, NewAead},
Aes256Gcm,
};

pub const KEY_LENGTH: usize = 32;
pub const IV_LENGTH: usize = 12;
Expand All @@ -34,17 +36,17 @@ pub mod AES_256_GCM {
tag: &mut [u8; TAG_LENGTH],
) -> crate::Result<()> {
if plaintext.len() > ciphertext.len() {
return Err(Error::BufferSize{ needs: plaintext.len(), has: ciphertext.len() });
return Err(Error::BufferSize {
needs: plaintext.len(),
has: ciphertext.len(),
});
}
ciphertext.copy_from_slice(plaintext);

let t = Aes256Gcm::new(GenericArray::from_slice(key))
.encrypt_in_place_detached(
GenericArray::from_slice(iv),
associated_data,
ciphertext,
).map_err(|_| {
Error::CipherError { alg: "AES_256_GCM::encrypt" }
.encrypt_in_place_detached(GenericArray::from_slice(iv), associated_data, ciphertext)
.map_err(|_| Error::CipherError {
alg: "AES_256_GCM::encrypt",
})?;

tag.copy_from_slice(t.as_slice());
Expand All @@ -60,7 +62,10 @@ pub mod AES_256_GCM {
plaintext: &mut [u8],
) -> crate::Result<()> {
if ciphertext.len() > plaintext.len() {
return Err(Error::BufferSize{ needs: ciphertext.len(), has: plaintext.len()});
return Err(Error::BufferSize {
needs: ciphertext.len(),
has: plaintext.len(),
});
}
plaintext.copy_from_slice(ciphertext);

Expand All @@ -70,7 +75,10 @@ pub mod AES_256_GCM {
associated_data,
plaintext,
GenericArray::from_slice(tag),
).map_err(|_| Error::CipherError { alg: "AES_256_GCM::decrypt" } )
)
.map_err(|_| Error::CipherError {
alg: "AES_256_GCM::decrypt",
})
}
}

Expand Down
92 changes: 74 additions & 18 deletions src/ciphers/chacha.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,10 @@ pub mod xchacha20poly1305 {
associated_data: &[u8],
) -> crate::Result<()> {
if plaintext.len() > ciphertext.len() {
return Err(Error::BufferSize{ needs: plaintext.len(), has: ciphertext.len() });
return Err(Error::BufferSize {
needs: plaintext.len(),
has: ciphertext.len(),
});
}
ciphertext.copy_from_slice(plaintext);

Expand All @@ -43,8 +46,10 @@ pub mod xchacha20poly1305 {
Ok(t) => {
tag.copy_from_slice(t.as_slice());
Ok(())
},
Err(_) => Err(Error::CipherError { alg: "xchacha20poly1305::encrypt" })
}
Err(_) => Err(Error::CipherError {
alg: "xchacha20poly1305::encrypt",
}),
}
}

Expand All @@ -57,17 +62,21 @@ pub mod xchacha20poly1305 {
associated_data: &[u8],
) -> crate::Result<()> {
if ciphertext.len() > plaintext.len() {
return Err(Error::BufferSize{ needs: ciphertext.len(), has: plaintext.len()});
return Err(Error::BufferSize {
needs: ciphertext.len(),
has: plaintext.len(),
});
}
plaintext.copy_from_slice(ciphertext);

let k = chacha20poly1305::Key::from_slice(key);
let n = chacha20poly1305::XNonce::from_slice(nonce);
let t = chacha20poly1305::Tag::from_slice(tag);
let mut c = chacha20poly1305::XChaCha20Poly1305::new(k);
c.decrypt_in_place_detached(n, associated_data, plaintext, t).map_err(|_| {
Error::CipherError { alg: "xchacha20poly1305::decrypt" }
})
c.decrypt_in_place_detached(n, associated_data, plaintext, t)
.map_err(|_| Error::CipherError {
alg: "xchacha20poly1305::decrypt",
})
}

#[cfg(test)]
Expand Down Expand Up @@ -144,24 +153,71 @@ pub mod xchacha20poly1305 {
assert_eq!(expected_tag, tag);

let mut decrypted_plain_text = vec![0; ciphertext.len()];
decrypt(&mut decrypted_plain_text, &ciphertext, &key, &tag, &nonce, &associated_data)?;
decrypt(
&mut decrypted_plain_text,
&ciphertext,
&key,
&tag,
&nonce,
&associated_data,
)?;
assert_eq!(decrypted_plain_text, plaintext);

let mut corrupted_tag = tag.clone();
let mut corrupted_tag = tag;
crate::test_utils::corrupt(&mut corrupted_tag);
assert!(decrypt(&mut decrypted_plain_text, &ciphertext, &key, &corrupted_tag, &nonce, &associated_data).is_err());

let mut corrupted_nonce = nonce.clone();
assert!(decrypt(
&mut decrypted_plain_text,
&ciphertext,
&key,
&corrupted_tag,
&nonce,
&associated_data
)
.is_err());

let mut corrupted_nonce = nonce;
crate::test_utils::corrupt(&mut corrupted_nonce);
assert!(decrypt(&mut decrypted_plain_text, &ciphertext, &key, &tag, &corrupted_nonce, &associated_data).is_err());

if associated_data.len() > 0 {
assert!(decrypt(
&mut decrypted_plain_text,
&ciphertext,
&key,
&tag,
&corrupted_nonce,
&associated_data
)
.is_err());

if !associated_data.is_empty() {
let mut corrupted_associated_data = associated_data.clone();
crate::test_utils::corrupt(&mut corrupted_associated_data);
assert!(decrypt(&mut decrypted_plain_text, &ciphertext, &key, &tag, &nonce, &corrupted_associated_data).is_err());
assert!(decrypt(&mut decrypted_plain_text, &ciphertext, &key, &tag, &nonce, &crate::test_utils::fresh::bytestring()).is_err());
assert!(decrypt(
&mut decrypted_plain_text,
&ciphertext,
&key,
&tag,
&nonce,
&corrupted_associated_data
)
.is_err());
assert!(decrypt(
&mut decrypted_plain_text,
&ciphertext,
&key,
&tag,
&nonce,
&crate::test_utils::fresh::bytestring()
)
.is_err());
} else {
assert!(decrypt(&mut decrypted_plain_text, &ciphertext, &key, &tag, &nonce, &crate::test_utils::fresh::non_empty_bytestring()).is_err());
assert!(decrypt(
&mut decrypted_plain_text,
&ciphertext,
&key,
&tag,
&nonce,
&crate::test_utils::fresh::non_empty_bytestring()
)
.is_err());
}
}

Expand Down
6 changes: 3 additions & 3 deletions src/ciphers/mod.rs
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
// Copyright 2020 IOTA Stiftung
//
// Licensed under the Apache License, Version 2.0 (the "License");
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// See the License for the specific language governing permissions and
// limitations under the License.

#[cfg(feature = "chacha")]
Expand Down
15 changes: 6 additions & 9 deletions src/ed25519.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,9 +54,10 @@ impl PublicKey {

pub fn from_compressed_bytes(bs: [u8; COMPRESSED_PUBLIC_KEY_LENGTH]) -> crate::Result<Self> {
ed25519_zebra::VerificationKey::try_from(bs)
.map(|vk| Self(vk))
.map(Self)
.map_err(|_| crate::Error::ConvertError {
from: "compressed bytes", to: "Ed25519 public key"
from: "compressed bytes",
to: "Ed25519 public key",
})
}
}
Expand All @@ -74,10 +75,7 @@ impl Signature {
}

pub fn verify(pk: &PublicKey, sig: &Signature, msg: &[u8]) -> bool {
match pk.0.verify(&sig.0, msg) {
Ok(_) => true,
Err(_) => false,
}
pk.0.verify(&sig.0, msg).is_ok()
}

#[cfg(test)]
Expand Down Expand Up @@ -139,7 +137,7 @@ mod tests {

crate::test_utils::corrupt(&mut sigb);
let incorrect_sig = Signature::from_bytes(sigb);
assert!(! verify(&pk, &incorrect_sig, &msg));
assert!(!verify(&pk, &incorrect_sig, &msg));
}

Ok(())
Expand All @@ -159,9 +157,8 @@ mod tests {
let mut sigb = sig.to_bytes();
crate::test_utils::corrupt(&mut sigb);
let incorrect_sig = Signature::from_bytes(sigb);
assert!(! verify(&sk.public_key(), &incorrect_sig, &msg));
assert!(!verify(&sk.public_key(), &incorrect_sig, &msg));

Ok(())
}
}

23 changes: 14 additions & 9 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,22 +43,27 @@ pub enum Error {
ConvertError { from: &'static str, to: &'static str },
/// Private Key Error
PrivateKeyError,
SystemError { call: &'static str, raw_os_error: Option<i32> },
SystemError {
call: &'static str,
raw_os_error: Option<i32>,
},
}

impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Error::BufferSize { needs, has } =>
write!(f, "buffer needs {} bytes, but it only has {}", needs, has),
Error::BufferSize { needs, has } => write!(f, "buffer needs {} bytes, but it only has {}", needs, has),
Error::CipherError { alg } => write!(f, "error in algorithm {}", alg),
Error::ConvertError { from, to } =>
write!(f, "failed to convert {} to {}", from, to),
Error::ConvertError { from, to } => write!(f, "failed to convert {} to {}", from, to),
Error::PrivateKeyError => write!(f, "Failed to generate private key."),
Error::SystemError { call, raw_os_error: None } =>
write!(f, "system error when calling {}", call),
Error::SystemError { call, raw_os_error: Some(errno) } =>
write!(f, "system error when calling {}: {}", call, errno),
Error::SystemError {
call,
raw_os_error: None,
} => write!(f, "system error when calling {}", call),
Error::SystemError {
call,
raw_os_error: Some(errno),
} => write!(f, "system error when calling {}: {}", call, errno),
}
}
}
Expand Down
6 changes: 3 additions & 3 deletions src/rand.rs
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
// Copyright 2020 IOTA Stiftung
//
// Licensed under the Apache License, Version 2.0 (the "License");
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// See the License for the specific language governing permissions and
// limitations under the License.

pub fn fill(bs: &mut [u8]) -> crate::Result<()> {
Expand Down
4 changes: 3 additions & 1 deletion src/test_utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,9 @@ pub mod fresh {
use super::*;

pub fn bytestring() -> Vec<u8> {
let s = if rand::random::<u8>() % 4 == 0 { 0 } else {
let s = if rand::random::<u8>() % 4 == 0 {
0
} else {
rand::random::<usize>() % 4096
};

Expand Down

0 comments on commit fd4a2b6

Please sign in to comment.