vector_core/community/
cipher.rs1use nostr_sdk::prelude::nip44::v2::ConversationKey;
4use rand::RngCore;
5
6pub fn encrypt_with_random_nonce(
13 ck: &ConversationKey,
14 plaintext: &[u8],
15) -> Result<Vec<u8>, String> {
16 let mut nonce = [0u8; 32];
17 rand::rngs::OsRng.fill_bytes(&mut nonce);
18 crate::crypto::nip44::encrypt_with_nonce(ck, plaintext, nonce).map_err(|e| e.to_string())
19}
20
21#[cfg(test)]
22mod tests {
23 use super::*;
24 use nostr_sdk::prelude::nip44::v2::decrypt_to_bytes;
25
26 #[test]
27 fn round_trips_and_never_repeats_a_nonce() {
28 let ck = ConversationKey::new([0x5au8; 32]);
29 let a = encrypt_with_random_nonce(&ck, b"hello community").unwrap();
30 let b = encrypt_with_random_nonce(&ck, b"hello community").unwrap();
31 assert_ne!(a, b);
32 assert_eq!(decrypt_to_bytes(&ck, &a).unwrap(), b"hello community");
33 assert!(decrypt_to_bytes(&ConversationKey::new([1u8; 32]), &a).is_err());
34 }
35}