Skip to main content

ferogram_e2e/
crypto.rs

1/*
2 * Copyright (c) 2026 Ankit Chaubey <ankitchaubey.dev@gmail.com>
3 * https://github.com/ankit-chaubey
4 *
5 * Project: ferogram
6 * Website: https://ferogram.dev
7 *
8 * Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
9 * https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
10 * <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option.
11 * This file may not be copied, modified, or distributed except according
12 * to those terms.
13 */
14
15//! Cryptographic primitives for Telegram secret chats (MTProto 2.0).
16//!
17//! - Message encryption: [`encrypt_message`] / [`decrypt_message`].
18//! - Per-file encryption: [`file_encrypt`] / [`file_decrypt`] and
19//!   [`file_key_fingerprint`].
20//! - Key identification: [`key_fingerprint`] and [`emoji_fingerprint_indices`].
21
22use ferogram_crypto::aes::{ige_decrypt, ige_encrypt};
23use rand::Rng;
24use sha1::{Digest as _, Sha1};
25use sha2::Sha256;
26
27use crate::error::E2eError;
28
29/// Minimum number of random padding bytes in MTProto 2.0.
30const MIN_PADDING: usize = 12;
31
32/// Maximum number of random padding bytes in MTProto 2.0.
33const MAX_PADDING: usize = 1024;
34
35/// Number of padding bytes (12..=27) that bring `msg_len + padding` to a multiple of 16.
36fn padding_len(msg_len: usize) -> usize {
37    let rem = (msg_len + MIN_PADDING) % 16;
38    if rem == 0 {
39        MIN_PADDING
40    } else {
41        MIN_PADDING + (16 - rem)
42    }
43}
44
45/// Derive the AES-256-IGE key and IV from `auth_key` and `msg_key`.
46///
47/// `x` is 0 for messages sent by the chat originator and 8 for the opposite direction.
48fn derive_key_iv(auth_key: &[u8; 256], msg_key: &[u8; 16], x: usize) -> ([u8; 32], [u8; 32]) {
49    let mut input_a = Vec::with_capacity(16 + 36);
50    input_a.extend_from_slice(msg_key);
51    input_a.extend_from_slice(&auth_key[x..x + 36]);
52    let sha_a: [u8; 32] = Sha256::digest(&input_a).into();
53
54    let mut input_b = Vec::with_capacity(36 + 16);
55    input_b.extend_from_slice(&auth_key[40 + x..40 + x + 36]);
56    input_b.extend_from_slice(msg_key);
57    let sha_b: [u8; 32] = Sha256::digest(&input_b).into();
58
59    let mut aes_key = [0u8; 32];
60    aes_key[..8].copy_from_slice(&sha_a[..8]);
61    aes_key[8..24].copy_from_slice(&sha_b[8..24]);
62    aes_key[24..].copy_from_slice(&sha_a[24..]);
63
64    let mut aes_iv = [0u8; 32];
65    aes_iv[..8].copy_from_slice(&sha_b[..8]);
66    aes_iv[8..24].copy_from_slice(&sha_a[8..24]);
67    aes_iv[24..].copy_from_slice(&sha_b[24..]);
68
69    (aes_key, aes_iv)
70}
71
72/// Compute the 64-bit `key_fingerprint`: the last 8 bytes of `SHA1(auth_key)`, read as a
73/// little-endian `i64`.
74///
75/// This is a sanity check on the key exchange, not the key visualization shown to users.
76pub fn key_fingerprint(auth_key: &[u8; 256]) -> i64 {
77    let hash: [u8; 20] = Sha1::digest(auth_key).into();
78    let mut b = [0u8; 8];
79    b.copy_from_slice(&hash[12..20]);
80    i64::from_le_bytes(b)
81}
82
83/// Encrypt a secret chat message blob.
84///
85/// `plaintext` is the fully serialized inner TL (`DecryptedMessageLayer` bytes
86/// for layer 17 and above, or bare layer-8 service bytes for `notify_layer`).
87/// `admin` is `true` when we initiated the chat.
88///
89/// Returns `key_fingerprint (8, LE) || msg_key (16) || ciphertext`.
90pub fn encrypt_message(
91    auth_key: &[u8; 256],
92    plaintext: &[u8],
93    admin: bool,
94) -> Result<Vec<u8>, E2eError> {
95    let x: usize = if admin { 0 } else { 8 };
96
97    let current_len = 4 + plaintext.len();
98    let pad_len = padding_len(current_len);
99
100    let mut buf = Vec::with_capacity(current_len + pad_len);
101    buf.extend_from_slice(&(plaintext.len() as u32).to_le_bytes());
102    buf.extend_from_slice(plaintext);
103    let mut pad = vec![0u8; pad_len];
104    rand::rng().fill_bytes(&mut pad);
105    buf.extend_from_slice(&pad);
106
107    let mut key_input = Vec::with_capacity(32 + buf.len());
108    key_input.extend_from_slice(&auth_key[88 + x..88 + x + 32]);
109    key_input.extend_from_slice(&buf);
110    let msg_key_large: [u8; 32] = Sha256::digest(&key_input).into();
111    let mut msg_key = [0u8; 16];
112    msg_key.copy_from_slice(&msg_key_large[8..24]);
113
114    let (aes_key, aes_iv) = derive_key_iv(auth_key, &msg_key, x);
115    ige_encrypt(&mut buf, &aes_key, &aes_iv);
116
117    let fp = key_fingerprint(auth_key);
118    let mut out = Vec::with_capacity(8 + 16 + buf.len());
119    out.extend_from_slice(&fp.to_le_bytes());
120    out.extend_from_slice(&msg_key);
121    out.extend_from_slice(&buf);
122
123    Ok(out)
124}
125
126/// Decrypt an incoming secret chat blob.
127///
128/// `data` is `key_fingerprint (8) || msg_key (16) || ciphertext`.
129/// `admin` is `true` when we initiated the chat.
130///
131/// Verifies the key fingerprint, the `msg_key` (SHA-256 over a fragment of
132/// `auth_key` and the decrypted body), the length prefix and the padding size
133/// (12..=1024 bytes). Returns the inner TL bytes without the 4-byte length prefix.
134pub fn decrypt_message(
135    auth_key: &[u8; 256],
136    data: &[u8],
137    admin: bool,
138) -> Result<Vec<u8>, E2eError> {
139    // Decrypt uses opposite x from encrypt.
140    let x: usize = if admin { 8 } else { 0 };
141
142    if data.len() < 24 {
143        return Err(E2eError::DecryptionFailed);
144    }
145
146    let mut fp_bytes = [0u8; 8];
147    fp_bytes.copy_from_slice(&data[0..8]);
148    let received_fp = i64::from_le_bytes(fp_bytes);
149    let expected_fp = key_fingerprint(auth_key);
150    if received_fp != expected_fp {
151        return Err(E2eError::KeyFingerprintMismatch);
152    }
153
154    let mut msg_key = [0u8; 16];
155    msg_key.copy_from_slice(&data[8..24]);
156
157    let ciphertext = &data[24..];
158    if !ciphertext.len().is_multiple_of(16) || ciphertext.is_empty() {
159        return Err(E2eError::DecryptionFailed);
160    }
161
162    let (aes_key, aes_iv) = derive_key_iv(auth_key, &msg_key, x);
163
164    let mut decrypted = ciphertext.to_vec();
165    ige_decrypt(&mut decrypted, &aes_key, &aes_iv);
166
167    let mut verify_input = Vec::with_capacity(32 + decrypted.len());
168    verify_input.extend_from_slice(&auth_key[88 + x..88 + x + 32]);
169    verify_input.extend_from_slice(&decrypted);
170    let expected_large: [u8; 32] = Sha256::digest(&verify_input).into();
171    if msg_key != expected_large[8..24] {
172        return Err(E2eError::DecryptionFailed);
173    }
174
175    if decrypted.len() < 4 {
176        return Err(E2eError::DecryptionFailed);
177    }
178
179    let mut len_bytes = [0u8; 4];
180    len_bytes.copy_from_slice(&decrypted[0..4]);
181    let msg_len = u32::from_le_bytes(len_bytes) as usize;
182
183    if 4 + msg_len > decrypted.len() {
184        return Err(E2eError::DecryptionFailed);
185    }
186
187    // The message length is always a multiple of 4 (TL serialization).
188    if !msg_len.is_multiple_of(4) {
189        return Err(E2eError::DecryptionFailed);
190    }
191
192    let padding = decrypted.len() - 4 - msg_len;
193    if !(MIN_PADDING..=MAX_PADDING).contains(&padding) {
194        return Err(E2eError::DecryptionFailed);
195    }
196
197    Ok(decrypted[4..4 + msg_len].to_vec())
198}
199
200// Per-file AES-256-IGE encryption for `messages.sendEncryptedFile`.
201
202/// Encrypt file bytes with a freshly generated AES-256-IGE key and IV.
203///
204/// Returns `(key, iv, ciphertext)`.
205///
206/// Key and IV are both 32 bytes. IGE uses the full 32-byte IV as `iv1 || iv2`,
207/// the layout `ferogram_crypto::aes::ige_encrypt` expects. The plaintext is
208/// padded to a multiple of 16 bytes with random bytes before encryption; the
209/// receiver truncates to the `size` field of the `DecryptedMedia` TL.
210pub fn file_encrypt(plaintext: &[u8]) -> ([u8; 32], [u8; 32], Vec<u8>) {
211    let mut key = [0u8; 32];
212    let mut iv = [0u8; 32];
213    rand::rng().fill_bytes(&mut key);
214    rand::rng().fill_bytes(&mut iv);
215
216    let pad_len = (16 - (plaintext.len() % 16)) % 16;
217    let mut buf = plaintext.to_vec();
218    if pad_len > 0 {
219        let mut tail = vec![0u8; pad_len];
220        rand::rng().fill_bytes(&mut tail);
221        buf.extend_from_slice(&tail);
222    }
223
224    ige_encrypt(&mut buf, &key, &iv);
225
226    (key, iv, buf)
227}
228
229/// Decrypt file ciphertext with the key and iv from the inner TL media field.
230///
231/// `size` is the original plaintext length from the `DecryptedMedia` `size` field.
232/// Decrypts with AES-256-IGE and truncates the result to `size`.
233///
234/// Fails with [`E2eError::DecryptionFailed`] if `key` or `iv` is shorter than
235/// 32 bytes, the ciphertext is empty or not a multiple of 16 bytes, or `size`
236/// exceeds the decrypted length.
237pub fn file_decrypt(
238    ciphertext: &[u8],
239    key: &[u8],
240    iv: &[u8],
241    size: usize,
242) -> Result<Vec<u8>, crate::error::E2eError> {
243    if key.len() < 32 || iv.len() < 32 {
244        return Err(crate::error::E2eError::DecryptionFailed);
245    }
246    if !ciphertext.len().is_multiple_of(16) || ciphertext.is_empty() {
247        return Err(crate::error::E2eError::DecryptionFailed);
248    }
249
250    let key32: &[u8; 32] = key[..32]
251        .try_into()
252        .map_err(|_| crate::error::E2eError::DecryptionFailed)?;
253    let iv32: &[u8; 32] = iv[..32]
254        .try_into()
255        .map_err(|_| crate::error::E2eError::DecryptionFailed)?;
256
257    let mut buf = ciphertext.to_vec();
258    ige_decrypt(&mut buf, key32, iv32);
259
260    if size > buf.len() {
261        return Err(crate::error::E2eError::DecryptionFailed);
262    }
263    buf.truncate(size);
264    Ok(buf)
265}
266
267/// File key fingerprint, as defined by the secret chat spec.
268///
269/// ```text
270/// digest      = md5(key || iv)
271/// fingerprint = LE_i32(digest[0..4]) XOR LE_i32(digest[4..8])
272/// ```
273///
274/// Used as `key_fingerprint` in `InputEncryptedFileUploaded` and
275/// `InputEncryptedFileBigUploaded`. This is not the chat `auth_key` fingerprint.
276pub fn file_key_fingerprint(key: &[u8; 32], iv: &[u8; 32]) -> i32 {
277    let mut input = [0u8; 64];
278    input[..32].copy_from_slice(key);
279    input[32..].copy_from_slice(iv);
280    let digest: [u8; 16] = md5::compute(input).into();
281    let a = i32::from_le_bytes([digest[0], digest[1], digest[2], digest[3]]);
282    let b = i32::from_le_bytes([digest[4], digest[5], digest[6], digest[7]]);
283    a ^ b
284}
285
286/// Compute four indices into [`EMOJI_FINGERPRINT_TABLE`] from `auth_key`.
287///
288/// ```text
289/// SHA1(auth_key)  ->  20 bytes
290/// bytes[0..8]     ->  four little-endian u16 values
291/// value % 333     ->  index into EMOJI_FINGERPRINT_TABLE
292/// ```
293///
294/// Both sides of a chat derive the same four emojis from the shared key, so
295/// users can compare them out of band to detect a man-in-the-middle.
296pub fn emoji_fingerprint_indices(auth_key: &[u8; 256]) -> [usize; 4] {
297    let hash: [u8; 20] = Sha1::digest(auth_key).into();
298    [
299        (u16::from_le_bytes([hash[0], hash[1]]) % 333) as usize,
300        (u16::from_le_bytes([hash[2], hash[3]]) % 333) as usize,
301        (u16::from_le_bytes([hash[4], hash[5]]) % 333) as usize,
302        (u16::from_le_bytes([hash[6], hash[7]]) % 333) as usize,
303    ]
304}
305
306/// The 333-emoji table that [`emoji_fingerprint_indices`] indexes into.
307///
308/// Taken from Telegram Desktop (`kFingerprintEmojis` in
309/// `Telegram/SourceFiles/data/data_emoji_fingerprint.cpp`,
310/// <https://github.com/telegramdesktop/tdesktop>). The order must not change.
311pub const EMOJI_FINGERPRINT_TABLE: [&str; 333] = [
312    "\u{1F601}",
313    "\u{1F602}",
314    "\u{1F603}",
315    "\u{1F604}",
316    "\u{1F605}",
317    "\u{1F606}",
318    "\u{1F609}",
319    "\u{1F60A}",
320    "\u{1F60B}",
321    "\u{1F60C}",
322    "\u{1F60D}",
323    "\u{1F60E}",
324    "\u{1F60F}",
325    "\u{1F610}",
326    "\u{1F612}",
327    "\u{1F613}",
328    "\u{1F614}",
329    "\u{1F616}",
330    "\u{1F618}",
331    "\u{1F61A}",
332    "\u{1F61C}",
333    "\u{1F61D}",
334    "\u{1F61E}",
335    "\u{1F620}",
336    "\u{1F621}",
337    "\u{1F622}",
338    "\u{1F623}",
339    "\u{1F624}",
340    "\u{1F625}",
341    "\u{1F628}",
342    "\u{1F629}",
343    "\u{1F62A}",
344    "\u{1F62B}",
345    "\u{1F62D}",
346    "\u{1F630}",
347    "\u{1F631}",
348    "\u{1F632}",
349    "\u{1F633}",
350    "\u{1F635}",
351    "\u{1F637}",
352    "\u{1F638}",
353    "\u{1F639}",
354    "\u{1F63A}",
355    "\u{1F63B}",
356    "\u{1F63C}",
357    "\u{1F63D}",
358    "\u{1F63E}",
359    "\u{1F63F}",
360    "\u{1F640}",
361    "\u{1F645}",
362    "\u{1F646}",
363    "\u{1F647}",
364    "\u{1F648}",
365    "\u{1F649}",
366    "\u{1F64A}",
367    "\u{1F64B}",
368    "\u{1F64C}",
369    "\u{1F64D}",
370    "\u{1F64E}",
371    "\u{1F64F}",
372    "\u{1F40C}",
373    "\u{1F40D}",
374    "\u{1F40E}",
375    "\u{1F414}",
376    "\u{1F417}",
377    "\u{1F418}",
378    "\u{1F419}",
379    "\u{1F41A}",
380    "\u{1F41B}",
381    "\u{1F41C}",
382    "\u{1F41D}",
383    "\u{1F41E}",
384    "\u{1F41F}",
385    "\u{1F420}",
386    "\u{1F421}",
387    "\u{1F422}",
388    "\u{1F423}",
389    "\u{1F424}",
390    "\u{1F425}",
391    "\u{1F426}",
392    "\u{1F427}",
393    "\u{1F428}",
394    "\u{1F429}",
395    "\u{1F42B}",
396    "\u{1F42C}",
397    "\u{1F42D}",
398    "\u{1F42E}",
399    "\u{1F42F}",
400    "\u{1F430}",
401    "\u{1F431}",
402    "\u{1F432}",
403    "\u{1F433}",
404    "\u{1F434}",
405    "\u{1F435}",
406    "\u{1F436}",
407    "\u{1F437}",
408    "\u{1F438}",
409    "\u{1F439}",
410    "\u{1F43A}",
411    "\u{1F43B}",
412    "\u{1F43C}",
413    "\u{1F43D}",
414    "\u{1F43E}",
415    "\u{1F340}",
416    "\u{1F341}",
417    "\u{1F342}",
418    "\u{1F343}",
419    "\u{1F344}",
420    "\u{1F345}",
421    "\u{1F346}",
422    "\u{1F347}",
423    "\u{1F348}",
424    "\u{1F349}",
425    "\u{1F34A}",
426    "\u{1F34B}",
427    "\u{1F34C}",
428    "\u{1F34D}",
429    "\u{1F34E}",
430    "\u{1F34F}",
431    "\u{1F351}",
432    "\u{1F352}",
433    "\u{1F353}",
434    "\u{1F354}",
435    "\u{1F355}",
436    "\u{1F356}",
437    "\u{1F357}",
438    "\u{1F358}",
439    "\u{1F359}",
440    "\u{1F35A}",
441    "\u{1F35B}",
442    "\u{1F35C}",
443    "\u{1F35D}",
444    "\u{1F35E}",
445    "\u{1F35F}",
446    "\u{1F360}",
447    "\u{1F361}",
448    "\u{1F362}",
449    "\u{1F363}",
450    "\u{1F364}",
451    "\u{1F365}",
452    "\u{1F366}",
453    "\u{1F367}",
454    "\u{1F368}",
455    "\u{1F369}",
456    "\u{1F36A}",
457    "\u{1F36B}",
458    "\u{1F36C}",
459    "\u{1F36D}",
460    "\u{1F36E}",
461    "\u{1F36F}",
462    "\u{1F370}",
463    "\u{1F371}",
464    "\u{1F372}",
465    "\u{1F373}",
466    "\u{1F374}",
467    "\u{1F375}",
468    "\u{1F376}",
469    "\u{1F377}",
470    "\u{1F378}",
471    "\u{1F379}",
472    "\u{1F37A}",
473    "\u{1F37B}",
474    "\u{1F380}",
475    "\u{1F381}",
476    "\u{1F382}",
477    "\u{1F383}",
478    "\u{1F384}",
479    "\u{1F385}",
480    "\u{1F386}",
481    "\u{1F387}",
482    "\u{1F388}",
483    "\u{1F389}",
484    "\u{1F38A}",
485    "\u{1F38B}",
486    "\u{1F38C}",
487    "\u{1F38D}",
488    "\u{1F38E}",
489    "\u{1F38F}",
490    "\u{1F390}",
491    "\u{1F391}",
492    "\u{1F392}",
493    "\u{1F393}",
494    "\u{1F3A0}",
495    "\u{1F3A1}",
496    "\u{1F3A2}",
497    "\u{1F3A3}",
498    "\u{1F3A4}",
499    "\u{1F3A5}",
500    "\u{1F3A6}",
501    "\u{1F3A7}",
502    "\u{1F3A8}",
503    "\u{1F3A9}",
504    "\u{1F3AA}",
505    "\u{1F3AB}",
506    "\u{1F3AC}",
507    "\u{1F3AD}",
508    "\u{1F3AE}",
509    "\u{1F3AF}",
510    "\u{1F3B0}",
511    "\u{1F3B1}",
512    "\u{1F3B2}",
513    "\u{1F3B3}",
514    "\u{1F3B4}",
515    "\u{1F3B5}",
516    "\u{1F3B6}",
517    "\u{1F3B7}",
518    "\u{1F3B8}",
519    "\u{1F3B9}",
520    "\u{1F3BA}",
521    "\u{1F3BB}",
522    "\u{1F3BC}",
523    "\u{1F3BD}",
524    "\u{1F3BE}",
525    "\u{1F3BF}",
526    "\u{1F3C0}",
527    "\u{1F3C1}",
528    "\u{1F3C2}",
529    "\u{1F3C3}",
530    "\u{1F3C4}",
531    "\u{1F3C5}",
532    "\u{1F3C6}",
533    "\u{1F3C7}",
534    "\u{1F3C8}",
535    "\u{1F3C9}",
536    "\u{1F3CA}",
537    "\u{1F3E0}",
538    "\u{1F3E1}",
539    "\u{1F3E2}",
540    "\u{1F3E3}",
541    "\u{1F3E4}",
542    "\u{1F3E5}",
543    "\u{1F3E6}",
544    "\u{1F3E7}",
545    "\u{1F3E8}",
546    "\u{1F3E9}",
547    "\u{1F3EA}",
548    "\u{1F3EB}",
549    "\u{1F3EC}",
550    "\u{1F3ED}",
551    "\u{1F3EF}",
552    "\u{1F3F0}",
553    "\u{1F400}",
554    "\u{1F401}",
555    "\u{1F402}",
556    "\u{1F403}",
557    "\u{1F404}",
558    "\u{1F405}",
559    "\u{1F406}",
560    "\u{1F407}",
561    "\u{1F408}",
562    "\u{1F409}",
563    "\u{1F40A}",
564    "\u{1F40B}",
565    "\u{1F480}",
566    "\u{1F484}",
567    "\u{1F485}",
568    "\u{1F486}",
569    "\u{1F487}",
570    "\u{1F488}",
571    "\u{1F489}",
572    "\u{1F48A}",
573    "\u{1F48B}",
574    "\u{1F48C}",
575    "\u{1F48D}",
576    "\u{1F48E}",
577    "\u{1F48F}",
578    "\u{1F490}",
579    "\u{1F491}",
580    "\u{1F492}",
581    "\u{1F493}",
582    "\u{1F494}",
583    "\u{1F495}",
584    "\u{1F496}",
585    "\u{1F497}",
586    "\u{1F498}",
587    "\u{1F499}",
588    "\u{1F49A}",
589    "\u{1F49B}",
590    "\u{1F49C}",
591    "\u{1F49D}",
592    "\u{1F49E}",
593    "\u{1F49F}",
594    "\u{1F4A0}",
595    "\u{1F4A1}",
596    "\u{1F4A2}",
597    "\u{1F4A3}",
598    "\u{1F4A4}",
599    "\u{1F4A5}",
600    "\u{1F4A6}",
601    "\u{1F4A7}",
602    "\u{1F4A8}",
603    "\u{1F4A9}",
604    "\u{1F4AA}",
605    "\u{1F4AB}",
606    "\u{1F4AC}",
607    "\u{1F4AD}",
608    "\u{1F4AE}",
609    "\u{1F4AF}",
610    "\u{1F4B0}",
611    "\u{1F4B1}",
612    "\u{1F4B2}",
613    "\u{1F4B3}",
614    "\u{1F4B4}",
615    "\u{1F4B5}",
616    "\u{1F4B6}",
617    "\u{1F4B7}",
618    "\u{1F4B8}",
619    "\u{1F4B9}",
620    "\u{1F4BA}",
621    "\u{1F4BB}",
622    "\u{1F4BC}",
623    "\u{1F4BD}",
624    "\u{1F4BE}",
625    "\u{1F4BF}",
626    "\u{1F4C0}",
627    "\u{1F4C1}",
628    "\u{1F4C2}",
629    "\u{1F4C3}",
630    "\u{1F4C4}",
631    "\u{1F4C5}",
632    "\u{1F4C6}",
633    "\u{1F4C7}",
634    "\u{1F4C8}",
635    "\u{1F4C9}",
636    "\u{1F4CA}",
637    "\u{1F4CB}",
638    "\u{1F4CC}",
639    "\u{1F4CD}",
640    "\u{1F4CE}",
641    "\u{1F4CF}",
642    "\u{1F4D0}",
643    "\u{1F4D1}",
644    "\u{1F4D2}",
645];
646
647#[cfg(test)]
648mod tests {
649    use super::*;
650
651    fn test_key() -> [u8; 256] {
652        let mut k = [0u8; 256];
653        for (i, b) in k.iter_mut().enumerate() {
654            *b = (i * 7 + 3) as u8;
655        }
656        k
657    }
658
659    #[test]
660    fn message_round_trip_both_directions() {
661        let key = test_key();
662        let msg = b"hello secret chat, length divisible by four!".to_vec();
663        assert_eq!(msg.len() % 4, 0);
664
665        // Originator -> peer.
666        let blob = encrypt_message(&key, &msg, true).unwrap();
667        assert_eq!(decrypt_message(&key, &blob, false).unwrap(), msg);
668
669        // Peer -> originator.
670        let blob = encrypt_message(&key, &msg, false).unwrap();
671        assert_eq!(decrypt_message(&key, &blob, true).unwrap(), msg);
672    }
673
674    #[test]
675    fn wrong_direction_is_rejected() {
676        let key = test_key();
677        let blob = encrypt_message(&key, &[0u8; 16], true).unwrap();
678        assert!(decrypt_message(&key, &blob, true).is_err());
679    }
680
681    #[test]
682    fn tampering_is_rejected() {
683        let key = test_key();
684        let mut blob = encrypt_message(&key, &[1u8; 32], true).unwrap();
685        let last = blob.len() - 1;
686        blob[last] ^= 1;
687        assert!(matches!(
688            decrypt_message(&key, &blob, false),
689            Err(E2eError::DecryptionFailed)
690        ));
691    }
692
693    #[test]
694    fn wrong_key_fingerprint_is_rejected() {
695        let key = test_key();
696        let mut other = key;
697        other[0] ^= 0xff;
698        let blob = encrypt_message(&key, &[1u8; 32], true).unwrap();
699        assert!(matches!(
700            decrypt_message(&other, &blob, false),
701            Err(E2eError::KeyFingerprintMismatch)
702        ));
703    }
704
705    #[test]
706    fn short_blob_is_rejected() {
707        let key = test_key();
708        assert!(decrypt_message(&key, &[0u8; 23], false).is_err());
709    }
710
711    #[test]
712    fn padding_length_is_in_range() {
713        for len in 0..200 {
714            let pad = padding_len(len);
715            assert!((MIN_PADDING..=MAX_PADDING).contains(&pad));
716            assert_eq!((len + pad) % 16, 0);
717        }
718    }
719
720    #[test]
721    fn file_round_trip() {
722        let data = (0..1000u32).map(|i| i as u8).collect::<Vec<_>>();
723        let (key, iv, ct) = file_encrypt(&data);
724        assert_eq!(file_decrypt(&ct, &key, &iv, data.len()).unwrap(), data);
725        assert!(file_decrypt(&ct, &key[..16], &iv, data.len()).is_err());
726        assert!(file_decrypt(&ct, &key, &iv, ct.len() + 1).is_err());
727    }
728
729    #[test]
730    fn emoji_indices_are_in_table() {
731        for idx in emoji_fingerprint_indices(&test_key()) {
732            assert!(idx < EMOJI_FINGERPRINT_TABLE.len());
733        }
734    }
735}