Skip to content

Commit

Permalink
feat: edition 2021 and update crypto deps
Browse files Browse the repository at this point in the history
Bumps msrv to 1.57
  • Loading branch information
dignifiedquire committed Nov 7, 2022
1 parent c57232e commit a0a71cc
Show file tree
Hide file tree
Showing 12 changed files with 127 additions and 90 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -312,4 +312,4 @@ jobs:
- uses: actions-rs/clippy-check@v1
with:
token: ${{ secrets.GITHUB_TOKEN }}
args: --all-features
args: --all-features
35 changes: 17 additions & 18 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,22 +15,22 @@ categories = ["cryptography", "email"]
exclude = ["tests/tests/*"]

edition = "2021"
rust-version = "1.57"

[dependencies]
aes = "^0.7"
aes = "^0.8"
base64 = "^0.13.0"
bitfield = "0.13.1"
block-modes = "^0.8"
block-padding = "0.2.0"
blowfish = "^0.8"
bitfield = "0.14"
block-padding = "^0.3.2"
blowfish = "^0.9"
byteorder = "^1.4"
cast5 = "^0.10.0"
cfb-mode = "^0.7.0"
chrono = { version = "^0.4", default-features = false, features = ["clock", "std"] }
cipher = "^0.3"
cast5 = "^0.11.0"
cfb-mode = "^0.8.1"
cipher = "^0.4"
crc24 = "^0.1"
derive_builder = "0.9.0"
des = "^0.7"
derive_builder = "^0.11.1"
des = "^0.8"
digest = "^0.10"
generic-array = "^0.14"
hex = "^0.4"
Expand All @@ -46,14 +46,14 @@ sha1 = { version = "^0.10.5", features = ["oid"] }
sha2 = { version = "^0.10.6", features = ["oid"] }
sha3 = { version = "^0.10.5", features = ["oid"] }
signature = "1.3.0"
smallvec = "1.6.1"
thiserror = "1.0.9"
twofish = "^0.6"
zeroize = { version = "1.4", features = ["zeroize_derive"] }
getrandom = { version = "0.2.3", optional = true }
smallvec = "1.8.0"
thiserror = "1.0.30"
twofish = "^0.7"
zeroize = { version = "1.5", features = ["zeroize_derive"] }
getrandom = { version = "0.2.6", optional = true }

[dependencies.buf_redux]
version = "0.8.1"
version = "0.8.4"
default-features = false

[dependencies.ed25519-dalek]
Expand All @@ -71,7 +71,7 @@ version = "0.2.0"
optional = true

[dependencies.num-bigint]
version = "0.8"
version = "0.8.1"
features = ["rand", "i128", "u64_digit", "prime", "zeroize"]
package = "num-bigint-dig"

Expand Down Expand Up @@ -100,4 +100,3 @@ wasm = ["chrono/wasmbind", "getrandom", "getrandom/js"]

[profile.bench]
debug = true

6 changes: 3 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
[![crates.io][crate-image]][crate-link]
[![Documentation][doc-image]][doc-link]
[![Build Status][build-image]][build-link]
![minimum rustc 1.51][msrv-image]
![minimum rustc 1.56][msrv-image]
[![dependency status][deps-image]][deps-link]
[![License][license-image]][license-link]

Expand Down Expand Up @@ -70,7 +70,7 @@ Some key differences:

## Minimum Supported Rust Version (MSRV)

All crates in this repository support Rust 1.51 or higher. In future minimally supported version of Rust can be changed, but it will be done with a minor version bump.
All crates in this repository support Rust 1.56 or higher. In future minimally supported version of Rust can be changed, but it will be done with a minor version bump.

## LICENSE

