signed-crypto 0.1.2

A Rust library for encrypted payloads with built-in integrity verification
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
// Copyright 2026, Kehan Pan, All rights reserved.
//
// Cryptographic scheme inspired by:
// https://github.com/google/openrtb-doubleclick/blob/master/doubleclick-core/src/main/java/com/google/doubleclick/crypto/DoubleClickCrypto.java

//! # signed-crypto
//!
//! A Rust library for encrypted payloads with built-in integrity verification.
//!
//! ## Package Format
//!
//! Encrypted payloads follow this structure:
//!
//! ```text
//! initVector:16 || E(payload:?) || I(signature:4)
//! ```
//!
//! where:
//! - `initVector` = `timestamp:8 || serverId:8`
//! - `E(payload)` = AES-256/CTR64 encryption with encryption key
//! - `I(signature)` = First 4 bytes of HMAC-SHA256(integrityKey, payload || initVector)
//!
//! ## Example
//!
//! ```rust
//! use signed_crypto::{Crypto, Keys};
//!
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! // WARNING: Never use all-zero keys in production!
//! // Generate secure random keys using a cryptographic RNG.
//! let keys = Keys::new(&[0u8; 32], &[0u8; 32])?;
//! let crypto = Crypto::new(keys);
//!
//! // Encrypt
//! let payload = b"Hello, world!";
//! let mut pkg = crypto.init_plain_data(payload.len(), None)?;
//! crypto.set_payload(&mut pkg, payload)?;
//! let encrypted = crypto.encrypt(&pkg)?;
//!
//! // Decrypt
//! let decrypted = crypto.decrypt(&encrypted)?;
//! assert_eq!(crypto.payload(&decrypted), Some(payload.as_slice()));
//! # Ok(())
//! # }
//! ```

use aes::cipher::{KeyIvInit, StreamCipher};
use base64::{engine::general_purpose::URL_SAFE, Engine as _};
use byteorder::{BigEndian, ByteOrder};
use hmac::{Hmac, Mac};
use sha2::Sha256;
use thiserror::Error;
use time::{Duration, OffsetDateTime};

type HmacSha256 = Hmac<Sha256>;
type Aes256Ctr64BE = ctr::Ctr64BE<aes::Aes256>;

const UNIX_EPOCH: OffsetDateTime = time::OffsetDateTime::UNIX_EPOCH;

/// Holds the encryption and integrity keys.
///
/// Both keys must be exactly 32 bytes (256 bits).
///
/// # Fields
///
/// * `encryption_key` - AES-256 encryption key
/// * `integrity_key` - HMAC-SHA256 integrity key
#[derive(Clone, Debug)]
pub struct Keys {
    /// AES-256 encryption key (32 bytes)
    pub encryption_key: [u8; 32],
    /// HMAC-SHA256 integrity key (32 bytes)
    pub integrity_key: [u8; 32],
}

impl Keys {
    /// Creates a new `Keys` instance from raw byte slices.
    ///
    /// Both keys must be exactly 32 bytes.
    ///
    /// # Errors
    ///
    /// Returns [`CryptoError::InvalidKey`] if either key is not 32 bytes.
    ///
    /// # Example
    ///
    /// ```rust
    /// use signed_crypto::Keys;
    ///
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// // WARNING: Never use all-zero keys in production!
    /// // Generate secure random keys using a cryptographic RNG.
    /// let enc_key = [0u8; 32];
    /// let int_key = [0u8; 32];
    /// let keys = Keys::new(&enc_key, &int_key)?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn new(encryption_key: &[u8], integrity_key: &[u8]) -> Result<Self, CryptoError> {
        let encryption_key: [u8; 32] = encryption_key
            .try_into()
            .map_err(|_| CryptoError::InvalidKey)?;
        let integrity_key: [u8; 32] = integrity_key
            .try_into()
            .map_err(|_| CryptoError::InvalidKey)?;

        Ok(Self {
            encryption_key,
            integrity_key,
        })
    }
}

