Argyle-Software / kyber

A rust implementation of the Kyber post-quantum KEM
https://docs.rs/pqc_kyber/
Apache License 2.0
164 stars 37 forks source link

encrypt custom messages #48

Closed oilel closed 1 year ago

oilel commented 1 year ago

Can it encrypt custom messages to replace GPG? GPG is a program made by GNU project, it can encrypt user-inputted messages.

mberry commented 1 year ago

Sure, here's quick example, though you should always use it alongside a traditional public key algorithm like x25519, rather than by itself in the following.

use pqc_kyber::*;
use aes_gcm::{
  aead::{Aead, KeyInit, OsRng},
  Aes256Gcm, Nonce
};

fn main() {
  let msg = b"hello";
  let nonce = Nonce::from_slice(b"unique nonce"); // 12 bytes
  let keys_bob = keypair(&mut OsRng);

  // Alice
  let (kem_ct, shared_secret_alice) = encapsulate(&keys_bob.public, &mut OsRng).unwrap();
  let alice_cipher = Aes256Gcm::new(&shared_secret_alice.into());
  let encrypted_msg = alice_cipher.encrypt(nonce, msg.as_ref()).unwrap();

  // Send nonce, kem_ct and encrypted_msg to Bob

  // Bob
  let shared_secret_bob = decapsulate(&kem_ct, &keys_bob.secret).unwrap();
  let bob_cipher = Aes256Gcm::new(&shared_secret_bob.into());
  let decrypted_msg = bob_cipher.decrypt(nonce, encrypted_msg.as_ref()).unwrap();

  assert_eq!(msg, &decrypted_msg.as_ref());
}

I'll add this to the examples folder.

mberry commented 1 year ago

If there's any more questions we can re-open the issue. Cheers.

oilel commented 1 year ago

@mberry Does nonce affect the security of encryption? If I use [0u8; 32] as nonce, all numbers are 0, is it secure?

oilel commented 1 year ago
// Send nonce, kem_ct and encrypted_msg to Bob

Do we need encrypt the nonce?