Expand All @@ -90,6 +90,6 @@ dual licensed as above, without any additional terms or conditions.
[license-link]: https://github.com/rpgp/rpgp/blob/master/LICENSE.md
[build-image]: https://github.com/rpgp/rpgp/workflows/CI/badge.svg
[build-link]: https://github.com/rpgp/rpgp/actions?query=workflow%3ACI+branch%3Amaster
[msrv-image]: https://img.shields.io/badge/rustc-1.51+-blue.svg
[msrv-image]: https://img.shields.io/badge/rustc-1.56+-blue.svg
[deps-image]: https://deps.rs/repo/github/rpgp/rpgp/status.svg
[deps-link]: https://deps.rs/repo/github/rpgp/rpgp
2 changes: 1 addition & 1 deletion src/armor/writer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ pub fn write(
(crc >> 8) as u8,
crc as u8,
];
let crc_enc = base64::encode_config(&crc_buf, base64::STANDARD);
let crc_enc = base64::encode_config(crc_buf, base64::STANDARD);

writer.write_all(crc_enc.as_bytes())?;

Expand Down
6 changes: 3 additions & 3 deletions src/crypto/aes_kw.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use aes::cipher::{BlockDecrypt, BlockEncrypt, NewBlockCipher};
use aes::cipher::{BlockDecrypt, BlockEncrypt, KeyInit};
use byteorder::{BigEndian, WriteBytesExt};
use generic_array::sequence::{Concat, Split};
use generic_array::typenum::U8;
Expand Down Expand Up @@ -66,7 +66,7 @@ macro_rules! impl_aes_kw {
for i in 0..n {
let t = (n * j + (i + 1)) as u64;

let cipher = <$hasher as NewBlockCipher>::new(&key);
let cipher = <$hasher as KeyInit>::new(&key);
// Safe to unwrap, as we know the size of t_arr.
(&mut t_arr[..]).write_u64::<BigEndian>(t).unwrap();

Expand Down Expand Up @@ -121,7 +121,7 @@ macro_rules! impl_aes_kw {
for i in (0..n).rev() {
let t = (n * j + (i + 1)) as u64;

let cipher = <$hasher as NewBlockCipher>::new(&key);
let cipher = <$hasher as KeyInit>::new(&key);
// Safe to unwrap, as we know the size of t_arr.
(&mut t_arr[..]).write_u64::<BigEndian>(t).unwrap();

Expand Down
113 changes: 75 additions & 38 deletions src/crypto/ecdh.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use block_padding::{Padding, Pkcs7};
use generic_array::{typenum::U8, GenericArray};
use rand::{CryptoRng, Rng};
use x25519_dalek::{PublicKey, StaticSecret};
use zeroize::{Zeroize, Zeroizing};
Expand Down Expand Up @@ -135,12 +136,23 @@ pub fn decrypt(priv_key: &ECDHSecretKey, mpis: &[Mpi], fingerprint: &[u8]) -> Re
encrypted_session_key_vec[(encrypted_key_len - encrypted_session_key.len())..]
.copy_from_slice(encrypted_session_key);

let decrypted_key_padded = aes_kw::unwrap(&z, &encrypted_session_key_vec)?;

let mut decrypted_key_padded = aes_kw::unwrap(&z, &encrypted_session_key_vec)?;
// PKCS5 unpadding (PKCS5 is PKCS7 with a blocksize of 8)
let decrypted_key = Pkcs7::unpad(&decrypted_key_padded)?;
{
let len = decrypted_key_padded.len();
let block_size = 8;
ensure!(len % block_size == 0, "invalid key length {}", len);
ensure!(!decrypted_key_padded.is_empty(), "empty key is not valid");

// grab the last block
let offset = len - block_size;
let last_block = GenericArray::<u8, U8>::from_slice(&decrypted_key_padded[offset..]);
let unpadded_last_block = Pkcs7::unpad(last_block)?;
let unpadded_len = offset + unpadded_last_block.len();
decrypted_key_padded.truncate(unpadded_len);
}

Ok(decrypted_key.to_vec())
Ok(decrypted_key_padded)
}

/// Key Derivation Function for ECDH (as defined in RFC 6637).
Expand Down Expand Up @@ -169,6 +181,14 @@ pub fn encrypt<R: CryptoRng + Rng>(
) -> Result<Vec<Vec<u8>>> {
debug!("ECDH encrypt");

// can't fit more size wise
let max_size = 239;
ensure!(
plain.len() < max_size,
"unable to encrypt larger than {} bytes",
max_size
);

let param = build_ecdh_param(&curve.oid(), alg_sym, hash, fingerprint);

ensure_eq!(q.len(), 33, "invalid public key");
Expand Down Expand Up @@ -198,7 +218,18 @@ pub fn encrypt<R: CryptoRng + Rng>(
let len = plain.len();
let mut plain_padded = plain.to_vec();
plain_padded.resize(len + 8, 0);
let plain_padded_ref = Pkcs7::pad(&mut plain_padded, len, 8)?;

let plain_padded_ref = {
let pos = len;
let block_size = 8;
let bs = block_size * (pos / block_size);
if plain_padded.len() < bs || plain_padded.len() - bs < block_size {
bail!("unable to pad");
}
let buf = GenericArray::<u8, U8>::from_mut_slice(&mut plain_padded[bs..bs + block_size]);
Pkcs7::pad(buf, pos - bs);
&plain_padded[..bs + block_size]
};

// Peform AES Key Wrap
let encrypted_key = aes_kw::wrap(&z, plain_padded_ref)?;
Expand All @@ -208,7 +239,7 @@ pub fn encrypt<R: CryptoRng + Rng>(
encoded_public.push(0x40);
encoded_public.extend(x25519_dalek::PublicKey::from(&our_secret).as_bytes().iter());

let encrypted_key_len = vec![encrypted_key.len() as u8];
let encrypted_key_len = vec![u8::try_from(encrypted_key.len())?];

Ok(vec![encoded_public, encrypted_key_len, encrypted_key])
}
Expand All @@ -227,37 +258,43 @@ mod tests {
let mut rng = ChaChaRng::from_seed([0u8; 32]);

let (pkey, skey) = generate_key(&mut rng);
let mut fingerprint = vec![0u8; 20];
rng.fill_bytes(&mut fingerprint);

let plain = b"hello world";

let mpis = match pkey {
PublicParams::ECDH {
ref curve,
ref p,
hash,
alg_sym,
} => encrypt(
&mut rng,
curve,
alg_sym,
hash,
&fingerprint,
p.as_bytes(),
&plain[..],
)
.unwrap(),
_ => panic!("invalid key generated"),
};

let mpis = mpis.into_iter().map(Into::into).collect::<Vec<Mpi>>();

let decrypted = match skey.as_ref().as_repr(&pkey).unwrap() {
SecretKeyRepr::ECDH(ref skey) => decrypt(skey, &mpis, &fingerprint).unwrap(),
_ => panic!("invalid key generated"),
};

assert_eq!(&plain[..], &decrypted[..]);

for text_size in 1..239 {
for _i in 0..10 {
let mut fingerprint = vec![0u8; 20];
rng.fill_bytes(&mut fingerprint);

let mut plain = vec![0u8; text_size];
rng.fill_bytes(&mut plain);

let mpis = match pkey {
PublicParams::ECDH {
ref curve,
ref p,
hash,
alg_sym,
} => encrypt(
&mut rng,
curve,
alg_sym,
hash,
&fingerprint,
p.as_bytes(),
&plain[..],
)
.unwrap(),
_ => panic!("invalid key generated"),
};

let mpis = mpis.into_iter().map(Into::into).collect::<Vec<Mpi>>();

let decrypted = match skey.as_ref().as_repr(&pkey).unwrap() {
SecretKeyRepr::ECDH(ref skey) => decrypt(skey, &mpis, &fingerprint).unwrap(),
_ => panic!("invalid key generated"),
};

assert_eq!(&plain[..], &decrypted[..]);
}
}
}
}
12 changes: 6 additions & 6 deletions src/crypto/sym.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
use aes::{Aes128, Aes192, Aes256};
use blowfish::Blowfish;
use cast5::Cast5;
use cfb_mode::cipher::{AsyncStreamCipher, NewCipher};
use cfb_mode::Cfb;
use cfb_mode::cipher::{AsyncStreamCipher, KeyIvInit};
use cfb_mode::{BufDecryptor, BufEncryptor, Decryptor, Encryptor};
use des::TdesEde3;
use rand::{thread_rng, CryptoRng, Rng};
use sha1::{Digest, Sha1};
Expand All @@ -13,7 +13,7 @@ use crate::errors::{Error, Result};

macro_rules! decrypt {
($mode:ident, $key:expr, $iv:expr, $prefix:expr, $data:expr, $bs:expr, $resync:expr) => {{
let mut mode = Cfb::<$mode>::new_from_slices($key, $iv)?;
let mut mode = BufDecryptor::<$mode>::new_from_slices($key, $iv)?;
mode.decrypt($prefix);

// quick check, before decrypting the rest
Expand Down Expand Up @@ -41,7 +41,7 @@ macro_rules! decrypt {

macro_rules! encrypt {
($mode:ident, $key:expr, $iv:expr, $prefix:expr, $data:expr, $bs:expr, $resync:expr) => {{
let mut mode = Cfb::<$mode>::new_from_slices($key, $iv)?;
let mut mode = BufEncryptor::<$mode>::new_from_slices($key, $iv)?;
mode.encrypt($prefix);

if $resync {
Expand All @@ -57,13 +57,13 @@ macro_rules! encrypt {

macro_rules! decrypt_regular {
($mode:ident, $key:expr, $iv:expr, $ciphertext:expr, $bs:expr) => {{
let mut mode = Cfb::<$mode>::new_from_slices($key, $iv)?;
let mode = Decryptor::<$mode>::new_from_slices($key, $iv)?;
mode.decrypt($ciphertext);
}};
}
macro_rules! encrypt_regular {
($mode:ident, $key:expr, $iv:expr, $plaintext:expr, $bs:expr) => {{
let mut mode = Cfb::<$mode>::new_from_slices($key, $iv)?;
let mode = Encryptor::<$mode>::new_from_slices($key, $iv)?;
mode.encrypt($plaintext);
}};
}
Expand Down
26 changes: 13 additions & 13 deletions src/errors.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
use std::num::TryFromIntError;

use ed25519_dalek::SignatureError;

pub type Result<T> = ::std::result::Result<T, Error>;
Expand Down Expand Up @@ -64,6 +66,8 @@ pub enum Error {
SignatureError(#[from] SignatureError),
#[error("Modification Detection Code error")]
MdcError,
#[error("Invalid size conversion {0}")]
TryFromInt(#[from] TryFromIntError),
}

impl Error {
Expand Down Expand Up @@ -97,6 +101,7 @@ impl Error {
Error::InvalidPacketContent(_) => 25,
Error::SignatureError(_) => 26,
Error::MdcError => 27,
Error::TryFromInt(_) => 28,
}
}
}
Expand Down Expand Up @@ -140,14 +145,8 @@ impl From<rsa::errors::Error> for Error {
}
}

impl From<block_modes::BlockModeError> for Error {
fn from(_: block_modes::BlockModeError) -> Error {
Error::BlockMode
}
}

impl From<cipher::errors::InvalidLength> for Error {
fn from(_: cipher::errors::InvalidLength) -> Error {
impl From<cipher::InvalidLength> for Error {
fn from(_: cipher::InvalidLength) -> Error {
Error::CfbInvalidKeyIvLength
}
}
Expand All @@ -157,18 +156,19 @@ impl From<block_padding::UnpadError> for Error {
Error::UnpadError
}
}
impl From<block_padding::PadError> for Error {
fn from(_: block_padding::PadError) -> Error {
Error::PadError
}
}

impl From<String> for Error {
fn from(err: String) -> Error {
Error::Message(err)
}
}

impl From<derive_builder::UninitializedFieldError> for Error {
fn from(err: derive_builder::UninitializedFieldError) -> Error {
Error::Message(err.to_string())
}
}

#[macro_export]
macro_rules! unimplemented_err {
($e:expr) => {
Expand Down

0 comments on commit a0a71cc

Please sign in to comment.