Skip to main content

vector_core/crypto/
nip44.rs

1//! NIP-44 v2 on Vector's own ChaCha20 and SHA-256: the bytes of rust-nostr's `nip44::v2`,
2//! decrypting in place in the buffer the payload was decoded into.
3//!
4//! Like `nip44::v2::decrypt_to_bytes`, decryption leaves the version byte to the caller.
5
6use nostr_sdk::prelude::nip44::v2::ConversationKey;
7
8use super::chachapoly::{chacha20_xor, wipe};
9use super::sha256::Sha256;
10
11const NONCE_SIZE: usize = 32;
12const MAC_SIZE: usize = 32;
13const MIN_PAYLOAD_SIZE: usize = 1 + NONCE_SIZE + 2 + 32 + MAC_SIZE;
14const EXTENDED_PREFIX_THRESHOLD: u64 = 65_536;
15const MAX_PLAINTEXT_SIZE: u64 = u32::MAX as u64;
16const MAX_PAYLOAD_SIZE: u64 = 1 + NONCE_SIZE as u64 + 6 + calc_padding(MAX_PLAINTEXT_SIZE) + MAC_SIZE as u64;
17/// The longest base64 payload rust-nostr's `nip44::decrypt` takes.
18pub const MAX_ENCODED_PAYLOAD_SIZE: u64 = MAX_PAYLOAD_SIZE.div_ceil(3) * 4;
19
20#[derive(Debug, Clone, Copy, PartialEq, Eq)]
21pub enum Error {
22    PayloadTooShort,
23    MessageEmpty,
24    MessageTooLong,
25    InvalidHmac,
26    InvalidPadding,
27}
28
29impl std::fmt::Display for Error {
30    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
31        f.write_str(match self {
32            Error::PayloadTooShort => "payload size is too short",
33            Error::MessageEmpty => "message empty",
34            Error::MessageTooLong => "message too long",
35            Error::InvalidHmac => "invalid HMAC",
36            Error::InvalidPadding => "invalid padding",
37        })
38    }
39}
40
41impl std::error::Error for Error {}
42
43/// HMAC-SHA256 under one key, its key schedule absorbed once.
44#[derive(Clone)]
45struct Hmac {
46    inner: Sha256,
47    outer: Sha256,
48}
49
50impl Hmac {
51    /// `key` is at most one block: a conversation key or a message's auth key.
52    fn new(key: &[u8; 32]) -> Self {
53        let mut block = [0u8; 64];
54        block[..32].copy_from_slice(key);
55        let (mut inner, mut outer) = (Sha256::new(), Sha256::new());
56        let mut pad = block.map(|b| b ^ 0x36);
57        inner.update(pad);
58        pad = block.map(|b| b ^ 0x5c);
59        outer.update(pad);
60        wipe(&mut pad);
61        wipe(&mut block);
62        Hmac { inner, outer }
63    }
64
65    fn mac(&self, parts: &[&[u8]]) -> [u8; 32] {
66        let mut inner = self.inner.clone();
67        for part in parts {
68            inner.update(part);
69        }
70        let mut outer = self.outer.clone();
71        outer.update(inner.finalize());
72        outer.finalize()
73    }
74}
75
76/// The 76 message key bytes (RFC 5869 expand of the conversation key over the nonce):
77/// ChaCha20 key, ChaCha20 nonce, HMAC key.
78struct MessageKeys([u8; 96]);
79
80impl MessageKeys {
81    fn derive(ck: &ConversationKey, nonce: &[u8]) -> Self {
82        let prk = Hmac::new(ck.as_bytes().try_into().expect("a conversation key is 32 bytes"));
83        let mut out = [0u8; 96];
84        let t1 = prk.mac(&[nonce, &[1]]);
85        let t2 = prk.mac(&[&t1, nonce, &[2]]);
86        let t3 = prk.mac(&[&t2, nonce, &[3]]);
87        out[..32].copy_from_slice(&t1);
88        out[32..64].copy_from_slice(&t2);
89        out[64..].copy_from_slice(&t3);
90        MessageKeys(out)
91    }
92
93    fn cipher_key(&self) -> &[u8; 32] {
94        self.0[..32].try_into().expect("32 bytes")
95    }
96
97    fn cipher_nonce(&self) -> &[u8; 12] {
98        self.0[32..44].try_into().expect("12 bytes")
99    }
100
101    fn auth(&self) -> Hmac {
102        Hmac::new(self.0[44..76].try_into().expect("32 bytes"))
103    }
104}
105
106impl Drop for MessageKeys {
107    fn drop(&mut self) {
108        wipe(&mut self.0);
109    }
110}
111
112const fn calc_padding(len: u64) -> u64 {
113    if len <= 32 {
114        return 32;
115    }
116    let nextpower = 1 << ((u64::BITS - 1 - (len - 1).leading_zeros()) + 1);
117    let chunk = if nextpower <= 256 { 32 } else { nextpower / 8 };
118    chunk * (((len - 1) / chunk) + 1)
119}
120
121/// Encrypt `plaintext` under `nonce`: `[2][nonce][length prefix | plaintext | padding][mac]`.
122pub fn encrypt_with_nonce(ck: &ConversationKey, plaintext: &[u8], nonce: [u8; 32]) -> Result<Vec<u8>, Error> {
123    let len = plaintext.len() as u64;
124    if len == 0 {
125        return Err(Error::MessageEmpty);
126    }
127    if len > MAX_PLAINTEXT_SIZE {
128        return Err(Error::MessageTooLong);
129    }
130    let extended = len >= EXTENDED_PREFIX_THRESHOLD;
131    let ciphertext_len = if extended { 6 } else { 2 } + calc_padding(len) as usize;
132    let mac_at = 1 + NONCE_SIZE + ciphertext_len;
133    let mut payload = Vec::with_capacity(mac_at + MAC_SIZE);
134    payload.push(2);
135    payload.extend_from_slice(&nonce);
136    if extended {
137        payload.extend_from_slice(&[0, 0]);
138        payload.extend_from_slice(&(len as u32).to_be_bytes());
139    } else {
140        payload.extend_from_slice(&(len as u16).to_be_bytes());
141    }
142    payload.extend_from_slice(plaintext);
143    payload.resize(mac_at, 0);
144    let keys = MessageKeys::derive(ck, &nonce);
145    chacha20_xor(keys.cipher_key(), keys.cipher_nonce(), 0, &mut payload[1 + NONCE_SIZE..]);
146    let mac = keys.auth().mac(&[&payload[1..]]);
147    payload.extend_from_slice(&mac);
148    Ok(payload)
149}
150
151/// Decrypt a decoded v2 `payload`, reusing its buffer for the plaintext.
152pub fn decrypt(ck: &ConversationKey, mut payload: Vec<u8>) -> Result<Vec<u8>, Error> {
153    let len = payload.len();
154    if len < MIN_PAYLOAD_SIZE {
155        return Err(Error::PayloadTooShort);
156    }
157    if len as u64 > MAX_PAYLOAD_SIZE {
158        return Err(Error::MessageTooLong);
159    }
160    let mac_at = len - MAC_SIZE;
161    let keys = MessageKeys::derive(ck, &payload[1..1 + NONCE_SIZE]);
162    let mac = keys.auth().mac(&[&payload[1..mac_at]]);
163    if !mac_eq(&mac, &payload[mac_at..]) {
164        return Err(Error::InvalidHmac);
165    }
166    let body = &mut payload[1 + NONCE_SIZE..mac_at];
167    chacha20_xor(keys.cipher_key(), keys.cipher_nonce(), 0, body);
168    let framed = (|| {
169        let (prefix, unpadded) = plaintext_length(body)?;
170        let end = prefix.checked_add(unpadded).ok_or(Error::InvalidPadding)?;
171        if end > body.len() {
172            return Err(Error::InvalidPadding);
173        }
174        if unpadded == 0 {
175            return Err(Error::MessageEmpty);
176        }
177        let expected = (prefix as u64).checked_add(calc_padding(unpadded as u64)).ok_or(Error::InvalidPadding)?;
178        if body.len() as u64 != expected {
179            return Err(Error::InvalidPadding);
180        }
181        Ok((prefix, unpadded))
182    })();
183    let (prefix, unpadded) = match framed {
184        Ok(framed) => framed,
185        Err(e) => {
186            // It decrypted: what it holds now is plaintext.
187            super::chachapoly::wipe_vec(&mut payload);
188            return Err(e);
189        }
190    };
191    let start = 1 + NONCE_SIZE + prefix;
192    payload.copy_within(start..start + unpadded, 0);
193    payload.truncate(unpadded);
194    Ok(payload)
195}
196
197fn plaintext_length(body: &[u8]) -> Result<(usize, usize), Error> {
198    let short = u16::from_be_bytes(body.get(..2).ok_or(Error::InvalidPadding)?.try_into().expect("2 bytes"));
199    if short != 0 {
200        return Ok((2, short as usize));
201    }
202    let wide = u32::from_be_bytes(body.get(2..6).ok_or(Error::InvalidPadding)?.try_into().expect("4 bytes"));
203    if (wide as u64) < EXTENDED_PREFIX_THRESHOLD {
204        return Err(Error::InvalidPadding);
205    }
206    Ok((6, usize::try_from(wide).map_err(|_| Error::MessageTooLong)?))
207}
208
209fn mac_eq(a: &[u8; 32], b: &[u8]) -> bool {
210    b.len() == 32 && a.iter().zip(b).fold(0u8, |acc, (x, y)| acc | (x ^ y)) == 0
211}
212
213#[cfg(test)]
214mod tests {
215    use super::*;
216    use nostr_sdk::prelude::nip44::v2 as theirs;
217
218    fn lengths() -> impl Iterator<Item = usize> {
219        (1..=600).chain([1000, 1023, 1024, 1025, 4096, 8193, 32_768, 65_535, 65_536, 65_537, 100_000, 300_001])
220    }
221
222    #[test]
223    fn encrypts_byte_for_byte_as_rust_nostr() {
224        let mut seed = 0x51u8;
225        for len in lengths() {
226            seed = seed.wrapping_mul(31).wrapping_add(7);
227            let ck = ConversationKey::new([seed; 32]);
228            let nonce = [seed ^ 0xa5; 32];
229            let plaintext: Vec<u8> = (0..len).map(|i| (i as u8).wrapping_mul(seed)).collect();
230            let ours = encrypt_with_nonce(&ck, &plaintext, nonce).unwrap();
231            assert_eq!(ours, theirs::encrypt_to_bytes_with_nonce(&ck, &plaintext, nonce).unwrap(), "len {len}");
232            assert_eq!(decrypt(&ck, ours.clone()).unwrap(), plaintext, "len {len}");
233            assert_eq!(theirs::decrypt_to_bytes(&ck, &ours).unwrap(), plaintext, "len {len}");
234        }
235        assert_eq!(encrypt_with_nonce(&ConversationKey::new([1; 32]), &[], [0; 32]), Err(Error::MessageEmpty));
236    }
237
238    #[test]
239    fn refuses_exactly_what_rust_nostr_refuses() {
240        let ck = ConversationKey::new([9; 32]);
241        let valid = theirs::encrypt_to_bytes_with_nonce(&ck, b"a message long enough to pad past one chunk, and then some more", [3; 32]).unwrap();
242        let agree = |payload: &[u8], what: &str| {
243            let ours = decrypt(&ck, payload.to_vec());
244            let them = theirs::decrypt_to_bytes(&ck, payload);
245            assert_eq!(ours.as_ref().ok(), them.as_ref().ok(), "{what}: {ours:?} vs {them:?}");
246        };
247        // Every single-byte change, the version byte included (neither checks it).
248        for i in 0..valid.len() {
249            let mut p = valid.clone();
250            p[i] ^= 0x40;
251            agree(&p, &format!("byte {i}"));
252        }
253        for cut in [0, 1, 33, 98, 99, 100, valid.len() - 1] {
254            agree(&valid[..cut], &format!("cut to {cut}"));
255        }
256        agree(&[valid.clone(), vec![0; 32]].concat(), "trailing bytes");
257        // Correct MACs over plaintexts whose framing lies: a length past the padding, a zero length,
258        // an extended length below the threshold, padding of the wrong size.
259        let keys = MessageKeys::derive(&ck, &[5; 32]);
260        let forge = |body: Vec<u8>| {
261            let mut p = vec![2];
262            p.extend_from_slice(&[5; 32]);
263            let mut b = body;
264            chacha20_xor(keys.cipher_key(), keys.cipher_nonce(), 0, &mut b);
265            p.extend_from_slice(&b);
266            let mac = keys.auth().mac(&[&p[1..]]);
267            p.extend_from_slice(&mac);
268            p
269        };
270        for (what, body) in [
271            ("length past the padding", [&[0u8, 40][..], &[1; 32]].concat()),
272            ("zero length", [&[0u8, 0, 0, 0, 0, 0][..], &[1; 28]].concat()),
273            ("short extended length", [&[0u8, 0, 0, 0, 0, 20][..], &[1; 28]].concat()),
274            ("too much padding", [&[0u8, 3][..], &[1; 62]].concat()),
275            ("exact fit", [&[0u8, 32][..], &[1; 32]].concat()),
276        ] {
277            agree(&forge(body), what);
278        }
279    }
280
281    #[test]
282    fn decrypts_rust_nostrs_payloads_under_random_keys() {
283        use nostr_sdk::prelude::Keys;
284        for len in [1usize, 31, 32, 33, 200, 1500, 70_000] {
285            let (a, b) = (Keys::generate(), Keys::generate());
286            let ck = ConversationKey::derive(a.secret_key(), &b.public_key()).unwrap();
287            let plaintext = vec![0x42u8; len];
288            let payload = theirs::encrypt_to_bytes_with_nonce(&ck, &plaintext, [len as u8; 32]).unwrap();
289            assert_eq!(decrypt(&ck, payload).unwrap(), plaintext);
290        }
291    }
292}