aes.rs 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. use aes_gcm::{
  2. aead::{generic_array::GenericArray, Aead, NewAead},
  3. Aes256Gcm,
  4. };
  5. pub type AesKey = [u8; 32];
  6. pub type Plaintext = Vec<u8>;
  7. pub type Ciphertext = Vec<u8>;
  8. pub fn aes_encrypt(
  9. shared_secret: &AesKey,
  10. nonce: &[u8; 12],
  11. plaintext: &[u8],
  12. ) -> Option<Ciphertext> {
  13. // Rust is gay, I need to convert to 'GenericArray' whatever the fuck that is...
  14. let key = GenericArray::from_slice(&shared_secret[..]);
  15. let cipher = Aes256Gcm::new(key);
  16. let nonce = GenericArray::from_slice(nonce);
  17. let ciphertext = cipher.encrypt(nonce, plaintext);
  18. ciphertext.ok()
  19. }
  20. pub fn aes_decrypt(
  21. shared_secret: &AesKey,
  22. nonce: &[u8; 12],
  23. ciphertext: Ciphertext,
  24. ) -> Option<Plaintext> {
  25. // Rust is gay, I need to convert to 'GenericArray' whatever the fuck that is...
  26. let key = GenericArray::from_slice(&shared_secret[..]);
  27. let cipher = Aes256Gcm::new(key);
  28. let nonce = GenericArray::from_slice(nonce);
  29. let plaintext = cipher.decrypt(nonce, ciphertext.as_ref());
  30. plaintext.ok()
  31. }
  32. #[test]
  33. fn test_aes() {
  34. let sh_secret = "e02e56a41320d8ebefa946753e9f69587c16d43876cf5bbac86c0ea0e9253d14".as_bytes();
  35. let mut channel_secret = [0u8; 32];
  36. channel_secret.copy_from_slice(&sh_secret[0..32]);
  37. let nonce = [3; 12];
  38. let ciphertext = aes_encrypt(&channel_secret, &nonce, b"plaintext message").unwrap();
  39. let plaintext = aes_decrypt(&channel_secret, &nonce, ciphertext).unwrap();
  40. // OK it works!
  41. assert_eq!(&plaintext, b"plaintext message");
  42. }