Skip to content

Commit

Permalink
fmt
Browse files Browse the repository at this point in the history
  • Loading branch information
supinie committed May 24, 2024
1 parent 0df9179 commit 32503aa
Show file tree
Hide file tree
Showing 5 changed files with 48 additions and 35 deletions.
13 changes: 5 additions & 8 deletions src/indcpa.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@ use crate::{
polynomials::{Montgomery, Normalised, Poly, Unreduced},
vectors::PolyVec,
};
use tinyvec::ArrayVec;
use sha3::{Digest, Sha3_512};
use tinyvec::ArrayVec;

#[derive(Clone, Copy, PartialEq, Debug, Eq)]
pub struct PrivateKey {
Expand Down Expand Up @@ -36,10 +36,7 @@ impl PrivateKey {
Ok(Self { secret })
}

pub fn decrypt(
&self,
ciphertext: &[u8],
) -> Result<[u8; SYMBYTES], EncryptionDecryptionError> {
pub fn decrypt(&self, ciphertext: &[u8]) -> Result<[u8; SYMBYTES], EncryptionDecryptionError> {
let sec_level = self.sec_level();
if ciphertext.len() == sec_level.indcpa_bytes() {
let (u_bytes, v_bytes) = ciphertext.split_at(sec_level.poly_vec_compressed_bytes());
Expand Down Expand Up @@ -107,9 +104,9 @@ impl PublicKey {

pub fn encrypt(
&self,
message: &[u8], // length SYMBYTES
seed: &[u8], // length SYMBYTES
ciphertext_bytes: &mut [u8] // length indcpa_bytes()
message: &[u8], // length SYMBYTES
seed: &[u8], // length SYMBYTES
ciphertext_bytes: &mut [u8], // length indcpa_bytes()
) -> Result<(), EncryptionDecryptionError> {
let sec_level = self.sec_level();
let k_value: usize = sec_level.k().into();
Expand Down
64 changes: 40 additions & 24 deletions src/kem.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,11 @@ use crate::{
};
use rand_chacha::ChaCha20Rng;
use rand_core::{CryptoRng, RngCore, SeedableRng};
use sha3::{Digest, Sha3_256, Sha3_512, Shake256, digest::{ExtendableOutput, Update, XofReader}};
use subtle::{ConstantTimeEq, ConditionallySelectable};
use sha3::{
digest::{ExtendableOutput, Update, XofReader},
Digest, Sha3_256, Sha3_512, Shake256,
};
use subtle::{ConditionallySelectable, ConstantTimeEq};
use tinyvec::ArrayVec;

#[derive(Debug, Eq, PartialEq)]
Expand Down Expand Up @@ -169,7 +172,7 @@ impl PrivateKey {
/// # Ok::<(), enc_rust::errors::KeyGenerationError>(())
/// ```
#[must_use]
pub const fn get_public_key(&self) -> PublicKey {
pub const fn get_public_key(&self) -> PublicKey {
PublicKey {
pk: self.pk,
h_pk: self.h_pk,
Expand Down Expand Up @@ -202,9 +205,13 @@ impl PrivateKey {
let sec_level = self.sec_level();

if bytes.len() != sec_level.private_key_bytes() {
return Err(CrystalsError::IncorrectBufferLength(bytes.len(), sec_level.private_key_bytes()).into());
return Err(CrystalsError::IncorrectBufferLength(
bytes.len(),
sec_level.private_key_bytes(),
)
.into());
}

let (sk_bytes, rest) = bytes.split_at_mut(sec_level.indcpa_private_key_bytes());
let (pk_bytes, rest) = rest.split_at_mut(sec_level.indcpa_public_key_bytes());
let (h_pk_bytes, z_bytes) = rest.split_at_mut(SYMBYTES);
Expand Down Expand Up @@ -257,9 +264,7 @@ impl PrivateKey {
let mut z = [0u8; SYMBYTES];
z.copy_from_slice(z_bytes);

Ok(
Self{ sk, pk, h_pk, z }
)
Ok(Self { sk, pk, h_pk, z })
}

/// Decapsulates a ciphertext (given as a byte slice) into the shared secret
Expand All @@ -285,30 +290,38 @@ impl PrivateKey {
///
/// # Ok::<(), enc_rust::errors::EncryptionDecryptionError>(())
/// ```
pub fn decapsulate(&self, ciphertext: &[u8]) -> Result<[u8; SHAREDSECRETBYTES], EncryptionDecryptionError> {
pub fn decapsulate(
&self,
ciphertext: &[u8],
) -> Result<[u8; SHAREDSECRETBYTES], EncryptionDecryptionError> {
let sec_level = self.sec_level();

if ciphertext.len() != sec_level.ciphertext_bytes() {
return Err(CrystalsError::InvalidCiphertextLength(ciphertext.len(), sec_level.ciphertext_bytes(), sec_level.k()).into());
return Err(CrystalsError::InvalidCiphertextLength(
ciphertext.len(),
sec_level.ciphertext_bytes(),
sec_level.k(),
)
.into());
}

let m = self.sk.decrypt(ciphertext)?;

let (k, r) = sha3_512_from(&[m, self.h_pk].concat());

let k_bar = shake256_from(&[&self.z, ciphertext].concat());

let mut ct = [0u8; MAX_CIPHERTEXT]; // max indcpa_bytes()
self.pk.encrypt(&m, &r, &mut ct[..sec_level.indcpa_bytes()])?;
self.pk
.encrypt(&m, &r, &mut ct[..sec_level.indcpa_bytes()])?;

let equal = ct.ct_eq(ciphertext);

Ok(k.iter()
.zip(k_bar.iter())
.map(|(x, y)| u8::conditional_select(x, y, equal))
.collect::<ArrayVec<[u8; SHAREDSECRETBYTES]>>()
.into_inner()
)
.zip(k_bar.iter())
.map(|(x, y)| u8::conditional_select(x, y, equal))
.collect::<ArrayVec<[u8; SHAREDSECRETBYTES]>>()
.into_inner())
}
}

Expand Down Expand Up @@ -341,7 +354,11 @@ impl PublicKey {
/// ```
pub fn pack(&self, bytes: &mut [u8]) -> Result<(), PackingError> {
if bytes.len() != self.sec_level().public_key_bytes() {
return Err(CrystalsError::IncorrectBufferLength(bytes.len(), self.sec_level().public_key_bytes()).into());
return Err(CrystalsError::IncorrectBufferLength(
bytes.len(),
self.sec_level().public_key_bytes(),
)
.into());
}

self.pk.pack(bytes)?;
Expand Down Expand Up @@ -376,9 +393,7 @@ impl PublicKey {
let pk = IndcpaPublicKey::unpack(bytes)?;
let h_pk = sha3_256_from(bytes);

Ok(
Self { pk, h_pk }
)
Ok(Self { pk, h_pk })
}

/// Encapsulates a generated shared secret into a ciphertext to be shared
Expand Down Expand Up @@ -428,14 +443,15 @@ impl PublicKey {

let (k, r) = sha3_512_from(&[m, self.h_pk].concat());
let mut bytes = [0u8; MAX_CIPHERTEXT]; // max ciphertext_bytes
self.pk.encrypt(&m, &r, &mut bytes[..sec_level.ciphertext_bytes()])?;

self.pk
.encrypt(&m, &r, &mut bytes[..sec_level.ciphertext_bytes()])?;

Ok((
Ciphertext {
bytes,
len: sec_level.ciphertext_bytes(),
},
k
k,
))
}
}
2 changes: 1 addition & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,11 +36,11 @@ mod tests {
// mod buffer;
mod field_operations;
mod indcpa;
mod kem;
mod matrix;
mod ntt;
mod params;
mod polynomials;
mod sample;
mod vectors;
mod kem;
}
2 changes: 1 addition & 1 deletion src/params.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use num_enum::{IntoPrimitive, TryFromPrimitive};
use core::fmt::{Display, Formatter};
use num_enum::{IntoPrimitive, TryFromPrimitive};

pub const N: usize = 256;
pub const Q: usize = 3329;
Expand Down
2 changes: 1 addition & 1 deletion src/tests/kem.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ mod kem_tests {
#[test]
fn encapsulate_decapsulate((pk, sk) in new_keypair()) {
let (ciphertext, shared_secret) = pk.encapsulate(None, None).unwrap();

let decap_secret = sk.decapsulate(ciphertext.as_bytes()).unwrap();

assert_eq!(shared_secret, decap_secret);
Expand Down

0 comments on commit 32503aa

Please sign in to comment.