Skip to content

Commit

Permalink
refactoring ae and encrypted_header
Browse files Browse the repository at this point in the history
  • Loading branch information
Adam Khayam authored and Adam Khayam committed May 6, 2024
1 parent 0f00011 commit 7eb2639
Show file tree
Hide file tree
Showing 8 changed files with 22 additions and 161 deletions.
2 changes: 1 addition & 1 deletion examples/decrypt.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use cosmian_cover_crypt::api::EncryptedHeader;
use cosmian_cover_crypt::core::EncryptedHeader;

const USK: &str = "AubJg6rkTo7EjT2A7jswv5tq2uR5kZflMxbqogOl+WYNWUDwr8yvmgGSe7D6kHLYHHjW78VWtfV3kjRUrT3gRAsMAAEAnzQygadC4nJKHl4nP9VkHqU/62dVM4NVCkNlmFSBMgMCAQkBAPRl3kM+kOijMKDR0OjOWq2h0N+MhQzdi/uRUwKTi08HAgMJAQCbcxAJ960xi+CDtCeg/l7uux1a/DFzPUOFk94Apdt4CwIECQEAdt+vYI9Hga7eEgBhLTi97eDgp7NGCZV0JTrvKdxJlAMCBQkBAU2GnUJtqBUZ6rRtbdP6gvC5KmOjgMKk1V8p14iiL18E8lwJjdmrcweORogGSlVUZ4OW9IM+IzRJaLqfz0VMGsItYRpkLHQVmslsJxrMs0mzFWt0nsfD6bRzhlFSyWdByEOr1nCJnhClpJWAhAZSUxJe4vOlWlNJOKQDAWKA/4K6vsxRfBachXQ/9GeXbxAValix03xgLdwpszZPM/SshSKgxVIGvojFmNEU5KERtXEw9RVxXWImMVRCuMoMy4MIaRw9tSkczirJSOl9F9WT8jK8OfGSiDdbY9UFmrRijMUIw2QLeWquYtUHyCo3qwd+aTy/yFhgbhEd4vqKttk8XUIAjSuyNSGiJ7tDsNBwJjopdeOdWslOk5pccaYWSfuGo4UHomg1MvA+G5Oc0kqOzegtIAk1DdRGv1tEG1RW8YSGD7WdIyDBo0IAlhBAdRwEjwMmvrg7S5FwFlyVtoKTd9F8AFK3TKep0iO8RwJ9tXci5isYdGlCd6wasDAdEPS87PZYXWxXuLSG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nrKQYgOn+rfS+TA5zKAhwQNLF0IgfYPDi0mZTMDdL3z5A7v0T1xSsaNkEQs0aDPXWbfKoqp36VU8FLUyqYsel7Qd0qyBO2ZLn8Zu5Dbjr5ifCkXkvatr7ZC3eRTY6VwuNanwSBVQPzOnNjIiWrUgdxRadwnifliecZSYXaBrxKrogZpqvbuH5xGqTzIKbXeWOGnHWLXaDAk80cEvNAqSD2UNpJCaDii2EGgw6xGl+zm57lU07nDQqcrlMYxd2TJ/PZapIWSw3cAdtwbltwWiE8XAYbDEucjlaMrXOEhw0KF5TsuqjnKnqQYmS6e4azxlpoPstqpriUVAhZlullTeFppjxqrCwXovJBjBMintjoPRR1HjDoLAz2RmU8X+/5wHp6YBe4Q1XgEEK4ZPVkbHsmOiumLU/oU8XhNUy5bEcGHvCxtG4WTqqQuEI2nASyGxoHyxAkde9LpoZGLvXMYNKysjS3Bvbcv5zWEDQ5CptrlaQGRnWhh6qoreyWObpgkW3LVIXBM9MEj+Uasb7gEmnkXi4nMUrSBiyGyxIjhooVXHjqpGPVvkVBN4kRT2/Glc4giq9onItwnsZGxWzAXtCVmEfGdPjAMFFXQaE4d9kDqhN7ASkbSzuryn6aYuc0LiCMj2VSzqeXtGoFaD48fhQiiiTlEjgwNnDZvmYzU+dMfdmwBN9RAzhGjurEUaVXBsKjpYn8i8hIZf9ZE/LovkFKwsJWae7SqKFjvKcBgiXgedojpJTahFj4TktgKS4GWL8ZMAbCGe5EH0tGcGwbZftOpr+CzWAXfIwnJy/KLcC2KSg/2ns1NTLhsNGD9c6f";

Expand Down
3 changes: 2 additions & 1 deletion examples/encrypt.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use cosmian_cover_crypt::{
abe_policy::{AccessPolicy, Policy},
api::{Covercrypt, EncryptedHeader},
api::Covercrypt,
core::EncryptedHeader,
test_utils::policy,
MasterPublicKey, MasterSecretKey,
};
Expand Down
3 changes: 2 additions & 1 deletion examples/runme.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@

