Skip to main content

vector_core/community/
cipher.rs

1//! Raw-key NIP-44 v2 sealing with a nonce no call site can choose.
2
3use nostr_sdk::prelude::nip44::v2::ConversationKey;
4use rand::RngCore;
5
6/// NIP-44 v2 encrypt with a freshly generated nonce.
7///
8/// The nonce MUST be unique per message under a given conversation key: reuse
9/// repeats the ChaCha20 keystream and forfeits both confidentiality and MAC
10/// integrity. Drawn from the OS CSPRNG here so no call site can supply its own.
11/// Wire output is unchanged (`[2][nonce][ct][mac]`).
12pub 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}