/// Errors that can occur during cryptographic operations.
#[derive(Error, Debug)]
pub enum CryptoError {
    /// Key is not exactly 32 bytes.
    #[error("invalid key")]
    InvalidKey,
    /// HMAC signature verification failed.
    #[error("invalid signature")]
    InvalidSign,
    /// Initialization vector is invalid.
    #[error("invalid init vector")]
    InvalidInitVector,
    /// Data is too short to be a valid package.
    #[error("data too short")]
    DataTooShort,
    /// Payload size does not match expected size.
    #[error("payload size mismatch")]
    PayloadSizeMismatch,
    /// Base64 decoding failed.
    #[error("decode error: {0}")]
    DecodeError(#[from] base64::DecodeError),
}

/// Main cryptographic operations instance.
///
/// Holds the keys and provides methods for encryption, decryption,
/// and metadata extraction.
///
/// # Example
///
/// ```rust
/// use signed_crypto::{Crypto, Keys};
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// // WARNING: Never use all-zero keys in production!
/// let keys = Keys::new(&[0u8; 32], &[0u8; 32])?;
/// let crypto = Crypto::new(keys);
/// # Ok(())
/// # }
/// ```
pub struct Crypto {
    /// The encryption and integrity keys.
    pub keys: Keys,
}

impl Crypto {
    /// Creates a new `Crypto` instance.
    ///
    /// # Example
    ///
    /// ```rust
    /// use signed_crypto::{Crypto, Keys};
    ///
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// // WARNING: Never use all-zero keys in production!
    /// let keys = Keys::new(&[0u8; 32], &[0u8; 32])?;
    /// let crypto = Crypto::new(keys);
    /// # Ok(())
    /// # }
    /// ```
    pub fn new(keys: Keys) -> Self {
        Self { keys }
    }

    /// Offset of the initialization vector in a package.
    pub const IV_BASE: usize = 0;
    /// Size of the initialization vector in bytes.
    pub const IV_SIZE: usize = 16;
    /// Offset of the timestamp within the IV.
    pub const IV_TIME_OFFSET: usize = 0;
    /// Size of the timestamp in bytes.
    pub const IV_TIME_SIZE: usize = 8;
    /// Offset of the server ID within the IV.
    pub const IV_SERVER_ID_OFFSET: usize = 8;
    /// Size of the server ID in bytes.
    pub const IV_SERVER_ID_SIZE: usize = 8;
    /// Size of the HMAC signature in bytes.
    pub const SIGNATURE_SIZE: usize = 4;
    /// Offset where the payload begins.
    pub const PAYLOAD_BASE: usize = Crypto::IV_BASE + Crypto::IV_SIZE;
    /// Total overhead size (IV + signature) in bytes.
    pub const OVERHEAD_SIZE: usize = Crypto::IV_SIZE + Crypto::SIGNATURE_SIZE;

    /// Decodes a URL-safe Base64 encoded string.
    ///
    /// # Example
    ///
    /// ```rust
    /// use signed_crypto::{Crypto, Keys};
    ///
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// // WARNING: Never use all-zero keys in production!
    /// let crypto = Crypto::new(Keys::new(&[0u8; 32], &[0u8; 32])?);
    /// let encoded = "SGVsbG8=";
    /// let decoded = crypto.decode(encoded)?;
    /// # Ok(())
    /// # }
    /// ```
    #[inline]
    pub fn decode<T>(&self, data: T) -> Result<Vec<u8>, CryptoError>
    where
        T: AsRef<[u8]>,
    {
        URL_SAFE
            .decode(data)
            .map(|v| v.to_vec())
            .map_err(|e| e.into())
    }

    /// Encodes data as a URL-safe Base64 string.
    ///
    /// # Example
    ///
    /// ```rust
    /// use signed_crypto::{Crypto, Keys};
    ///
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// // WARNING: Never use all-zero keys in production!
    /// let crypto = Crypto::new(Keys::new(&[0u8; 32], &[0u8; 32])?);
    /// let data = b"Hello";
    /// let encoded = crypto.encode(data);
    /// # Ok(())
    /// # }
    /// ```
    #[inline]
    pub fn encode<T>(&self, data: T) -> String
    where
        T: AsRef<[u8]>,
    {
        URL_SAFE.encode(data)
    }

