Skip to content

Commit

Permalink
[refactor]: revert rename
Browse files Browse the repository at this point in the history
Signed-off-by: Dmitry Balashov <43530070+0x009922@users.noreply.github.com>
  • Loading branch information
0x009922 committed Mar 7, 2024
1 parent 70a553c commit 24a28fc
Show file tree
Hide file tree
Showing 11 changed files with 100 additions and 103 deletions.
10 changes: 5 additions & 5 deletions crypto/src/kex/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ use alloc::vec::Vec;

pub use x25519::X25519Sha256;

use crate::{error::ParseError, KeyPairGenOption, SessionKey};
use crate::{error::ParseError, KeyGenOption, SessionKey};

/// A Generic trait for key exchange schemes. Each scheme provides a way to generate keys and
/// do a diffie-hellman computation
Expand All @@ -24,14 +24,14 @@ pub trait KeyExchangeScheme {
fn new() -> Self;

/// Create new keypairs. If
/// - `options` is [`Random`](KeyPairGenOption::Random), the keys are generated ephemerally from the [`OsRng`](rand::rngs::OsRng)
/// - `options` is [`UseSeed`](KeyPairGenOption::UseSeed), the keys are generated ephemerally from the sha256 hash of the seed which is
/// - `options` is [`Random`](KeyGenOption::Random), the keys are generated ephemerally from the [`OsRng`](rand::rngs::OsRng)
/// - `options` is [`UseSeed`](KeyGenOption::UseSeed), the keys are generated ephemerally from the sha256 hash of the seed which is
/// then used to seed the [`ChaChaRng`](rand_chacha::ChaChaRng)
/// - `options` is [`FromPrivateKey`](KeyPairGenOption::FromPrivateKey), the corresponding public key is returned. This should be used for
/// - `options` is [`FromPrivateKey`](KeyGenOption::FromPrivateKey), the corresponding public key is returned. This should be used for
/// static Diffie-Hellman and loading a long-term key.
fn keypair(
&self,
options: KeyPairGenOption<Self::PrivateKey>,
options: KeyGenOption<Self::PrivateKey>,
) -> (Self::PublicKey, Self::PrivateKey);

/// Compute the diffie-hellman shared secret.
Expand Down
17 changes: 8 additions & 9 deletions crypto/src/kex/x25519.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ use x25519_dalek::{PublicKey, StaticSecret};
use zeroize::Zeroize;

use super::KeyExchangeScheme;
use crate::{error::ParseError, KeyPairGenOption, SessionKey};
use crate::{error::ParseError, KeyGenOption, SessionKey};

/// Implements the [`KeyExchangeScheme`] using X25519 key exchange and SHA256 hash function.
#[derive(Copy, Clone)]
Expand All @@ -28,25 +28,25 @@ impl KeyExchangeScheme for X25519Sha256 {

fn keypair(
&self,
mut option: KeyPairGenOption<Self::PrivateKey>,
mut option: KeyGenOption<Self::PrivateKey>,
) -> (Self::PublicKey, Self::PrivateKey) {
match option {
#[cfg(feature = "rand")]
KeyPairGenOption::Random => {
KeyGenOption::Random => {
let rng = OsRng;
let sk = StaticSecret::random_from_rng(rng);
let pk = PublicKey::from(&sk);
(pk, sk)
}
KeyPairGenOption::UseSeed(ref mut s) => {
KeyGenOption::UseSeed(ref mut s) => {
let hash = sha2::Sha256::digest(s.as_slice());
s.zeroize();
let rng = ChaChaRng::from_seed(*array_ref!(hash.as_slice(), 0, 32));
let sk = StaticSecret::random_from_rng(rng);
let pk = PublicKey::from(&sk);
(pk, sk)
}
KeyPairGenOption::FromPrivateKey(ref sk) => {
KeyGenOption::FromPrivateKey(ref sk) => {
let pk = PublicKey::from(sk);
(pk, sk.clone())
}
Expand Down Expand Up @@ -91,15 +91,14 @@ mod tests {
#[test]
fn key_exchange() {
let scheme = X25519Sha256::new();
let (public_key1, secret_key1) = scheme.keypair(KeyPairGenOption::Random);
let (public_key1, secret_key1) = scheme.keypair(KeyGenOption::Random);

let (public_key2, secret_key2) = scheme.keypair(KeyPairGenOption::Random);
let (public_key2, secret_key2) = scheme.keypair(KeyGenOption::Random);
let shared_secret1 = scheme.compute_shared_secret(&secret_key2, &public_key1);
let shared_secret2 = scheme.compute_shared_secret(&secret_key1, &public_key2);
assert_eq!(shared_secret1.payload(), shared_secret2.payload());

let (public_key2, _secret_key1) =
scheme.keypair(KeyPairGenOption::FromPrivateKey(secret_key1));
let (public_key2, _secret_key1) = scheme.keypair(KeyGenOption::FromPrivateKey(secret_key1));
assert_eq!(public_key2, public_key1);
}
}
80 changes: 40 additions & 40 deletions crypto/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -111,24 +111,11 @@ impl FromStr for Algorithm {
}
}

/// Needed since it couldn't be represented in FFI
#[derive(Clone)]
#[cfg_attr(not(feature = "ffi_import"), derive(Debug))]
enum KeyPairGenConfigInner {
/// Use random number generator
#[cfg(feature = "rand")]
Random { algorithm: Algorithm },
/// Use seed
UseSeed { seed: Vec<u8>, algorithm: Algorithm },
/// Derive from a private key
FromPrivateKey(PrivateKey),
}

/// While [`KeyPairGenConfig`] is for external users, this structure is for internal use
/// While [`KeyGenConfig`] is for external users, this structure is for internal use
/// to pass it to a specific algorithm.
/// Parameter `K` is intended to be set as a `PrivateKey` type of that specific algorithm.
/// Parameter `K` is intended to be set as a private key type of that specific algorithm.
#[derive(Debug)]
pub enum KeyPairGenOption<K> {
pub enum KeyGenOption<K> {
/// Use random number generator
#[cfg(feature = "rand")]
Random,
Expand All @@ -142,35 +129,48 @@ ffi::ffi_item! {
/// Configuration for key generation
#[derive(Clone)]
#[cfg_attr(not(feature = "ffi_import"), derive(Debug))]
pub struct KeyPairGenConfig{
inner: KeyPairGenConfigInner
pub struct KeyGenConfig{
inner: KeyGenConfigInner
}
}

/// Needed since it couldn't be represented in FFI
#[derive(Clone)]
#[cfg_attr(not(feature = "ffi_import"), derive(Debug))]
enum KeyGenConfigInner {
/// Use random number generator
#[cfg(feature = "rand")]
Random { algorithm: Algorithm },
/// Use seed
UseSeed { seed: Vec<u8>, algorithm: Algorithm },
/// Derive from a private key
FromPrivateKey(PrivateKey),
}

#[ffi_impl_opaque]
impl KeyPairGenConfig {
impl KeyGenConfig {
/// Generate using random number generation with a specified algorithm
#[cfg(feature = "rand")]
#[must_use]
pub fn from_random(algorithm: Algorithm) -> Self {
Self {
inner: KeyPairGenConfigInner::Random { algorithm },
inner: KeyGenConfigInner::Random { algorithm },
}
}

/// Construct using a seed with a specified algorithm
#[must_use]
pub fn from_seed(seed: Vec<u8>, algorithm: Algorithm) -> Self {
Self {
inner: KeyPairGenConfigInner::UseSeed { seed, algorithm },
inner: KeyGenConfigInner::UseSeed { seed, algorithm },
}
}

/// Construct the pair from a private key. Infers the algorithm from the key's one.
#[must_use]
pub fn from_private_key(key: PrivateKey) -> Self {
Self {
inner: KeyPairGenConfigInner::FromPrivateKey(key),
inner: KeyGenConfigInner::FromPrivateKey(key),
}
}

Expand Down Expand Up @@ -198,7 +198,7 @@ impl KeyPair {
/// Generates a random key pair using [`Algorithm::default()`]
#[cfg(feature = "rand")]
pub fn generate() -> Self {
Self::generate_with_config(KeyPairGenConfig::from_random(Algorithm::default()))
Self::generate_with_config(KeyGenConfig::from_random(Algorithm::default()))
}
}

Expand Down Expand Up @@ -230,29 +230,29 @@ impl KeyPair {
})
}

/// Generates a pair of Public and Private key with the corresponding [`KeyPairGenOption`].
pub fn generate_with_config(config: KeyPairGenConfig) -> Self {
use KeyPairGenConfigInner;
use KeyPairGenOption;
/// Generates a pair of Public and Private key with the corresponding [`KeyGenOption`].
pub fn generate_with_config(config: KeyGenConfig) -> Self {
use KeyGenConfigInner;
use KeyGenOption;

macro_rules! with_algorithm_variations {
($(($alg:ident, $alg_mod:path)),+) => {
match config.inner {
#[cfg(feature = "rand")]
KeyPairGenConfigInner::Random { algorithm } => {
KeyGenConfigInner::Random { algorithm } => {
match algorithm {
$(Algorithm::$alg => <$alg_mod>::keypair(KeyPairGenOption::Random).into()),*
$(Algorithm::$alg => <$alg_mod>::keypair(KeyGenOption::Random).into()),*
}
},
KeyPairGenConfigInner::UseSeed { seed, algorithm } => {
}
KeyGenConfigInner::UseSeed { seed, algorithm } => {
match algorithm {
$(Algorithm::$alg => <$alg_mod>::keypair(KeyPairGenOption::UseSeed(seed)).into()),*
$(Algorithm::$alg => <$alg_mod>::keypair(KeyGenOption::UseSeed(seed)).into()),*
}
}
KeyPairGenConfigInner::FromPrivateKey(key) => {
KeyGenConfigInner::FromPrivateKey(key) => {
match *key.0 {
$(
PrivateKeyInner::$alg(secret) => <$alg_mod>::keypair(KeyPairGenOption::FromPrivateKey(secret)).into(),
PrivateKeyInner::$alg(secret) => <$alg_mod>::keypair(KeyGenOption::FromPrivateKey(secret)).into(),
)*
}
}
Expand Down Expand Up @@ -595,7 +595,7 @@ impl From<PrivateKey> for PublicKey {
match $private_inner {
$(
PrivateKeyInner::$alg(secret) => {
PublicKeyInner::$alg(<$alg_mod>::keypair(KeyPairGenOption::FromPrivateKey(secret)).0)
PublicKeyInner::$alg(<$alg_mod>::keypair(KeyGenOption::FromPrivateKey(secret)).0)
}
)*
}
Expand Down Expand Up @@ -865,7 +865,7 @@ mod ffi {

#[cfg(any(feature = "ffi_export", feature = "ffi_import"))]
iroha_ffi::handles! {
KeyPairGenConfig,
KeyGenConfig,
PublicKey,
PrivateKey,
KeyPair,
Expand All @@ -876,8 +876,8 @@ mod ffi {
iroha_ffi::decl_ffi_fns! { link_prefix="iroha_crypto" Drop, Clone, Eq, Ord, Default }
#[cfg(all(feature = "ffi_export", not(feature = "ffi_import")))]
iroha_ffi::def_ffi_fns! { link_prefix="iroha_crypto"
Drop: { KeyPairGenConfig, PublicKey, PrivateKey, KeyPair, Signature },
Clone: { KeyPairGenConfig, PublicKey, PrivateKey, KeyPair, Signature },
Drop: { KeyGenConfig, PublicKey, PrivateKey, KeyPair, Signature },
Clone: { KeyGenConfig, PublicKey, PrivateKey, KeyPair, Signature },
Eq: { PublicKey, PrivateKey, KeyPair, Signature },
Ord: { PublicKey, Signature },
}
Expand Down Expand Up @@ -937,7 +937,7 @@ mod tests {
Algorithm::BlsNormal,
Algorithm::BlsSmall,
] {
let key_pair = KeyPairGenConfig::from_random(algorithm).generate();
let key_pair = KeyGenConfig::from_random(algorithm).generate();

assert_eq!(
key_pair,
Expand Down Expand Up @@ -996,7 +996,7 @@ mod tests {
Algorithm::BlsNormal,
Algorithm::BlsSmall,
] {
let key_pair = KeyPairGenConfig::from_random(algorithm).generate();
let key_pair = KeyGenConfig::from_random(algorithm).generate();
let (public_key, _) = key_pair.into();

let encoded_public_key = public_key.encode();
Expand Down
10 changes: 5 additions & 5 deletions crypto/src/signature/bls/implementation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ use zeroize::Zeroize as _;

pub(super) const MESSAGE_CONTEXT: &[u8; 20] = b"for signing messages";

use crate::{Algorithm, Error, KeyPairGenOption, ParseError};
use crate::{Algorithm, Error, KeyGenOption, ParseError};

pub trait BlsConfiguration {
const ALGORITHM: Algorithm;
Expand All @@ -25,13 +25,13 @@ impl<C: BlsConfiguration + ?Sized> BlsImpl<C> {
// the names are from an RFC, not a good idea to change them
#[allow(clippy::similar_names)]
pub fn keypair(
mut option: KeyPairGenOption<SecretKey<C::Engine>>,
mut option: KeyGenOption<SecretKey<C::Engine>>,
) -> (PublicKey<C::Engine>, SecretKey<C::Engine>) {
let private_key = match option {
#[cfg(feature = "rand")]
KeyPairGenOption::Random => SecretKey::generate(OsRng),
KeyGenOption::Random => SecretKey::generate(OsRng),
// Follows https://datatracker.ietf.org/doc/draft-irtf-cfrg-bls-signature/?include_text=1
KeyPairGenOption::UseSeed(ref mut seed) => {
KeyGenOption::UseSeed(ref mut seed) => {
let salt = b"BLS-SIG-KEYGEN-SALT-";
let info = [0u8, C::Engine::SECRET_KEY_SIZE.try_into().unwrap()]; // key_info || I2OSP(L, 2)
let mut ikm = vec![0u8; seed.len() + 1];
Expand All @@ -44,7 +44,7 @@ impl<C: BlsConfiguration + ?Sized> BlsImpl<C> {

SecretKey::<C::Engine>::from_seed(&okm)
}
KeyPairGenOption::FromPrivateKey(ref key) => key.clone(),
KeyGenOption::FromPrivateKey(ref key) => key.clone(),
};
(private_key.into_public(), private_key)
}
Expand Down
14 changes: 7 additions & 7 deletions crypto/src/signature/bls/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,16 @@ use super::{
normal::NormalConfiguration,
small::SmallConfiguration,
};
use crate::KeyPairGenOption;
use crate::KeyGenOption;

const MESSAGE_1: &[u8; 22] = b"This is a test message";
const MESSAGE_2: &[u8; 20] = b"Another test message";
const SEED: &[u8; 10] = &[1u8; 10];

#[allow(clippy::similar_names)]
fn test_keypair_generation_from_seed<C: BlsConfiguration>() {
let (pk_1, sk_1) = BlsImpl::<C>::keypair(KeyPairGenOption::UseSeed(SEED.to_vec()));
let (pk_2, sk_2) = BlsImpl::<C>::keypair(KeyPairGenOption::UseSeed(SEED.to_vec()));
let (pk_1, sk_1) = BlsImpl::<C>::keypair(KeyGenOption::UseSeed(SEED.to_vec()));
let (pk_2, sk_2) = BlsImpl::<C>::keypair(KeyGenOption::UseSeed(SEED.to_vec()));

assert!(
(pk_1, sk_1.to_bytes()) == (pk_2, sk_2.to_bytes()),
Expand All @@ -23,15 +23,15 @@ fn test_keypair_generation_from_seed<C: BlsConfiguration>() {
}

fn test_signature_verification<C: BlsConfiguration>() {
let (pk, sk) = BlsImpl::<C>::keypair(KeyPairGenOption::Random);
let (pk, sk) = BlsImpl::<C>::keypair(KeyGenOption::Random);

let signature_1 = BlsImpl::<C>::sign(MESSAGE_1, &sk);
BlsImpl::<C>::verify(MESSAGE_1, &signature_1, &pk)
.expect("Signature verification should succeed");
}

fn test_signature_verification_different_messages<C: BlsConfiguration>() {
let (pk, sk) = BlsImpl::<C>::keypair(KeyPairGenOption::Random);
let (pk, sk) = BlsImpl::<C>::keypair(KeyGenOption::Random);

let signature = BlsImpl::<C>::sign(MESSAGE_1, &sk);
BlsImpl::<C>::verify(MESSAGE_2, &signature, &pk)
Expand All @@ -40,8 +40,8 @@ fn test_signature_verification_different_messages<C: BlsConfiguration>() {

#[allow(clippy::similar_names)]
fn test_signature_verification_different_keys<C: BlsConfiguration>() {
let (_pk_1, sk_1) = BlsImpl::<C>::keypair(KeyPairGenOption::Random);
let (pk_2, _sk_2) = BlsImpl::<C>::keypair(KeyPairGenOption::Random);
let (_pk_1, sk_1) = BlsImpl::<C>::keypair(KeyGenOption::Random);
let (pk_2, _sk_2) = BlsImpl::<C>::keypair(KeyGenOption::Random);

let signature = BlsImpl::<C>::sign(MESSAGE_1, &sk_1);
BlsImpl::<C>::verify(MESSAGE_1, &signature, &pk_2)
Expand Down
Loading

0 comments on commit 24a28fc

Please sign in to comment.