Skip to content

Commit

Permalink
add kem key gen
Browse files Browse the repository at this point in the history
  • Loading branch information
supinie committed May 14, 2024
1 parent 826d064 commit 0dbaea0
Show file tree
Hide file tree
Showing 3 changed files with 50 additions and 6 deletions.
5 changes: 2 additions & 3 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,11 @@ license = "GPL-3.0-or-later"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
# arrayvec = { version = "0.7.4", default-features = false, features = ["zeroize"] }
byteorder = "1.4.3"
# clap = { version = "4.3.12", features = ["cargo"] }
more-asserts = "0.3.1"
num_enum = { version = "0.7.1", default-features = false }
rand_core = { version = "0.6.4", default-features = false }
rand_chacha = { version = "0.3.1", default-features = false }
rand_core = { version = "0.6.4", features = ["getrandom"] }
sha3 = "0.10.8"
tinyvec = "1.6.0"
zeroize = { version = "1.7.0", default-features = false }
Expand Down
9 changes: 9 additions & 0 deletions src/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ pub enum CrystalsError {
IncorrectBufferLength(usize, usize),
InvalidSeedLength(usize, usize),
InternalError(),
InvalidK(usize),
}

impl Display for CrystalsError {
Expand All @@ -21,6 +22,7 @@ impl Display for CrystalsError {
Self::IncorrectBufferLength(buf_len, expected_buf_len) => write!(f, "Incorrect buffer length for (un)packing. Expected buffer length {expected_buf_len}, got length {buf_len}"),
Self::InvalidSeedLength(seed_len, expected_seed_len) => write!(f, "Invalid seed length, expected {expected_seed_len}, got {seed_len}"),
Self::InternalError() => write!(f, "Unexpected internal error"),
Self::InvalidK(k) => write!(f, "Recieved invalid k value, {k}, expected 2, 3, or 4"),
}
}
}
Expand Down Expand Up @@ -62,6 +64,7 @@ pub enum KeyGenerationError {
Crystals(CrystalsError),
TryFromSlice(TryFromSliceError),
Packing(PackingError),
Rand(rand_core::Error),
}

impl From<CrystalsError> for KeyGenerationError {
Expand All @@ -82,6 +85,12 @@ impl From<PackingError> for KeyGenerationError {
}
}

impl From<rand_core::Error> for KeyGenerationError {
fn from(error: rand_core::Error) -> Self {
Self::Rand(error)
}
}

#[derive(Debug)]
pub enum EncryptionDecryptionError {
Crystals(CrystalsError),
Expand Down
42 changes: 39 additions & 3 deletions src/kem.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
use crate::{
errors::{CrystalsError, KeyGenerationError},
indcpa::{generate_indcpa_key_pair, PrivateKey as IndcpaPrivateKey, PublicKey as IndcpaPublicKey},
params::{SecurityLevel, SYMBYTES}
params::{SecurityLevel, SYMBYTES, K}
};
use sha3::{Digest, Sha3_256};
use rand_core::{CryptoRng, RngCore, SeedableRng};
use rand_chacha::ChaCha20Rng;

pub struct PrivateKey {
sk: IndcpaPrivateKey,
Expand Down Expand Up @@ -36,7 +38,41 @@ fn new_key_from_seed(seed: &[u8], sec_level: SecurityLevel) -> Result<(PublicKey
let h_pk: [u8; SYMBYTES] = hash.finalize().into();

Ok((
PublicKey { pk: pk.clone(), h_pk },
PrivateKey { sk, pk: pk.clone(), h_pk, z }
PublicKey { pk, h_pk },
PrivateKey { sk, pk, h_pk, z }
))
}

/// Generates a new keypair for a given security level.
/// Takes either a given RNG, or will generate one using `ChaCha20`
/// # Errors
/// Will return a `KeyGenerationError` if:
/// - Given invalid K value
/// - RNG fails
/// Example:
/// ```
/// let (pk, sk) = generate_key_pair(None, 3)?;
/// ```
pub fn generate_key_pair<R: RngCore + CryptoRng>(rng: Option<&mut R>, k: usize) -> Result<(PublicKey, PrivateKey), KeyGenerationError> {
let k_result = K::try_from(k);

if let Ok(k_value) = k_result {
let mut seed = [0u8; 2 * SYMBYTES];

if let Some(rng) = rng {
rng.try_fill_bytes(&mut seed)?;
} else {
let mut chacha = ChaCha20Rng::from_entropy();
chacha.try_fill_bytes(&mut seed)?;
};

let sec_level = SecurityLevel::new(k_value);

return new_key_from_seed(&seed, sec_level);
}

Err(CrystalsError::InvalidK(k).into())
}



0 comments on commit 0dbaea0

Please sign in to comment.