    /// Decrypts a package and verifies the HMAC signature.
    ///
    /// # Errors
    ///
    /// Returns [`CryptoError::InvalidSign`] if signature verification fails.
    ///
    /// # Example
    ///
    /// ```rust
    /// use signed_crypto::{Crypto, Keys};
    ///
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// // WARNING: Never use all-zero keys in production!
    /// let crypto = Crypto::new(Keys::new(&[0u8; 32], &[0u8; 32])?);
    /// let mut pkg = crypto.init_plain_data(5, None)?;
    /// crypto.set_payload(&mut pkg, b"Hello")?;
    /// let encrypted = crypto.encrypt(&pkg)?;
    /// let decrypted = crypto.decrypt(&encrypted)?;
    /// # Ok(())
    /// # }
    /// ```
    #[inline]
    pub fn decrypt(&self, cipher_data: &[u8]) -> Result<Vec<u8>, CryptoError> {
        if cipher_data.len() < Self::OVERHEAD_SIZE {
            return Err(CryptoError::DataTooShort);
        }

        let mut data = cipher_data.to_vec();
        let data_size = data.len();

        self.xor_payload(&mut data)?;

        let confirmation_signature = self.hmac_signature(&data)?;
        let integrity_signature = self.read_i32(&data, data_size - Self::SIGNATURE_SIZE);
        self.write_i32(
            &mut data,
            data_size - Self::SIGNATURE_SIZE,
            confirmation_signature,
        );

        if confirmation_signature != integrity_signature {
            return Err(CryptoError::InvalidSign);
        }

        Ok(data)
    }

    /// Encrypts a package in-place.
    ///
    /// # Example
    ///
    /// ```rust
    /// use signed_crypto::{Crypto, Keys};
    ///
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// // WARNING: Never use all-zero keys in production!
    /// let crypto = Crypto::new(Keys::new(&[0u8; 32], &[0u8; 32])?);
    /// let mut pkg = crypto.init_plain_data(5, None)?;
    /// crypto.set_payload(&mut pkg, b"Hello")?;
    /// let encrypted = crypto.encrypt(&pkg)?;
    /// # Ok(())
    /// # }
    /// ```
    #[inline]
    pub fn encrypt(&self, plain_data: &[u8]) -> Result<Vec<u8>, CryptoError> {
        if plain_data.len() < Self::OVERHEAD_SIZE {
            return Err(CryptoError::DataTooShort);
        }

        let mut data = plain_data.to_vec();
        let data_size = data.len();
        let signature = self.hmac_signature(&data)?;
        self.write_i32(&mut data, data_size - Self::SIGNATURE_SIZE, signature);

        self.xor_payload(&mut data)?;

        Ok(data)
    }

    /// Creates a custom initialization vector.
    ///
    /// # Arguments
    ///
    /// * `timestamp` - The timestamp to embed
    /// * `server_id` - The server ID to embed
    ///
    /// # Example
    ///
    /// ```rust
    /// use signed_crypto::{Crypto, Keys};
    /// use time::OffsetDateTime;
    ///
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let crypto = Crypto::new(Keys::new(&[0u8; 32], &[0u8; 32])?);
    /// let iv = crypto.create_init_vector(OffsetDateTime::now_utc(), 12345);
    /// # Ok(())
    /// # }
    /// ```
    #[inline]
    pub fn create_init_vector(&self, timestamp: OffsetDateTime, server_id: i64) -> Vec<u8> {
        let timestamp = (timestamp.unix_timestamp_nanos() / 1_000) as i64; // microseconds
        let mut iv = vec![0; Self::IV_SIZE];
        self.write_i64(&mut iv, Self::IV_TIME_OFFSET, timestamp);
        self.write_i64(&mut iv, Self::IV_SERVER_ID_OFFSET, server_id);
        iv
    }

