crypto.rs 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. use crypto_box::aead::Aead;
  2. use rand::rngs::OsRng;
  3. /// Try decrypting a message given a NaCl box and a base58 string.
  4. /// The format we're using is nonce+ciphertext, where nonce is 24 bytes.
  5. pub fn try_decrypt_message(salt_box: &crypto_box::Box, ciphertext: &str) -> Option<String> {
  6. let bytes = match bs58::decode(ciphertext).into_vec() {
  7. Ok(v) => v,
  8. Err(_) => return None,
  9. };
  10. if bytes.len() < 25 {
  11. return None
  12. }
  13. // Try extracting the nonce
  14. let nonce = match bytes[0..24].try_into() {
  15. Ok(v) => v,
  16. Err(_) => return None,
  17. };
  18. // Take the remaining ciphertext
  19. let message = &bytes[24..];
  20. // Try decrypting the message
  21. match salt_box.decrypt(nonce, message) {
  22. Ok(v) => Some(String::from_utf8_lossy(&v).to_string()),
  23. Err(_) => None,
  24. }
  25. }
  26. /// Encrypt a message given a NaCl box and a plaintext string.
  27. /// The format we're using is nonce+ciphertext, where nonce is 24 bytes.
  28. pub fn encrypt_message(salt_box: &crypto_box::Box, plaintext: &str) -> String {
  29. let nonce = crypto_box::generate_nonce(&mut OsRng);
  30. let mut ciphertext = salt_box.encrypt(&nonce, plaintext.as_bytes()).unwrap();
  31. let mut concat = vec![];
  32. concat.append(&mut nonce.as_slice().to_vec());
  33. concat.append(&mut ciphertext);
  34. bs58::encode(concat).into_string()
  35. }