Skip to content

Commit

Permalink
refactor: switch from num_derive to num_enum
Browse files Browse the repository at this point in the history
  • Loading branch information
hko-s committed Jan 22, 2024
1 parent 0e673a2 commit 8014e49
Show file tree
Hide file tree
Showing 23 changed files with 86 additions and 89 deletions.
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ idea = "^0.5"
log = "0.4.6"
md-5 = { version = "^0.10.5", features = ["oid"] }
nom = "^7.0"
num-derive = "0.4.0"
num_enum = "0.7"
num-traits = "0.2.6"
p256 = { version = "^0.13", features = ["ecdsa"] }
p384 = { version = "^0.13", features = ["ecdsa"] }
Expand Down
10 changes: 4 additions & 6 deletions src/composed/message/decrypt.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
use std::boxed::Box;
use std::io::Cursor;

use num_traits::FromPrimitive;

use crate::composed::message::types::{Edata, Message};
use crate::composed::shared::Deserializable;
use crate::crypto::sym::SymmetricKeyAlgorithm;
Expand Down Expand Up @@ -35,8 +33,8 @@ where
}
SecretKeyRepr::EdDSA(_) => unimplemented_err!("EdDSA"),
};
let algorithm = SymmetricKeyAlgorithm::from_u8(decrypted_key[0])
.ok_or_else(|| format_err!("invalid symmetric key algorithm"))?;
let algorithm = SymmetricKeyAlgorithm::try_from(decrypted_key[0])
.map_err(|_| format_err!("invalid symmetric key algorithm"))?;
alg = Some(algorithm);
debug!("alg: {:?}", alg);

Expand Down Expand Up @@ -88,8 +86,8 @@ where
.sym_algorithm()
.decrypt_with_iv_regular(&key, &iv, &mut decrypted_key)?;

let alg = SymmetricKeyAlgorithm::from_u8(decrypted_key[0])
.ok_or_else(|| format_err!("invalid symmetric key algorithm"))?;
let alg = SymmetricKeyAlgorithm::try_from(decrypted_key[0])
.map_err(|_| format_err!("invalid symmetric key algorithm"))?;

Ok((decrypted_key[1..].to_vec(), alg))
}
Expand Down
4 changes: 3 additions & 1 deletion src/crypto/aead.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
use num_enum::TryFromPrimitive;