use cosmian_cover_crypt::{
abe_policy::{AccessPolicy, DimensionBuilder, EncryptionHint, Policy},
api::{Covercrypt, EncryptedHeader},
api::Covercrypt,
core::EncryptedHeader,
};

fn main() {
Expand Down
160 changes: 9 additions & 151 deletions src/core/api.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
use std::{collections::HashMap, sync::Mutex};

use cosmian_crypto_core::{
kdf256,
reexport::rand_core::{CryptoRngCore, SeedableRng},
Aes256Gcm, CsRng, Dem, FixedSizeCBytes, Instantiable, Nonce, RandomFixedSizeCBytes, Secret,
SymmetricKey,
use std::{
collections::HashMap,
sync::{Mutex, MutexGuard},
};

use cosmian_crypto_core::{kdf256, reexport::rand_core::SeedableRng, CsRng, Secret, SymmetricKey};

use super::{
ae::AE,
primitives::{mpk_keygen, prune, update_coordinate_keys, usk_keygen},
MIN_TRACING_LEVEL,
};
Expand Down Expand Up @@ -40,6 +39,9 @@ impl PartialEq for Covercrypt {
}

impl Covercrypt {
pub fn rng(&self) -> MutexGuard<CsRng> {
self.rng.lock().expect("poisoned mutex")
}
/// Sets up the Covercrypt scheme.
///
/// Generates a MSK and a MPK with a tracing level of
Expand Down Expand Up @@ -173,150 +175,6 @@ impl Covercrypt {
}
}

/// Authenticated Encryption trait
pub trait AE<const KEY_LENGTH: usize> {
/// Encrypts the given plaintext `ptx` using the given `key`.
fn encrypt(
key: &SymmetricKey<KEY_LENGTH>,
ptx: &[u8],
rng: &mut impl CryptoRngCore,
) -> Result<Vec<u8>, Error>;

/// Decrypts the given ciphertext `ctx` using the given `key`.
///
/// # Error
///
/// Returns an error if the integrity of the ciphertext could not be verified.
fn decrypt(key: &SymmetricKey<KEY_LENGTH>, ctx: &[u8]) -> Result<Vec<u8>, Error>;
}

impl AE<{ Self::KEY_LENGTH }> for Aes256Gcm {
fn encrypt(
key: &SymmetricKey<{ Self::KEY_LENGTH }>,
ptx: &[u8],
rng: &mut impl CryptoRngCore,
) -> Result<Vec<u8>, Error> {
let nonce = Nonce::<{ Self::NONCE_LENGTH }>::new(&mut *rng);
let ciphertext = Self::new(key).encrypt(&nonce, ptx, None)?;
Ok([nonce.as_bytes(), &ciphertext].concat())
}

fn decrypt(key: &SymmetricKey<{ Self::KEY_LENGTH }>, ctx: &[u8]) -> Result<Vec<u8>, Error> {
if ctx.len() < Self::NONCE_LENGTH {
return Err(Error::CryptoCoreError(
cosmian_crypto_core::CryptoCoreError::DecryptionError,
));
}
let nonce = Nonce::try_from_slice(&ctx[..Self::NONCE_LENGTH])?;
Self::new(key)
.decrypt(&nonce, &ctx[Self::NONCE_LENGTH..], None)
.map_err(Error::CryptoCoreError)
}
}

/// Encrypted header holding a `Covercrypt` encapsulation of a 256-byte seed, and metadata
/// encrypted under the scheme AES256Gcm using a key derived from the encapsulated seed.
#[derive(Debug, PartialEq, Eq)]
pub struct EncryptedHeader {
pub encapsulation: Encapsulation,
pub encrypted_metadata: Option<Vec<u8>>,
}

impl EncryptedHeader {
/// Generates an encrypted header for a random seed and the given metadata.
/// Returns the encrypted header along with the encapsulated seed.
///
/// - `cover_crypt` : `Covercrypt` object
/// - `policy` : global policy
/// - `public_key` : `Covercrypt` public key
/// - `encryption_policy` : access policy used for the encapsulation
/// - `header_metadata` : additional data symmetrically encrypted in the
/// header
/// - `authentication_data` : authentication data used in the DEM encryption
pub fn generate(
cover_crypt: &Covercrypt,
policy: &Policy,
public_key: &MasterPublicKey,
encryption_policy: &AccessPolicy,
metadata: Option<&[u8]>,
authentication_data: Option<&[u8]>,
) -> Result<(Secret<SEED_LENGTH>, Self), Error> {
let (seed, encapsulation) = cover_crypt.encaps(public_key, policy, encryption_policy)?;

let encrypted_metadata = metadata
.map(|bytes| {
let mut key = SymmetricKey::<{ Aes256Gcm::KEY_LENGTH }>::default();
kdf256!(&mut key, &seed, &[0u8]);
let mut rng = cover_crypt.rng.lock().expect("poisoned lock");
let nonce = Nonce::<{ Aes256Gcm::NONCE_LENGTH }>::new(&mut *rng);
let aes = Aes256Gcm::new(&key);
aes.encrypt(&nonce, bytes, authentication_data)
})
.transpose()?;

// Generating a new seed adding a variant component 1, to prevent reusing
// seed used for the metadata encryption.
let mut new_seed = Secret::<SEED_LENGTH>::default();
kdf256!(&mut new_seed, &seed, &[1u8]);

Ok((
new_seed,
Self {
encapsulation,
encrypted_metadata,
},
))
}

/// Decrypts the header with the given user secret key.
///
/// - `cover_crypt` : `Covercrypt` object
/// - `usk` : `Covercrypt` user secret key
/// - `authentication_data` : authentication data used in the DEM encryption
pub fn decrypt(
&self,
cover_crypt: &Covercrypt,
usk: &UserSecretKey,
authentication_data: Option<&[u8]>,
) -> Result<Option<CleartextHeader>, Error> {
cover_crypt
.decaps(usk, &self.encapsulation)?
.map(|seed| {
let metadata = self
.encrypted_metadata
.as_ref()
.map(|ctx| {
let mut key = SymmetricKey::<{ Aes256Gcm::KEY_LENGTH }>::default();
kdf256!(&mut key, &seed, &[0u8]);
let mut rng = cover_crypt.rng.lock().expect("poisoned lock");
let nonce = Nonce::<{ Aes256Gcm::NONCE_LENGTH }>::new(&mut *rng);
let aes = Aes256Gcm::new(&key);
aes.decrypt(&nonce, ctx, authentication_data)
})
.transpose()?;

let mut new_seed = Secret::<SEED_LENGTH>::default();
kdf256!(&mut new_seed, &seed, &[1u8]);

Ok(CleartextHeader {
seed: new_seed,
metadata,
})
})
.transpose()
}
}

/// Structure containing all data encrypted in an `EncryptedHeader`.
///
/// - `symmetric_key` : DEM key
/// - `metadata` : additional data symmetrically encrypted in a header
#[derive(Debug, PartialEq, Eq)]
pub struct CleartextHeader {
pub seed: Secret<SEED_LENGTH>,
pub metadata: Option<Vec<u8>>,
}

pub trait CovercryptKEM {
/// Generates an encapsulation for the given access
/// policy.
Expand Down
1 change: 1 addition & 0 deletions src/core/macros.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ pub use tiny_keccak::{Hasher, Shake, Xof};
/// # Parameters
///
/// - `bytes` : input bytes
#[macro_export]
macro_rules! eakem_hash {
($TAG_LENGTH: ident, $KEY_LENGTH: ident, $($bytes: expr),+) => {
{
Expand Down
4 changes: 3 additions & 1 deletion src/core/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,9 @@ use crate::{

#[macro_use]
pub mod macros;

pub mod ae;
pub mod api;
mod encrypted_header;
pub mod primitives;
#[cfg(feature = "serialization")]
pub mod serialization;
Expand All @@ -25,6 +26,7 @@ mod postquantum;
mod tests;

use elgamal::{EcPoint, Scalar};
pub use encrypted_header::{CleartextHeader, EncryptedHeader};

/// The length of the secret encapsulated by Covercrypt.
///
Expand Down
7 changes: 2 additions & 5 deletions src/core/serialization/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,16 +16,13 @@ use super::{
use crate::{
abe_policy::Coordinate,
core::{
Encapsulation, MasterPublicKey, MasterSecretKey, SeedEncapsulation, UserSecretKey,
SEED_LENGTH,
CleartextHeader, Encapsulation, EncryptedHeader, MasterPublicKey, MasterSecretKey,
SeedEncapsulation, UserSecretKey, SEED_LENGTH,
},
data_struct::{RevisionMap, RevisionVec},
Error,
};

use crate::api::CleartextHeader;
use crate::api::EncryptedHeader;

impl Serializable for TracingPublicKey {
type Error = Error;

Expand Down
3 changes: 2 additions & 1 deletion src/test_utils/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,8 @@ mod tests {
use super::*;
use crate::{
abe_policy::{AccessPolicy, Attribute, LegacyPolicy},
api::{Covercrypt, CovercryptKEM, EncryptedHeader},
api::{Covercrypt, CovercryptKEM},
core::EncryptedHeader,
};

#[test]
Expand Down

0 comments on commit 7eb2639

Please sign in to comment.