    /// Extracts the timestamp from a package's initialization vector.
    ///
    /// Returns `None` if the data is too short.
    ///
    /// # Example
    ///
    /// ```rust
    /// use signed_crypto::{Crypto, Keys};
    /// use time::OffsetDateTime;
    ///
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let crypto = Crypto::new(Keys::new(&[0u8; 32], &[0u8; 32])?);
    /// let mut pkg = crypto.init_plain_data(5, None)?;
    /// crypto.set_payload(&mut pkg, b"Hello")?;
    /// let encrypted = crypto.encrypt(&pkg)?;
    /// let ts = crypto.timestamp(&encrypted).unwrap();
    /// # Ok(())
    /// # }
    /// ```
    #[inline]
    pub fn timestamp(&self, data: &[u8]) -> Option<OffsetDateTime> {
        if data.len() < Self::IV_SIZE {
            return None;
        }
        let ts = self.read_i64(data, Self::IV_BASE + Self::IV_TIME_OFFSET);
        Some(
            UNIX_EPOCH
                .checked_add(Duration::microseconds(ts))
                .unwrap_or(UNIX_EPOCH),
        )
    }

    /// Extracts the server ID from a package's initialization vector.
    ///
    /// Returns `None` if the data is too short.
    ///
    /// # Example
    ///
    /// ```rust
    /// use signed_crypto::{Crypto, Keys};
    ///
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// // WARNING: Never use all-zero keys in production!
    /// let crypto = Crypto::new(Keys::new(&[0u8; 32], &[0u8; 32])?);
    /// let mut pkg = crypto.init_plain_data(5, None)?;
    /// crypto.set_payload(&mut pkg, b"Hello")?;
    /// let encrypted = crypto.encrypt(&pkg)?;
    /// let server_id = crypto.server_id(&encrypted).unwrap();
    /// # Ok(())
    /// # }
    /// ```
    #[inline]
    pub fn server_id(&self, data: &[u8]) -> Option<i64> {
        if data.len() < Self::IV_SIZE {
            return None;
        }
        Some(self.read_i64(data, Self::IV_BASE + Self::IV_SERVER_ID_OFFSET))
    }

