VibeProtocol/
sodium_wrapper.rs

1use sodiumoxide::crypto::{secretbox, box_};
2use sodiumoxide::init as sodium_init;
3
4pub fn encrypt_sodium(plaintext: &str) -> Result<(Vec<u8>, secretbox::Nonce, secretbox::Key), String> {
5    sodium_init().map_err(|_| "Failed to initialize sodiumoxide")?;
6
7    let key = secretbox::gen_key();
8    let nonce = secretbox::gen_nonce();
9    let ciphertext = secretbox::seal(plaintext.as_bytes(), &nonce, &key);
10
11    Ok((ciphertext, nonce, key))
12}
13
14pub fn decrypt_sodium(ciphertext: &[u8], nonce: &secretbox::Nonce, key: &secretbox::Key) -> Result<String, String> {
15    secretbox::open(ciphertext, nonce, key)
16        .map(|decrypted| String::from_utf8(decrypted).unwrap_or_else(|_| "Failed to decode plaintext".to_owned()))
17        .map_err(|_| "Decryption failed".to_owned())
18}