Skip to content

Commit

Permalink
style(kyberlib): 🎨 fix Rustfmt warnings
Browse files Browse the repository at this point in the history
  • Loading branch information
sebastienrousseau committed May 9, 2024
1 parent 6d13a32 commit c32f576
Show file tree
Hide file tree
Showing 43 changed files with 1,345 additions and 414 deletions.
31 changes: 31 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -35,12 +35,14 @@ version = "0.0.5"
[dependencies]
aes = { version = "0.8.4", optional = true }
ctr = { version = "0.9.2", optional = true }
pqc_core = { version = "0.3.0", features = ["zero"]}
rand = { version = "0.8.5", default-features = false, features = ["getrandom"] }
rand_core = { version = "0.6.4", default-features = false }
rlg = "0.0.4"
sha2 = { version = "0.10.8", optional = true }
tokio = { version = "1.37.0", optional = true }
wasm-bindgen = "0.2.92"
zeroize = { version = "1.7.0", features = ["derive"] }

[dev-dependencies]
criterion = "0.5.1"
Expand Down
33 changes: 26 additions & 7 deletions benches/api.rs

Large diffs are not rendered by default.

8 changes: 6 additions & 2 deletions examples/ake.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,12 @@ fn main() -> Result<(), KyberLibError> {

// Bob receives the request and authenticates Alice, sends
// encapsulated shared secret back
let server_send =
bob.server_receive(client_send, &alice_keys.public, &bob_keys.secret, &mut rng)?;
let server_send = bob.server_receive(
client_send,
&alice_keys.public,
&bob_keys.secret,
&mut rng,
)?;

// Alice authenticates and decapsulates
alice.client_confirm(server_send, &alice_keys.secret)?;
Expand Down
6 changes: 4 additions & 2 deletions examples/kem.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,10 +30,12 @@ fn main() -> Result<(), KyberLibError> {
let alice_keys = keypair(&mut rng)?;

// Bob encapsulates a shared secret
let (ciphertext, shared_secret_bob) = encapsulate(&alice_keys.public, &mut rng)?;
let (ciphertext, shared_secret_bob) =
encapsulate(&alice_keys.public, &mut rng)?;

// Alice decapsulates the shared secret
let shared_secret_alice = decapsulate(&ciphertext, &alice_keys.secret)?;
let shared_secret_alice =
decapsulate(&ciphertext, &alice_keys.secret)?;

// Both can now communicate symmetrically
assert_eq!(shared_secret_alice, shared_secret_bob);
Expand Down
3 changes: 2 additions & 1 deletion examples/uake.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,8 @@ fn main() -> Result<(), KyberLibError> {

// Bob receives the request and authenticates Alice, sends
// encapsulated shared secret back
let server_send = bob.server_receive(client_send, &bob_keys.secret, &mut rng)?;
let server_send =
bob.server_receive(client_send, &bob_keys.secret, &mut rng)?;

// Alice authenticates and decapsulates
alice.client_confirm(server_send)?;
Expand Down
41 changes: 34 additions & 7 deletions src/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ use crate::{
params::*,
CryptoRng, RngCore,
};
use pqc_core::zero;
#[cfg(feature = "zeroize")]
use zeroize::{Zeroize, ZeroizeOnDrop};

Expand Down Expand Up @@ -38,7 +39,9 @@ where
let mut public = [0u8; KYBER_PUBLIC_KEY_BYTES];
let mut secret = [0u8; KYBER_SECRET_KEY_BYTES];
generate_key_pair(&mut public, &mut secret, rng, None)?;
Ok(Keypair { public, secret })
let keys = Keypair { public, secret };
zero!(secret);
Ok(keys)
}

/// Verify that given secret and public key matches and put them in
Expand All @@ -62,7 +65,7 @@ pub fn keypairfrom<R>(
where
R: RngCore + CryptoRng,
{
//Try to encapsulate and decapsule to verify secret key matches public key
//Try to encapsulate and decapsulate to verify secret key matches public key
let (ciphertext, shared_secret) = encapsulate(public, rng)?;
let expected_shared_secret = decapsulate(&ciphertext, secret)?;
//If it does match, return a KeyPair
Expand Down Expand Up @@ -142,12 +145,14 @@ where
/// let mut rng = rand::thread_rng();
/// let keys = keypair(&mut rng)?;
/// let (ct, ss1) = encapsulate(&keys.public, &mut rng)?;
/// let ss2 = decapsulate(&ct, &keys.secret)?;
/// let ss2 = decapsulate(&ct, keys.expose_secret())?;
/// assert_eq!(ss1, ss2);
/// # Ok(())}
/// ```
pub fn decapsulate(ct: &[u8], sk: &[u8]) -> Decapsulated {
if ct.len() != KYBER_CIPHERTEXT_BYTES || sk.len() != KYBER_SECRET_KEY_BYTES {
if ct.len() != KYBER_CIPHERTEXT_BYTES
|| sk.len() != KYBER_SECRET_KEY_BYTES
{
return Err(KyberLibError::InvalidInput);
}
let mut ss = [0u8; KYBER_SHARED_SECRET_BYTES];
Expand Down Expand Up @@ -188,10 +193,27 @@ impl Keypair {
/// # assert!(empty_keys != keys);
/// # Ok(()) }
/// ```
pub fn generate<R: CryptoRng + RngCore>(rng: &mut R) -> Result<Keypair, KyberLibError> {
pub fn generate<R: CryptoRng + RngCore>(
rng: &mut R,
) -> Result<Keypair, KyberLibError> {
keypair(rng)
}

/// Explicitly exposes the secret key
///```
/// use kyberlib::*;
///
/// let mut rng = rand::thread_rng();
/// let keys = Keypair::generate(&mut rng);
/// let binding = keys.expect("Exposed secret key");
/// let secret = binding.expose_secret();
/// assert!(secret.len() == KYBER_SECRET_KEY_BYTES);
/// assert!(secret.len() != 0);
/// ```
pub fn expose_secret(&self) -> &SecretKey {
&self.secret
}

/// Imports a keypair from existing public and secret key arrays.
///
/// This function imports a keypair from existing public and secret key arrays and returns it as a `Keypair` struct.
Expand Down Expand Up @@ -237,7 +259,10 @@ impl RngCore for DummyRng {
panic!()
}

fn try_fill_bytes(&mut self, _dest: &mut [u8]) -> Result<(), rand_core::Error> {
fn try_fill_bytes(

Check warning on line 262 in src/api.rs

View check run for this annotation

Codecov / codecov/patch

src/api.rs#L262

Added line #L262 was not covered by tests
&mut self,
_dest: &mut [u8],
) -> Result<(), rand_core::Error> {
panic!()
}

Expand Down Expand Up @@ -287,7 +312,9 @@ pub fn derive(seed: &[u8]) -> Result<Keypair, KyberLibError> {
pub fn public(sk: &[u8]) -> PublicKey {
let mut pk = [0u8; KYBER_INDCPA_PUBLICKEYBYTES];
pk.copy_from_slice(
&sk[KYBER_INDCPA_SECRETKEYBYTES..KYBER_INDCPA_SECRETKEYBYTES + KYBER_INDCPA_PUBLICKEYBYTES],
&sk[KYBER_INDCPA_SECRETKEYBYTES
..KYBER_INDCPA_SECRETKEYBYTES
+ KYBER_INDCPA_PUBLICKEYBYTES],
);
pk
}
85 changes: 68 additions & 17 deletions src/avx2/aes256ctr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,20 +24,33 @@ impl Aes256CtrCtx {
}
}

unsafe fn aesni_encrypt4(out: &mut [u8], n: &mut __m128i, rkeys: &[__m128i; 16]) {
let idx: __m128i = _mm_set_epi8(8, 9, 10, 11, 12, 13, 14, 15, 7, 6, 5, 4, 3, 2, 1, 0);
unsafe fn aesni_encrypt4(
out: &mut [u8],
n: &mut __m128i,
rkeys: &[__m128i; 16],
) {
let idx: __m128i = _mm_set_epi8(
8, 9, 10, 11, 12, 13, 14, 15, 7, 6, 5, 4, 3, 2, 1, 0,
);

// Load current counter value
let mut f = _mm_load_si128(n);

// Increase counter in 4 consecutive blocks
let mut f0 = _mm_shuffle_epi8(_mm_add_epi64(f, _mm_set_epi64x(0, 0)), idx);
let mut f1 = _mm_shuffle_epi8(_mm_add_epi64(f, _mm_set_epi64x(1, 0)), idx);
let mut f2 = _mm_shuffle_epi8(_mm_add_epi64(f, _mm_set_epi64x(2, 0)), idx);
let mut f3 = _mm_shuffle_epi8(_mm_add_epi64(f, _mm_set_epi64x(3, 0)), idx);
let mut f0 =
_mm_shuffle_epi8(_mm_add_epi64(f, _mm_set_epi64x(0, 0)), idx);
let mut f1 =
_mm_shuffle_epi8(_mm_add_epi64(f, _mm_set_epi64x(1, 0)), idx);
let mut f2 =
_mm_shuffle_epi8(_mm_add_epi64(f, _mm_set_epi64x(2, 0)), idx);
let mut f3 =
_mm_shuffle_epi8(_mm_add_epi64(f, _mm_set_epi64x(3, 0)), idx);

// Write counter for next iteration, increased by 4
_mm_store_si128(n as *mut __m128i, _mm_add_epi64(f, _mm_set_epi64x(4, 0)));
_mm_store_si128(
n as *mut __m128i,
_mm_add_epi64(f, _mm_set_epi64x(4, 0)),
);

// Actual AES encryption, 4x interleaved4
f = _mm_load_si128(&rkeys[0]);
Expand Down Expand Up @@ -76,11 +89,16 @@ unsafe fn cast_128(x: __m128i) -> __m128 {
_mm_castsi128_ps(x)
}

pub fn aes256ctr_init(state: &mut Aes256CtrCtx, key: &[u8], nonce: [u8; 12]) {
pub fn aes256ctr_init(
state: &mut Aes256CtrCtx,
key: &[u8],
nonce: [u8; 12],
) {
unsafe {
let mut idx = 0;
let key0 = _mm_loadu_si128(key.as_ptr() as *const __m128i);
let key1 = _mm_loadu_si128(key[16..].as_ptr() as *const __m128i);
let key1 =
_mm_loadu_si128(key[16..].as_ptr() as *const __m128i);

state.n = _mm_loadl_epi64(nonce[..].as_ptr() as *const __m128i);
state.rkeys[idx] = key0;
Expand All @@ -95,11 +113,23 @@ pub fn aes256ctr_init(state: &mut Aes256CtrCtx, key: &[u8], nonce: [u8; 12]) {
temp1 = _mm_aeskeygenassist_si128(temp2, $imm);
state.rkeys[idx] = temp2;
idx += 1;
temp4 = cast_128i(_mm_shuffle_ps(cast_128(temp4), cast_128(temp0), 0x10));
temp4 = cast_128i(_mm_shuffle_ps(
cast_128(temp4),
cast_128(temp0),
0x10,
));
temp0 = _mm_xor_si128(temp0, temp4);
temp4 = cast_128i(_mm_shuffle_ps(cast_128(temp4), cast_128(temp0), 0x8c));
temp4 = cast_128i(_mm_shuffle_ps(
cast_128(temp4),
cast_128(temp0),
0x8c,
));
temp0 = _mm_xor_si128(temp0, temp4);
temp1 = cast_128i(_mm_shuffle_ps(cast_128(temp1), cast_128(temp1), 0xff));
temp1 = cast_128i(_mm_shuffle_ps(
cast_128(temp1),
cast_128(temp1),
0xff,
));
temp0 = _mm_xor_si128(temp0, temp1)
};
}
Expand All @@ -109,11 +139,23 @@ pub fn aes256ctr_init(state: &mut Aes256CtrCtx, key: &[u8], nonce: [u8; 12]) {
temp1 = _mm_aeskeygenassist_si128(temp0, $imm);
state.rkeys[idx] = temp0;
idx += 1;
temp4 = cast_128i(_mm_shuffle_ps(cast_128(temp4), cast_128(temp2), 0x10));
temp4 = cast_128i(_mm_shuffle_ps(
cast_128(temp4),
cast_128(temp2),
0x10,
));
temp2 = _mm_xor_si128(temp2, temp4);
temp4 = cast_128i(_mm_shuffle_ps(cast_128(temp4), cast_128(temp2), 0x8c));
temp4 = cast_128i(_mm_shuffle_ps(
cast_128(temp4),
cast_128(temp2),
0x8c,
));
temp2 = _mm_xor_si128(temp2, temp4);
temp1 = cast_128i(_mm_shuffle_ps(cast_128(temp1), cast_128(temp1), 0xaa));
temp1 = cast_128i(_mm_shuffle_ps(
cast_128(temp1),
cast_128(temp1),
0xaa,
));
temp2 = _mm_xor_si128(temp2, temp1)
};
}
Expand All @@ -138,7 +180,11 @@ pub fn aes256ctr_init(state: &mut Aes256CtrCtx, key: &[u8], nonce: [u8; 12]) {
}
}

pub fn aes256ctr_squeezeblocks(out: &mut [u8], nblocks: usize, state: &mut Aes256CtrCtx) {
pub fn aes256ctr_squeezeblocks(
out: &mut [u8],
nblocks: usize,
state: &mut Aes256CtrCtx,
) {
let mut idx = 0;
for _ in 0..nblocks {
unsafe {
Expand All @@ -149,7 +195,12 @@ pub fn aes256ctr_squeezeblocks(out: &mut [u8], nblocks: usize, state: &mut Aes25
}

#[cfg(feature = "90s")]
pub fn aes256ctr_prf(out: &mut [u8], mut outlen: usize, seed: &[u8], nonce: u8) {
pub fn aes256ctr_prf(
out: &mut [u8],
mut outlen: usize,
seed: &[u8],
nonce: u8,
) {
let mut buf = [0u8; 64];
let mut idx = 0;
let mut pad_nonce = [0u8; 12];
Expand Down
21 changes: 15 additions & 6 deletions src/avx2/align.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,8 @@ use core::arch::x86_64::*;
#[repr(C, align(32))]
pub union GenMatrixBuf {
pub coeffs: [u8; REJ_UNIFORM_AVX_NBLOCKS * SHAKE128_RATE],
pub vec: [__m256i; (REJ_UNIFORM_AVX_NBLOCKS * SHAKE128_RATE + 31) / 32],
pub vec:
[__m256i; (REJ_UNIFORM_AVX_NBLOCKS * SHAKE128_RATE + 31) / 32],
}

impl GenMatrixBuf {
Expand All @@ -26,7 +27,8 @@ impl GenMatrixBuf {
#[repr(C)]
pub union GenMatrixBuf90s {
pub coeffs: [u8; REJ_UNIFORM_AVX_NBLOCKS * XOF_BLOCKBYTES],
pub vec: [__m256i; (REJ_UNIFORM_AVX_NBLOCKS * XOF_BLOCKBYTES + 31) / 32],
pub vec:
[__m256i; (REJ_UNIFORM_AVX_NBLOCKS * XOF_BLOCKBYTES + 31) / 32],
}

#[cfg(feature = "90s")]
Expand All @@ -51,15 +53,22 @@ impl GenMatrixBuf90s {

#[repr(C)]
pub union IndcpaBuf {
pub coeffs: [u8; (KYBER_ETA1 * KYBER_N / 4) / XOF_BLOCKBYTES * XOF_BLOCKBYTES + 32],
pub vec:
[__m256i; ((KYBER_ETA1 * KYBER_N / 4) / XOF_BLOCKBYTES * XOF_BLOCKBYTES + 32 + 31) / 32],
pub coeffs: [u8; (KYBER_ETA1 * KYBER_N / 4) / XOF_BLOCKBYTES
* XOF_BLOCKBYTES
+ 32],
pub vec: [__m256i;
((KYBER_ETA1 * KYBER_N / 4) / XOF_BLOCKBYTES * XOF_BLOCKBYTES
+ 32
+ 31)
/ 32],
}

impl IndcpaBuf {
pub fn new() -> Self {
Self {
coeffs: [0u8; (KYBER_ETA1 * KYBER_N / 4) / XOF_BLOCKBYTES * XOF_BLOCKBYTES + 32],
coeffs: [0u8; (KYBER_ETA1 * KYBER_N / 4) / XOF_BLOCKBYTES
* XOF_BLOCKBYTES
+ 32],
}
}
}
Expand Down
Loading

0 comments on commit c32f576

Please sign in to comment.