    /// Extracts the payload from a package without decryption.
    ///
    /// Returns `None` if the data is too short.
    ///
    /// # Example
    ///
    /// ```rust
    /// use signed_crypto::{Crypto, Keys};
    ///
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// // WARNING: Never use all-zero keys in production!
    /// let crypto = Crypto::new(Keys::new(&[0u8; 32], &[0u8; 32])?);
    /// let mut pkg = crypto.init_plain_data(5, None)?;
    /// crypto.set_payload(&mut pkg, b"Hello")?;
    /// let payload = crypto.payload(&pkg).unwrap();
    /// assert_eq!(payload, b"Hello");
    /// # Ok(())
    /// # }
    /// ```
    #[inline]
    pub fn payload<'a>(&self, data: &'a [u8]) -> Option<&'a [u8]> {
        if data.len() < Self::OVERHEAD_SIZE {
            return None;
        }
        Some(&data[Self::PAYLOAD_BASE..data.len() - Self::SIGNATURE_SIZE])
    }

    /// Initializes a plain data package buffer.
    ///
    /// If `iv` is `None`, generates a random IV with current timestamp.
    ///
    /// # Arguments
    ///
    /// * `payload_size` - Size of the payload in bytes
    /// * `iv` - Optional custom initialization vector
    ///
    /// # Example
    ///
    /// ```rust
    /// use signed_crypto::{Crypto, Keys};
    ///
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// // WARNING: Never use all-zero keys in production!
    /// let crypto = Crypto::new(Keys::new(&[0u8; 32], &[0u8; 32])?);
    /// let pkg = crypto.init_plain_data(10, None)?;
    /// # Ok(())
    /// # }
    /// ```
    #[inline]
    pub fn init_plain_data(
        &self,
        payload_size: usize,
        iv: Option<&[u8]>,
    ) -> Result<Vec<u8>, CryptoError> {
        let mut plain_data = vec![0; Self::OVERHEAD_SIZE + payload_size];
        if let Some(iv) = iv {
            plain_data[Self::IV_BASE..Self::IV_BASE + Self::IV_SIZE].copy_from_slice(iv);
        } else {
            let now = (OffsetDateTime::now_utc().unix_timestamp_nanos() / 1_000) as i64;
            self.write_i64(&mut plain_data, Self::IV_TIME_OFFSET, now);
            self.write_i64(
                &mut plain_data,
                Self::IV_SERVER_ID_OFFSET,
                rand::random::<i64>(),
            );
        }

        Ok(plain_data)
    }

    /// Sets the payload in a plain data package buffer.
    ///
    /// # Errors
    ///
    /// Returns [`CryptoError::PayloadSizeMismatch`] if the payload size
    /// does not match the expected size.
    ///
    /// # Example
    ///
    /// ```rust
    /// use signed_crypto::{Crypto, Keys};
    ///
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// // WARNING: Never use all-zero keys in production!
    /// let crypto = Crypto::new(Keys::new(&[0u8; 32], &[0u8; 32])?);
    /// let mut pkg = crypto.init_plain_data(5, None)?;
    /// crypto.set_payload(&mut pkg, b"Hello")?;
    /// # Ok(())
    /// # }
    /// ```
    #[inline]
    pub fn set_payload(&self, plain_data: &mut [u8], payload: &[u8]) -> Result<(), CryptoError> {
        if payload.len() != plain_data.len() - Self::OVERHEAD_SIZE {
            return Err(CryptoError::PayloadSizeMismatch);
        }
        plain_data[Self::PAYLOAD_BASE..Self::PAYLOAD_BASE + payload.len()].copy_from_slice(payload);
        Ok(())
    }

    #[inline]
    fn read_i32(&self, data: &[u8], offset: usize) -> i32 {
        BigEndian::read_i32(&data[offset..offset + 4])
    }

    #[inline]
    fn read_i64(&self, data: &[u8], offset: usize) -> i64 {
        BigEndian::read_i64(&data[offset..offset + 8])
    }

    #[inline]
    fn write_i32(&self, data: &mut [u8], offset: usize, value: i32) {
        BigEndian::write_i32(&mut data[offset..offset + 4], value);
    }

    #[inline]
    fn write_i64(&self, data: &mut [u8], offset: usize, value: i64) {
        BigEndian::write_i64(&mut data[offset..offset + 8], value);
    }

    #[inline]
    fn xor_payload(&self, data: &mut [u8]) -> Result<(), CryptoError> {
        let iv: &[u8; 16] = &data[Self::IV_BASE..Self::IV_BASE + Self::IV_SIZE]
            .try_into()
            .map_err(|_| CryptoError::InvalidInitVector)?;

        let mut cipher = Aes256Ctr64BE::new(&self.keys.encryption_key.into(), iv.into());
        let data_size = data.len();
        cipher.apply_keystream(&mut data[Self::PAYLOAD_BASE..data_size - Self::SIGNATURE_SIZE]);

        Ok(())
    }

    #[inline]
    fn hmac_signature(&self, data: &[u8]) -> Result<i32, CryptoError> {
        let mut mac = HmacSha256::new_from_slice(&self.keys.integrity_key)
            .map_err(|_| CryptoError::InvalidKey)?;

        mac.update(&data[Self::PAYLOAD_BASE..data.len() - Self::SIGNATURE_SIZE]);
        mac.update(&data[Self::IV_BASE..Self::IV_BASE + Self::IV_SIZE]);

        let b = mac.finalize().into_bytes();

        Ok(self.read_i32(&b, 0))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use base64::prelude::*;

    static TEST_ENCRYPTION_KEY: &str = "sIxwz7yw62yrfoLGt12lIHKuYrK/S5kLuApI2BQe7Ac=";
    static TEST_INTEGRITY_KEY: &str = "v3fsVcMBMMHYzRhi7SpM0sdqwzvAxM6KPTu9OtVod5I=";

    fn create_keys() -> Keys {
        Keys::new(
            &BASE64_STANDARD.decode(TEST_ENCRYPTION_KEY).unwrap(),
            &BASE64_STANDARD.decode(TEST_INTEGRITY_KEY).unwrap(),
        )
        .unwrap()
    }

    #[test]
    fn test_decode() {
        let crypto = Crypto::new(create_keys());
        let encoded = "aGVsbG8sIHdvcmxk";
        let decoded = crypto.decode(encoded).unwrap();
        assert_eq!(decoded, b"hello, world");
    }

    #[test]
    fn test_encode() {
        let crypto = Crypto::new(create_keys());
        let data = b"hello, world";
        let encoded = crypto.encode(data);
        assert_eq!(encoded, "aGVsbG8sIHdvcmxk");
    }

    #[test]
    fn test_decrypt() {
        let crypto = Crypto::new(create_keys());
        let timestamp = OffsetDateTime::UNIX_EPOCH + Duration::seconds(1);
        let iv = crypto.create_init_vector(timestamp, 123456789);
        let payload = "https://example.com".as_bytes();

        let mut plain_data = crypto.init_plain_data(payload.len(), Some(&iv)).unwrap();
        crypto.set_payload(&mut plain_data, payload).unwrap();
        let encrypted_data = crypto.encrypt(&plain_data).unwrap();

        assert_eq!(crypto.timestamp(&iv), Some(timestamp));
        assert_eq!(crypto.server_id(&iv), Some(123456789));
        assert_eq!(
            crypto.payload(&encrypted_data).unwrap().len(),
            payload.len()
        );
        assert_ne!(crypto.payload(&encrypted_data), Some(payload));

        let decrypted_data = crypto.decrypt(&encrypted_data).unwrap();
        assert_eq!(crypto.timestamp(&decrypted_data), Some(timestamp));
        assert_eq!(crypto.server_id(&decrypted_data), Some(123456789));
        assert_eq!(crypto.payload(&decrypted_data), Some(payload));

        let mut encrypted_data_invalid_sign = encrypted_data.clone();
        crypto.write_i32(
            &mut encrypted_data_invalid_sign,
            encrypted_data.len() - Crypto::SIGNATURE_SIZE,
            123456789,
        );
        assert!(matches!(
            crypto.decrypt(&encrypted_data_invalid_sign),
            Err(CryptoError::InvalidSign)
        ));
        assert_ne!(crypto.payload(&encrypted_data_invalid_sign), Some(payload))
    }

    #[test]
    fn test_create_init_vector() {
        let crypto = Crypto::new(create_keys());
        let timestamp = OffsetDateTime::UNIX_EPOCH + Duration::seconds(1);
        let iv = crypto.create_init_vector(timestamp, 123456789);
        assert_eq!(iv.len(), Crypto::IV_SIZE);
        assert_eq!(crypto.read_i64(&iv, Crypto::IV_TIME_OFFSET), 1_000_000);
        assert_eq!(crypto.read_i64(&iv, Crypto::IV_SERVER_ID_OFFSET), 123456789);
        assert_eq!(crypto.timestamp(&iv), Some(timestamp));
        assert_eq!(crypto.server_id(&iv), Some(123456789));
    }

    #[test]
    fn test_init_plain_data() {
        let crypto = Crypto::new(create_keys());
        let payload = "https://example.com".as_bytes();

        let mut plain_data = crypto.init_plain_data(payload.len(), None).unwrap();
        crypto.set_payload(&mut plain_data, payload).unwrap();

        assert_eq!(plain_data.len(), Crypto::OVERHEAD_SIZE + payload.len());
        assert_eq!(crypto.payload(&plain_data), Some(payload));
    }

    #[test]
    fn test_init_plain_data_empty_payload() {
        let crypto = Crypto::new(create_keys());
        let payload = "".as_bytes();

        let mut plain_data = crypto.init_plain_data(0, None).unwrap();
        crypto.set_payload(&mut plain_data, payload).unwrap();
        assert_eq!(crypto.payload(&plain_data), Some(payload));
    }
}