saltbox.rs 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2025 Dyne.org foundation
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU Affero General Public License as
  7. * published by the Free Software Foundation, either version 3 of the
  8. * License, or (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU Affero General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU Affero General Public License
  16. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  17. */
  18. use crypto_box::{
  19. aead::{Aead, AeadCore},
  20. ChaChaBox,
  21. };
  22. use rand::rngs::OsRng;
  23. /// Encrypt given data using the given `ChaChaBox`.
  24. /// Returns base58-encoded string of the ciphertext.
  25. /// Panics if encryption fails.
  26. ///
  27. /// The encryption format we're using with `ChaChaBox` is `nonce||ciphertext`,
  28. /// where nonce is 24 bytes large, and the remaining data should be the ciphertext.
  29. pub fn encrypt(salt_box: &ChaChaBox, plaintext: &[u8]) -> String {
  30. // Generate the nonce
  31. let nonce = ChaChaBox::generate_nonce(&mut OsRng);
  32. // Encrypt
  33. let mut ciphertext = salt_box.encrypt(&nonce, plaintext).unwrap();
  34. // Concatenate
  35. let mut concat = Vec::with_capacity(24 + ciphertext.len());
  36. concat.append(&mut nonce.as_slice().to_vec());
  37. concat.append(&mut ciphertext);
  38. // Encode
  39. bs58::encode(concat).into_string()
  40. }
  41. /// Attempt to decrypt given ciphertext using the given `ChaChaBox`.
  42. /// Returns a `Vec<u8>` on success, and `None` on failure.
  43. ///
  44. /// The encryption format we're using with `ChaChaBox` is `nonce||ciphertext`,
  45. /// where nonce is 24 bytes large, and the remaining data should be the ciphertext.
  46. pub fn try_decrypt(salt_box: &ChaChaBox, ciphertext: &[u8]) -> Option<Vec<u8>> {
  47. // Make sure we have enough bytes to work with
  48. if ciphertext.len() < 25 {
  49. return None
  50. }
  51. match salt_box.decrypt((&ciphertext[0..24]).into(), &ciphertext[24..]) {
  52. Ok(v) => Some(v),
  53. Err(_) => None,
  54. }
  55. }