/// Available AEAD algorithms.
#[derive(Debug, PartialEq, Eq, Copy, Clone, FromPrimitive)]
#[derive(Debug, PartialEq, Eq, Copy, Clone, TryFromPrimitive)]
#[repr(u8)]
#[derive(Default)]
pub enum AeadAlgorithm {
Expand Down
3 changes: 2 additions & 1 deletion src/crypto/hash.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,15 @@ use std::boxed::Box;

use digest::Digest;
use md5::Md5;
use num_enum::TryFromPrimitive;
use ripemd::Ripemd160;
use sha1::Sha1;

use crate::errors::Result;

/// Available hash algorithms.
/// Ref: https://tools.ietf.org/html/rfc4880.html#section-9.4
#[derive(Debug, PartialEq, Eq, Copy, Clone, FromPrimitive)]
#[derive(Debug, PartialEq, Eq, Copy, Clone, TryFromPrimitive)]
#[repr(u8)]
#[derive(Default)]
pub enum HashAlgorithm {
Expand Down
4 changes: 3 additions & 1 deletion src/crypto/public_key.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
#[derive(Debug, PartialEq, Eq, Clone, Copy, FromPrimitive)]
use num_enum::TryFromPrimitive;

#[derive(Debug, PartialEq, Eq, Clone, Copy, TryFromPrimitive)]
#[repr(u8)]
pub enum PublicKeyAlgorithm {
/// RSA (Encrypt and Sign)
Expand Down
3 changes: 2 additions & 1 deletion src/crypto/sym.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ use cfb_mode::cipher::{AsyncStreamCipher, KeyIvInit};
use cfb_mode::{BufDecryptor, BufEncryptor, Decryptor, Encryptor};
use des::TdesEde3;
use idea::Idea;
use num_enum::TryFromPrimitive;
use rand::{thread_rng, CryptoRng, Rng};
use sha1::{Digest, Sha1};
use twofish::Twofish;
Expand Down Expand Up @@ -71,7 +72,7 @@ macro_rules! encrypt_regular {
}

/// Available [symmetric key algorithms](https://tools.ietf.org/html/rfc4880#section-9.2).
#[derive(Debug, PartialEq, Eq, Copy, Clone, FromPrimitive)]
#[derive(Debug, PartialEq, Eq, Copy, Clone, TryFromPrimitive)]
#[repr(u8)]
#[derive(Default)]
pub enum SymmetricKeyAlgorithm {
Expand Down
2 changes: 0 additions & 2 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,6 @@
#[macro_use]
extern crate nom;
#[macro_use]
extern crate num_derive;
#[macro_use]
extern crate generic_array;
#[macro_use]
extern crate log;
Expand Down
5 changes: 2 additions & 3 deletions src/packet/compressed_data.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ use std::fmt;
use std::io::{self, Cursor, Read};

use flate2::read::{DeflateDecoder, ZlibDecoder};
use num_traits::FromPrimitive;

use crate::errors::Result;
use crate::packet::PacketTrait;
Expand Down Expand Up @@ -39,8 +38,8 @@ impl CompressedData {
pub fn from_slice(packet_version: Version, input: &[u8]) -> Result<Self> {
ensure!(input.len() > 1, "input too short");

let alg = CompressionAlgorithm::from_u8(input[0])
.ok_or_else(|| format_err!("invalid compression algorithm"))?;
let alg = CompressionAlgorithm::try_from(input[0])
.map_err(|_| format_err!("invalid compression algorithm"))?;
Ok(CompressedData {
packet_version,
compression_algorithm: alg,
Expand Down
8 changes: 4 additions & 4 deletions src/packet/literal_data.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,12 @@ use std::{fmt, io};
use bstr::{BStr, BString};
use byteorder::{BigEndian, WriteBytesExt};
use chrono::{DateTime, SubsecRound, TimeZone, Utc};
use nom::combinator::{map, map_opt, rest};
use nom::combinator::{map, map_opt, map_res, rest};
use nom::multi::length_data;
use nom::number::streaming::{be_u32, be_u8};
use nom::sequence::tuple;
use nom::IResult;
use num_traits::FromPrimitive;
use num_enum::TryFromPrimitive;

use crate::errors::Result;
use crate::line_writer::LineBreak;
Expand All @@ -31,7 +31,7 @@ pub struct LiteralData {
data: Vec<u8>,
}

#[derive(Debug, Copy, Clone, FromPrimitive, PartialEq, Eq)]
#[derive(Debug, Copy, Clone, TryFromPrimitive, PartialEq, Eq)]
#[repr(u8)]
pub enum DataMode {
Binary = b'b',
Expand Down Expand Up @@ -109,7 +109,7 @@ fn parse(packet_version: Version) -> impl Fn(&[u8]) -> IResult<&[u8], LiteralDat
move |i: &[u8]| {
map(
tuple((
map_opt(be_u8, DataMode::from_u8),
map_res(be_u8, DataMode::try_from),
map(length_data(be_u8), BStr::new::<[u8]>),
map_opt(be_u32, |v| Utc.timestamp_opt(i64::from(v), 0).single()),
rest,
Expand Down
3 changes: 1 addition & 2 deletions src/packet/many.rs
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,6 @@ mod tests {
#![allow(clippy::unwrap_used)]

use super::*;
use num_traits::FromPrimitive;
use regex::Regex;
use std::fs::File;
use std::io::{BufRead, BufReader, Seek, SeekFrom};
Expand Down Expand Up @@ -276,7 +275,7 @@ mod tests {

// println!("\n-- checking: {:?} {}", packet.tag(), e);

let tag = Tag::from_u8(tag.parse().unwrap()).unwrap();
let tag: Tag = u8::try_into(tag.parse().unwrap()).unwrap();
assert_eq!(tag, packet.tag(), "missmatch in packet {:?} ({})", p, e);
}
}
Expand Down
9 changes: 4 additions & 5 deletions src/packet/one_pass_signature.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
use std::io;

use nom::bytes::streaming::take;
use nom::combinator::{map, map_opt, map_res};
use nom::combinator::{map, map_res};
use nom::number::streaming::be_u8;
use nom::sequence::tuple;
use nom::IResult;
use num_traits::FromPrimitive;

use crate::crypto::hash::HashAlgorithm;
use crate::crypto::public_key::PublicKeyAlgorithm;
Expand Down Expand Up @@ -63,9 +62,9 @@ fn parse(packet_version: Version) -> impl Fn(&[u8]) -> IResult<&[u8], OnePassSig
map(
tuple((
be_u8,
map_opt(be_u8, SignatureType::from_u8),
map_opt(be_u8, HashAlgorithm::from_u8),
map_opt(be_u8, PublicKeyAlgorithm::from_u8),
map_res(be_u8, SignatureType::try_from),
map_res(be_u8, HashAlgorithm::try_from),
map_res(be_u8, PublicKeyAlgorithm::try_from),
map_res(take(8usize), KeyId::from_slice),
be_u8,
)),
Expand Down
5 changes: 2 additions & 3 deletions src/packet/public_key_encrypted_session_key.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,9 @@ use std::io;

use byteorder::{BigEndian, ByteOrder, WriteBytesExt};
use nom::bytes::streaming::take;
use nom::combinator::{map, map_opt, map_res};
use nom::combinator::{map, map_res};
use nom::number::streaming::be_u8;
use nom::sequence::pair;
use num_traits::FromPrimitive;
use rand::{CryptoRng, Rng};

use crate::crypto::checksum;
Expand Down Expand Up @@ -116,7 +115,7 @@ fn parse(
// the key id this maps to
let (i, id) = map_res(take(8u8), KeyId::from_slice)(i)?;
// the symmetric key algorithm
let (i, alg) = map_opt(be_u8, PublicKeyAlgorithm::from_u8)(i)?;
let (i, alg) = map_res(be_u8, PublicKeyAlgorithm::try_from)(i)?;

// key algorithm specific data
let (i, mpis) = parse_mpis(&alg, i)?;
Expand Down
13 changes: 6 additions & 7 deletions src/packet/public_key_parser.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
use chrono::{DateTime, TimeZone, Utc};
use nom::bytes::streaming::tag;
use nom::combinator::{map, map_opt};
use nom::combinator::{map, map_opt, map_res};
use nom::multi::length_data;
use nom::number::streaming::{be_u16, be_u32, be_u8};
use nom::sequence::{pair, tuple};
use num_traits::FromPrimitive;

use crate::crypto::ecc_curve::ecc_curve_from_oid;
use crate::crypto::hash::HashAlgorithm;
Expand Down Expand Up @@ -68,10 +67,10 @@ fn ecdh(i: &[u8]) -> IResult<&[u8], PublicParams> {
// a one-octet value 01, reserved for future extensions
tag(&[1][..]),
// a one-octet hash function ID used with a KDF
map_opt(be_u8, HashAlgorithm::from_u8),
map_res(be_u8, HashAlgorithm::try_from),
// a one-octet algorithm ID for the symmetric algorithm used to wrap
// the symmetric key used for the message encryption
map_opt(be_u8, SymmetricKeyAlgorithm::from_u8),
map_res(be_u8, SymmetricKeyAlgorithm::try_from),
)),
|(curve, p, _len2, _tag, hash, alg_sym)| PublicParams::ECDH {
curve,
Expand Down Expand Up @@ -147,7 +146,7 @@ fn new_public_key_parser(
> + '_ {
|i: &[u8]| {
let (i, created_at) = map_opt(be_u32, |v| Utc.timestamp_opt(i64::from(v), 0).single())(i)?;
let (i, alg) = map_opt(be_u8, PublicKeyAlgorithm::from_u8)(i)?;
let (i, alg) = map_res(be_u8, PublicKeyAlgorithm::try_from)(i)?;
let (i, params) = parse_pub_fields(alg)(i)?;
Ok((i, (*key_ver, alg, created_at, None, params)))
}
Expand All @@ -170,7 +169,7 @@ fn old_public_key_parser(
|i: &[u8]| {
let (i, created_at) = map_opt(be_u32, |v| Utc.timestamp_opt(i64::from(v), 0).single())(i)?;
let (i, exp) = be_u16(i)?;
let (i, alg) = map_opt(be_u8, PublicKeyAlgorithm::from_u8)(i)?;
let (i, alg) = map_res(be_u8, PublicKeyAlgorithm::try_from)(i)?;
let (i, params) = parse_pub_fields(alg)(i)?;

Ok((i, (*key_ver, alg, created_at, Some(exp), params)))
Expand All @@ -192,7 +191,7 @@ pub(crate) fn parse(
PublicParams,
),
> {
let (i, key_ver) = map_opt(be_u8, KeyVersion::from_u8)(i)?;
let (i, key_ver) = map_res(be_u8, KeyVersion::try_from)(i)?;
let (i, key) = match &key_ver {
&KeyVersion::V2 | &KeyVersion::V3 => old_public_key_parser(&key_ver)(i)?,
&KeyVersion::V4 => new_public_key_parser(&key_ver)(i)?,
Expand Down
7 changes: 3 additions & 4 deletions src/packet/secret_key_parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ use chrono::{DateTime, TimeZone, Utc};
use nom::combinator::{map_opt, map_res, rest};
use nom::number::streaming::{be_u16, be_u32, be_u8};
use nom::sequence::tuple;
use num_traits::FromPrimitive;

use crate::crypto::public_key::PublicKeyAlgorithm;
use crate::errors::{Error, IResult};
Expand Down Expand Up @@ -38,7 +37,7 @@ fn new_private_key_parser(
> + '_ {
|i: &[u8]| {
let (i, created_at) = map_opt(be_u32, |v| Utc.timestamp_opt(i64::from(v), 0).single())(i)?;
let (i, alg) = map_opt(be_u8, PublicKeyAlgorithm::from_u8)(i)?;
let (i, alg) = map_res(be_u8, PublicKeyAlgorithm::try_from)(i)?;
let (i, params) = parse_pub_priv_fields(alg)(i)?;
Ok((i, (*key_ver, alg, created_at, None, params.0, params.1)))
}
Expand All @@ -62,7 +61,7 @@ fn old_private_key_parser(
|i: &[u8]| {
let (i, created_at) = map_opt(be_u32, |v| Utc.timestamp_opt(i64::from(v), 0).single())(i)?;
let (i, exp) = be_u16(i)?;
let (i, alg) = map_opt(be_u8, PublicKeyAlgorithm::from_u8)(i)?;
let (i, alg) = map_res(be_u8, PublicKeyAlgorithm::try_from)(i)?;
let (i, params) = parse_pub_priv_fields(alg)(i)?;
Ok((
i,
Expand All @@ -87,7 +86,7 @@ pub(crate) fn parse(
SecretParams,
),
> {
let (i, key_ver) = map_opt(be_u8, KeyVersion::from_u8)(i)?;
let (i, key_ver) = map_res(be_u8, KeyVersion::try_from)(i)?;
let (i, key) = match &key_ver {
&KeyVersion::V2 | &KeyVersion::V3 => old_private_key_parser(&key_ver)(i)?,
&KeyVersion::V4 => new_private_key_parser(&key_ver)(i)?,
Expand Down
Loading

0 comments on commit 8014e49

Please sign in to comment.