Skip to content

Commit

Permalink
Merge pull request #75 from hug-dev/display-type
Browse files Browse the repository at this point in the history
Implement Display on Algorithm
  • Loading branch information
hug-dev authored Feb 19, 2021
2 parents c3a73aa + 6082719 commit 9fbd3ad
Show file tree
Hide file tree
Showing 4 changed files with 117 additions and 62 deletions.
54 changes: 27 additions & 27 deletions psa-crypto-sys/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,11 +60,11 @@ mod common {
.generate_comments(false)
.size_t_is_usize(true)
.generate()
.or_else(|_| {
Err(Error::new(
ErrorKind::Other,
"Unable to generate bindings to mbed crypto",
))
.map_err(|_| {
Error::new(
ErrorKind::Other,
"Unable to generate bindings to mbed crypto",
)
})?;
let out_path = PathBuf::from(env::var("OUT_DIR").unwrap());
shim_bindings.write_to_file(out_path.join("shim_bindings.rs"))?;
Expand All @@ -81,13 +81,13 @@ mod common {
.flag("-Werror")
.opt_level(2)
.try_compile("libshim.a")
.or_else(|_| Err(Error::new(ErrorKind::Other, "compiling shim.c failed")))?;
.map_err(|_| Error::new(ErrorKind::Other, "compiling shim.c failed"))?;

// Also link shim library
println!(
"cargo:rustc-link-search=native={}",
env::var("OUT_DIR").unwrap()
);
);
println!("cargo:rustc-link-lib=static=shim");

Ok(())
Expand All @@ -97,8 +97,8 @@ mod common {
#[cfg(all(feature = "interface", not(feature = "operations")))]
mod interface {
use super::common;
use std::io::{Error, ErrorKind, Result};
use std::env;
use std::io::{Error, ErrorKind, Result};

// Build script when the interface feature is on and not the operations one
pub fn script_interface() -> Result<()> {
Expand All @@ -116,12 +116,12 @@ mod interface {

#[cfg(feature = "operations")]
mod operations {
use super::common;
use cmake::Config;
use std::env;
use std::io::{Error, ErrorKind, Result};
use std::path::PathBuf;
use walkdir::WalkDir;
use super::common;

fn compile_mbed_crypto() -> Result<PathBuf> {
let mbedtls_dir = String::from("./vendor");
Expand All @@ -133,29 +133,29 @@ mod operations {
// Configure the MbedTLS build for making Mbed Crypto
if !::std::process::Command::new(mbedtls_dir + "/scripts/config.py")
.arg("--write")
.arg(&(out_dir.clone() + "/config.h"))
.arg("crypto")
.status()
.or_else(|_| Err(Error::new(ErrorKind::Other, "configuring mbedtls failed")))?
.success()
{
return Err(Error::new(
ErrorKind::Other,
"config.py returned an error status",
));
}
.arg(&(out_dir.clone() + "/config.h"))
.arg("crypto")
.status()
.map_err(|_| Error::new(ErrorKind::Other, "configuring mbedtls failed"))?
.success()
{
return Err(Error::new(
ErrorKind::Other,
"config.py returned an error status",
));
}

// Rerun build if anything file under the vendor directory has changed.
for entry in WalkDir::new("vendor")
.into_iter()
.filter_map(|entry| entry.ok())
{
if let Ok(metadata) = entry.metadata() {
if metadata.is_file() {
println!("cargo:rerun-if-changed={}", entry.path().display());
}
}
.filter_map(|entry| entry.ok())
{
if let Ok(metadata) = entry.metadata() {
if metadata.is_file() {
println!("cargo:rerun-if-changed={}", entry.path().display());
}
}
}

// Build the MbedTLS libraries
let mbed_build_path = Config::new("vendor")
Expand Down
2 changes: 1 addition & 1 deletion psa-crypto/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ static INITIALISED: AtomicBool = AtomicBool::new(false);
pub fn init() -> Result<()> {
// It is not a problem to call psa_crypto_init more than once.
Status::from(unsafe { psa_crypto_sys::psa_crypto_init() }).to_result()?;
let _ = INITIALISED.compare_and_swap(false, true, Ordering::Relaxed);
let _ = INITIALISED.store(true, Ordering::Relaxed);

Ok(())
}
Expand Down
57 changes: 30 additions & 27 deletions psa-crypto/src/types/algorithm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,10 @@ impl Mac {
matches!(
self,
Mac::FullLength(FullLengthMac::Hmac { .. })
| Mac::Truncated { mac_alg: FullLengthMac::Hmac { .. }, .. }
| Mac::Truncated {
mac_alg: FullLengthMac::Hmac { .. },
..
}
)
}

Expand All @@ -167,15 +170,15 @@ impl Mac {
matches!(
self,
Mac::FullLength(FullLengthMac::CbcMac)
| Mac::FullLength(FullLengthMac::Cmac)
| Mac::Truncated {
mac_alg: FullLengthMac::CbcMac,
..
}
| Mac::Truncated {
mac_alg: FullLengthMac::Cmac,
..
}
| Mac::FullLength(FullLengthMac::Cmac)
| Mac::Truncated {
mac_alg: FullLengthMac::CbcMac,
..
}
| Mac::Truncated {
mac_alg: FullLengthMac::Cmac,
..
}
)
}
}
Expand Down Expand Up @@ -251,15 +254,15 @@ impl Aead {
matches!(
self,
Aead::AeadWithDefaultLengthTag(AeadWithDefaultLengthTag::Ccm)
| Aead::AeadWithDefaultLengthTag(AeadWithDefaultLengthTag::Gcm)
| Aead::AeadWithShortenedTag {
aead_alg: AeadWithDefaultLengthTag::Ccm,
..
}
| Aead::AeadWithShortenedTag {
aead_alg: AeadWithDefaultLengthTag::Gcm,
..
}
| Aead::AeadWithDefaultLengthTag(AeadWithDefaultLengthTag::Gcm)
| Aead::AeadWithShortenedTag {
aead_alg: AeadWithDefaultLengthTag::Ccm,
..
}
| Aead::AeadWithShortenedTag {
aead_alg: AeadWithDefaultLengthTag::Gcm,
..
}
)
}

Expand All @@ -268,10 +271,10 @@ impl Aead {
matches!(
self,
Aead::AeadWithDefaultLengthTag(AeadWithDefaultLengthTag::Chacha20Poly1305)
| Aead::AeadWithShortenedTag {
aead_alg: AeadWithDefaultLengthTag::Chacha20Poly1305,
..
}
| Aead::AeadWithShortenedTag {
aead_alg: AeadWithDefaultLengthTag::Chacha20Poly1305,
..
}
)
}
}
Expand Down Expand Up @@ -406,8 +409,8 @@ impl AsymmetricSignature {
matches!(
self,
AsymmetricSignature::RsaPkcs1v15Sign { .. }
| AsymmetricSignature::RsaPkcs1v15SignRaw
| AsymmetricSignature::RsaPss { .. }
| AsymmetricSignature::RsaPkcs1v15SignRaw
| AsymmetricSignature::RsaPss { .. }
)
}

Expand All @@ -416,8 +419,8 @@ impl AsymmetricSignature {
matches!(
self,
AsymmetricSignature::Ecdsa { .. }
| AsymmetricSignature::EcdsaAny
| AsymmetricSignature::DeterministicEcdsa { .. }
| AsymmetricSignature::EcdsaAny
| AsymmetricSignature::DeterministicEcdsa { .. }
)
}

Expand Down
66 changes: 59 additions & 7 deletions psa-crypto/src/types/key.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ use crate::types::status::Status;
use crate::types::status::{Error, Result};
#[cfg(feature = "interface")]
use core::convert::{TryFrom, TryInto};
use core::fmt;
use log::error;
pub use psa_crypto_sys::{self, psa_key_id_t, PSA_KEY_ID_USER_MAX, PSA_KEY_ID_USER_MIN};
use serde::{Deserialize, Serialize};
Expand Down Expand Up @@ -281,10 +282,10 @@ impl Attributes {
matches!(
alg,
Algorithm::KeyAgreement(KeyAgreement::Raw(RawKeyAgreement::Ffdh))
| Algorithm::KeyAgreement(KeyAgreement::WithKeyDerivation {
ka_alg: RawKeyAgreement::Ffdh,
..
})
| Algorithm::KeyAgreement(KeyAgreement::WithKeyDerivation {
ka_alg: RawKeyAgreement::Ffdh,
..
})
)
}
}
Expand Down Expand Up @@ -541,10 +542,37 @@ pub enum Type {
},
}

impl fmt::Display for Type {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Type::RawData => write!(f, "Raw data"),
Type::Hmac => write!(f, "HMAC key"),
Type::Derive => write!(f, "Derivation key"),
Type::Aes => write!(f, "Key for an algorithm based on AES"),
Type::Des => write!(f, "Key for an algorithm based on DES or 3DES"),
Type::Camellia => write!(f, "Key for an algorithm based on Camellia"),
Type::Arc4 => write!(f, "Key for the RC4 stream cipher"),
Type::Chacha20 => write!(f, "Key for an algorithm based on ChaCha20"),
Type::RsaPublicKey => write!(f, "RSA public key"),
Type::RsaKeyPair => write!(f, "RSA key pair"),
Type::EccKeyPair { curve_family } => write!(f, "ECC key pair (using {})", curve_family),
Type::EccPublicKey { curve_family } => {
write!(f, "ECC public key (using {})", curve_family)
}
Type::DhKeyPair { group_family } => {
write!(f, "Diffie-Hellman key pair (using {})", group_family)
}
Type::DhPublicKey { group_family } => {
write!(f, "Diffie-Hellman public key (using {})", group_family)
}
}
}
}

impl Type {
/// Checks if a key type is ECC key pair with any curve family inside.
pub fn is_ecc_key_pair(self) -> bool {
matches!( self, Type::EccKeyPair { .. })
matches!(self, Type::EccKeyPair { .. })
}

/// Checks if a key type is ECC public key with any curve family inside.
Expand All @@ -562,12 +590,12 @@ impl Type {

/// Checks if a key type is DH public key with any group family inside.
pub fn is_dh_public_key(self) -> bool {
matches!( self, Type::DhPublicKey { .. } )
matches!(self, Type::DhPublicKey { .. })
}

/// Checks if a key type is DH key pair with any group family inside.
pub fn is_dh_key_pair(self) -> bool {
matches!( self, Type::DhKeyPair { .. } )
matches!(self, Type::DhKeyPair { .. })
}

/// If key is public or key pair, returns the corresponding public key type.
Expand Down Expand Up @@ -659,6 +687,22 @@ pub enum EccFamily {
Montgomery,
}

impl fmt::Display for EccFamily {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
EccFamily::SecpK1 => write!(f, "SEC Koblitz curves over prime fields"),
EccFamily::SecpR1 => write!(f, "SEC random curves over prime fields"),
EccFamily::SecpR2 => write!(f, "SEC additional random curves over prime fields"),
EccFamily::SectK1 => write!(f, "SEC Koblitz curves over binary fields"),
EccFamily::SectR1 => write!(f, "SEC random curves over binary fields"),
EccFamily::SectR2 => write!(f, "SEC additional random curves over binary fields"),
EccFamily::BrainpoolPR1 => write!(f, "Brainpool P random curves"),
EccFamily::Frp => write!(f, "FRP curve"),
EccFamily::Montgomery => write!(f, "Montgomery curve"),
}
}
}

/// Enumeration of Diffie Hellman group families supported.
#[derive(Copy, Clone, Debug, PartialEq, Serialize, Deserialize, Zeroize)]
pub enum DhFamily {
Expand All @@ -668,6 +712,14 @@ pub enum DhFamily {
Rfc7919,
}

impl fmt::Display for DhFamily {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
DhFamily::Rfc7919 => write!(f, "Diffie-Hellman groups defined in RFC 7919 Appendix A"),
}
}
}

/// Definition of the key policy, what is permitted to do with the key.
#[derive(Copy, Clone, Debug, PartialEq, Serialize, Deserialize, Zeroize)]
pub struct Policy {
Expand Down

0 comments on commit 9fbd3ad

Please sign in to comment.