Skip to main content

keep_core/
crypto.rs

1// SPDX-FileCopyrightText: © 2026 PrivKey LLC
2// SPDX-License-Identifier: MIT
3
4//! Cryptographic primitives for key derivation, encryption, and hashing.
5//!
6//! This module provides:
7//! - Argon2id key derivation with configurable parameters
8//! - XChaCha20-Poly1305 authenticated encryption
9//! - Blake2b-256 hashing
10//! - Memory-locked types for sensitive data
11
12#![deny(unsafe_code)]
13
14use argon2::{Algorithm, Argon2, Params, Version};
15use blake2::{Blake2b512, Digest};
16use chacha20poly1305::{
17    aead::{Aead, KeyInit},
18    XChaCha20Poly1305, XNonce,
19};
20use memsecurity::EncryptedMem;
21use zeroize::{Zeroize, Zeroizing};
22
23use crate::entropy;
24use crate::error::{CryptoError, KeepError, Result};
25
26use std::sync::atomic::{AtomicBool, Ordering};
27
28static MLOCK_DISABLED: AtomicBool = AtomicBool::new(false);
29static MLOCK_WARNING_SHOWN: AtomicBool = AtomicBool::new(false);
30
31/// Globally disable memory locking for the process.
32///
33/// When disabled, secret keys will not be locked in memory (mlock),
34/// which means they may be paged to disk. This is useful in container
35/// environments where mlock may not be available.
36pub fn disable_mlock() {
37    MLOCK_DISABLED.store(true, Ordering::SeqCst);
38}
39
40fn warn_once() {
41    if !MLOCK_WARNING_SHOWN.swap(true, Ordering::SeqCst) {
42        tracing::warn!(
43            "Failed to lock memory. Secrets may be paged to disk. \
44             To fix: ulimit -l unlimited (or increase RLIMIT_MEMLOCK)"
45        );
46    }
47}
48
49#[allow(unsafe_code)]
50fn try_mlock(ptr: *mut u8, len: usize) -> bool {
51    if MLOCK_DISABLED.load(Ordering::SeqCst) {
52        return false;
53    }
54    let locked = unsafe { memsec::mlock(ptr, len) };
55    if !locked {
56        warn_once();
57    }
58    locked
59}
60
61#[allow(unsafe_code)]
62mod mlock {
63    use super::try_mlock;
64    use std::alloc::{alloc_zeroed, dealloc, Layout};
65    use std::ptr::NonNull;
66    use zeroize::Zeroize;
67
68    /// Fixed-size memory-locked byte array.
69    ///
70    /// The contents are locked in memory to prevent swapping and
71    /// automatically zeroized when dropped.
72    pub struct MlockedBox<const N: usize> {
73        ptr: NonNull<[u8; N]>,
74        locked: bool,
75    }
76
77    impl<const N: usize> MlockedBox<N> {
78        /// Creates a new mlocked box from a mutable reference, zeroing the source.
79        ///
80        /// The source data is copied into mlocked memory and then immediately
81        /// zeroed to prevent secrets from remaining on the stack.
82        pub fn new(data: &mut [u8; N]) -> Self {
83            let layout = Layout::new::<[u8; N]>();
84            let raw_ptr = unsafe { alloc_zeroed(layout) as *mut [u8; N] };
85            let ptr =
86                NonNull::new(raw_ptr).unwrap_or_else(|| std::alloc::handle_alloc_error(layout));
87
88            unsafe { std::ptr::copy_nonoverlapping(data.as_ptr(), ptr.as_ptr() as *mut u8, N) };
89            data.zeroize();
90
91            let locked = try_mlock(ptr.as_ptr() as *mut u8, N);
92            Self { ptr, locked }
93        }
94
95        /// Returns true if the memory is successfully locked.
96        #[allow(dead_code)]
97        pub fn is_locked(&self) -> bool {
98            self.locked
99        }
100    }
101
102    impl<const N: usize> std::ops::Deref for MlockedBox<N> {
103        type Target = [u8; N];
104
105        fn deref(&self) -> &Self::Target {
106            // SAFETY: ptr is guaranteed non-null by NonNull and valid by construction
107            unsafe { self.ptr.as_ref() }
108        }
109    }
110
111    impl<const N: usize> std::ops::DerefMut for MlockedBox<N> {
112        fn deref_mut(&mut self) -> &mut Self::Target {
113            // SAFETY: ptr is guaranteed non-null by NonNull and valid by construction,
114            // and we have exclusive access via &mut self
115            unsafe { self.ptr.as_mut() }
116        }
117    }
118
119    impl<const N: usize> Drop for MlockedBox<N> {
120        fn drop(&mut self) {
121            // SAFETY: ptr is guaranteed valid by construction, and we own the allocation
122            unsafe {
123                memsec::memzero(self.ptr.as_ptr() as *mut u8, N);
124                if self.locked {
125                    memsec::munlock(self.ptr.as_ptr() as *mut u8, N);
126                }
127                dealloc(self.ptr.as_ptr() as *mut u8, Layout::new::<[u8; N]>());
128            }
129        }
130    }
131
132    impl<const N: usize> Zeroize for MlockedBox<N> {
133        fn zeroize(&mut self) {
134            // SAFETY: ptr is guaranteed valid by construction
135            unsafe { memsec::memzero(self.ptr.as_ptr() as *mut u8, N) };
136        }
137    }
138
139    // SAFETY: MlockedBox owns its data exclusively (like Box<T>).
140    // NonNull<T> is covariant over T and the data is heap-allocated.
141    // The type is safe to send/share because it doesn't contain any thread-local
142    // state, and all operations on the inner data require &mut self for mutation.
143    unsafe impl<const N: usize> Send for MlockedBox<N> {}
144    unsafe impl<const N: usize> Sync for MlockedBox<N> {}
145
146    /// Variable-size memory-locked byte vector.
147    ///
148    /// The contents are locked in memory to prevent swapping and
149    /// automatically zeroized when dropped.
150    pub struct MlockedVec {
151        ptr: NonNull<u8>,
152        len: usize,
153        capacity: usize,
154        locked: bool,
155    }
156
157    impl MlockedVec {
158        /// Creates a new mlocked vec, taking ownership and locking the memory.
159        ///
160        /// Note: The Vec's memory is locked in place. The original allocation
161        /// is preserved (not copied), so this is efficient for large data.
162        pub fn new(mut data: Vec<u8>) -> Self {
163            let len = data.len();
164            let capacity = data.capacity();
165
166            if capacity == 0 {
167                return Self {
168                    ptr: NonNull::dangling(),
169                    len: 0,
170                    capacity: 0,
171                    locked: false,
172                };
173            }
174
175            let raw_ptr = data.as_mut_ptr();
176            std::mem::forget(data);
177
178            // SAFETY: Vec guarantees a valid, non-null pointer for non-zero capacity.
179            let ptr = NonNull::new(raw_ptr).expect("non-zero capacity Vec had null pointer");
180            let locked = try_mlock(ptr.as_ptr(), capacity);
181
182            Self {
183                ptr,
184                len,
185                capacity,
186                locked,
187            }
188        }
189
190        /// Returns true if the memory is successfully locked.
191        #[allow(dead_code)]
192        pub fn is_locked(&self) -> bool {
193            self.locked
194        }
195
196        /// Returns a slice view of the locked data.
197        pub fn as_slice(&self) -> &[u8] {
198            // SAFETY: ptr and len are valid from Vec construction
199            unsafe { std::slice::from_raw_parts(self.ptr.as_ptr(), self.len) }
200        }
201    }
202
203    impl Drop for MlockedVec {
204        fn drop(&mut self) {
205            if self.capacity == 0 {
206                return;
207            }
208            // SAFETY: ptr is valid and we own the allocation from the original Vec
209            unsafe {
210                memsec::memzero(self.ptr.as_ptr(), self.capacity);
211                if self.locked {
212                    memsec::munlock(self.ptr.as_ptr(), self.capacity);
213                }
214                let _ = Vec::from_raw_parts(self.ptr.as_ptr(), 0, self.capacity);
215            }
216        }
217    }
218
219    impl Zeroize for MlockedVec {
220        fn zeroize(&mut self) {
221            if self.capacity > 0 {
222                // SAFETY: ptr is valid for capacity bytes
223                unsafe { memsec::memzero(self.ptr.as_ptr(), self.capacity) };
224            }
225        }
226    }
227
228    // SAFETY: MlockedVec owns its data exclusively (like Vec<T>).
229    // NonNull<u8> is used for the heap allocation which we own.
230    // The type is safe to send/share because it doesn't contain any thread-local
231    // state, and the inner data is only accessed via &self methods.
232    unsafe impl Send for MlockedVec {}
233    unsafe impl Sync for MlockedVec {}
234}
235
236pub use mlock::{MlockedBox, MlockedVec};
237
238/// Salt size for key derivation.
239pub const SALT_SIZE: usize = 32;
240
241/// Variable-length secret stored encrypted in RAM.
242pub struct SecretVec {
243    encrypted: EncryptedMem,
244}
245
246#[allow(missing_docs)]
247impl SecretVec {
248    pub fn new(mut data: Vec<u8>) -> Result<Self> {
249        let mut encrypted = EncryptedMem::new();
250        encrypted
251            .encrypt(&data)
252            .map_err(|_| CryptoError::encryption("encrypt secret in RAM"))?;
253        data.zeroize();
254        Ok(Self { encrypted })
255    }
256
257    pub fn as_slice(&self) -> Result<Zeroizing<Vec<u8>>> {
258        self.encrypted
259            .decrypt()
260            .map(|z| Zeroizing::new(z.expose_borrowed().to_vec()))
261            .map_err(|_| CryptoError::decryption("decrypt secret from RAM").into())
262    }
263}
264
265/// XChaCha20-Poly1305 nonce size.
266pub const NONCE_SIZE: usize = 24;
267/// Encryption key size.
268pub const KEY_SIZE: usize = 32;
269/// Authentication tag size.
270pub const TAG_SIZE: usize = 16;
271
272/// Parameters for Argon2id key derivation.
273#[derive(Clone, Copy)]
274pub struct Argon2Params {
275    /// Memory cost in KiB.
276    pub memory_kib: u32,
277    /// Number of iterations.
278    pub iterations: u32,
279    /// Degree of parallelism.
280    pub parallelism: u32,
281}
282
283impl Argon2Params {
284    /// Fast parameters for testing only. Do not use in production.
285    #[cfg(any(test, feature = "testing"))]
286    pub const TESTING: Self = Self {
287        memory_kib: 1024,
288        iterations: 1,
289        parallelism: 1,
290    };
291
292    /// Default parameters (256 MiB memory, 4 iterations).
293    pub const DEFAULT: Self = Self {
294        memory_kib: 256 * 1024,
295        iterations: 4,
296        parallelism: 4,
297    };
298
299    /// High security parameters (512 MiB memory, 6 iterations).
300    pub const HIGH: Self = Self {
301        memory_kib: 512 * 1024,
302        iterations: 6,
303        parallelism: 4,
304    };
305}
306
307impl Default for Argon2Params {
308    fn default() -> Self {
309        Self::DEFAULT
310    }
311}
312
313/// A 32-byte encryption key stored encrypted in RAM.
314pub struct SecretKey {
315    encrypted: EncryptedMem,
316}
317
318#[allow(missing_docs)]
319impl SecretKey {
320    pub fn new(mut bytes: [u8; KEY_SIZE]) -> Result<Self> {
321        let mut encrypted = EncryptedMem::new();
322        encrypted
323            .encrypt(&bytes)
324            .map_err(|_| CryptoError::encryption("encrypt key in RAM"))?;
325        bytes.zeroize();
326        Ok(Self { encrypted })
327    }
328
329    pub fn generate() -> Result<Self> {
330        let bytes: [u8; KEY_SIZE] = entropy::try_random_bytes()?;
331        Self::new(bytes)
332    }
333
334    pub fn decrypt(&self) -> Result<MlockedBox<KEY_SIZE>> {
335        let decrypted = self
336            .encrypted
337            .decrypt_32byte()
338            .map_err(|_| CryptoError::decryption("decrypt key"))?;
339        let mut bytes = *decrypted.expose_borrowed();
340        Ok(MlockedBox::new(&mut bytes))
341    }
342
343    pub fn from_slice(slice: &[u8]) -> Result<Self> {
344        if slice.len() != KEY_SIZE {
345            return Err(CryptoError::invalid_key("invalid key length").into());
346        }
347        // Zeroize the staging buffer: `Self::new` wipes its own by-value copy, but this local would
348        // otherwise linger un-zeroized in the stack frame after the call.
349        let mut bytes = Zeroizing::new([0u8; KEY_SIZE]);
350        bytes.copy_from_slice(slice);
351        Self::new(*bytes)
352    }
353
354    pub fn try_clone(&self) -> Result<Self> {
355        let decrypted = self.decrypt()?;
356        Self::new(*decrypted)
357    }
358}
359
360impl Clone for SecretKey {
361    fn clone(&self) -> Self {
362        self.try_clone()
363            .expect("SecretKey clone failed: RAM encryption invariant violated")
364    }
365}
366
367/// Derive an encryption key from a password using Argon2id.
368pub fn derive_key(
369    password: &[u8],
370    salt: &[u8; SALT_SIZE],
371    params: Argon2Params,
372) -> Result<SecretKey> {
373    let argon2_params = Params::new(
374        params.memory_kib,
375        params.iterations,
376        params.parallelism,
377        Some(KEY_SIZE),
378    )
379    .map_err(|e| CryptoError::kdf(format!("argon2 params: {e}")))?;
380
381    let argon2 = Argon2::new(Algorithm::Argon2id, Version::V0x13, argon2_params);
382
383    let mut output = [0u8; KEY_SIZE];
384    argon2
385        .hash_password_into(password, salt, &mut output)
386        .map_err(|e| CryptoError::kdf(format!("argon2: {e}")))?;
387
388    SecretKey::new(output)
389}
390
391/// Derive a subkey from a master key using domain separation.
392pub fn derive_subkey(master_key: &SecretKey, context: &[u8]) -> Result<SecretKey> {
393    let decrypted = master_key.decrypt()?;
394    let mut hasher = Blake2b512::new();
395    hasher.update(*decrypted);
396    hasher.update(context);
397    let result = hasher.finalize();
398
399    let mut output = [0u8; KEY_SIZE];
400    output.copy_from_slice(&result[..KEY_SIZE]);
401    SecretKey::new(output)
402}
403
404/// Encrypted data with nonce for authenticated decryption.
405#[derive(Clone)]
406pub struct EncryptedData {
407    /// The encrypted ciphertext with authentication tag.
408    pub ciphertext: Vec<u8>,
409    /// The nonce used for encryption.
410    pub nonce: [u8; NONCE_SIZE],
411}
412
413impl EncryptedData {
414    /// Serialize to bytes: nonce || ciphertext.
415    pub fn to_bytes(&self) -> Vec<u8> {
416        let mut result = Vec::with_capacity(NONCE_SIZE + self.ciphertext.len());
417        result.extend_from_slice(&self.nonce);
418        result.extend_from_slice(&self.ciphertext);
419        result
420    }
421
422    /// Deserialize from bytes: nonce || ciphertext.
423    pub fn from_bytes(bytes: &[u8]) -> Result<Self> {
424        if bytes.len() < NONCE_SIZE + TAG_SIZE {
425            return Err(CryptoError::decryption("encrypted data too short").into());
426        }
427
428        let mut nonce = [0u8; NONCE_SIZE];
429        nonce.copy_from_slice(&bytes[..NONCE_SIZE]);
430
431        Ok(Self {
432            nonce,
433            ciphertext: bytes[NONCE_SIZE..].to_vec(),
434        })
435    }
436}
437
438/// Encrypt plaintext using XChaCha20-Poly1305.
439pub fn encrypt(plaintext: &[u8], key: &SecretKey) -> Result<EncryptedData> {
440    encrypt_with_aad(plaintext, &[], key)
441}
442
443/// Decrypt ciphertext using XChaCha20-Poly1305.
444pub fn decrypt(encrypted: &EncryptedData, key: &SecretKey) -> Result<SecretVec> {
445    decrypt_with_aad(encrypted, &[], key)
446}
447
448/// Encrypt plaintext using XChaCha20-Poly1305 with additional authenticated data.
449///
450/// The `aad` is authenticated but not encrypted; decryption fails unless the
451/// same `aad` is supplied. Passing an empty slice is byte-identical to [`encrypt`].
452pub fn encrypt_with_aad(plaintext: &[u8], aad: &[u8], key: &SecretKey) -> Result<EncryptedData> {
453    use chacha20poly1305::aead::Payload;
454
455    let decrypted = key.decrypt()?;
456    let cipher = XChaCha20Poly1305::new_from_slice(&*decrypted)
457        .map_err(|_| KeepError::Encryption("Encryption failed".into()))?;
458
459    let nonce: [u8; NONCE_SIZE] = entropy::try_random_bytes()?;
460
461    let ciphertext = cipher
462        .encrypt(
463            &XNonce::from(nonce),
464            Payload {
465                msg: plaintext,
466                aad,
467            },
468        )
469        .map_err(|_| KeepError::Encryption("Encryption failed".into()))?;
470
471    Ok(EncryptedData { ciphertext, nonce })
472}
473
474/// Decrypt ciphertext using XChaCha20-Poly1305 with additional authenticated data.
475///
476/// Passing an empty `aad` slice is byte-identical to [`decrypt`].
477pub fn decrypt_with_aad(
478    encrypted: &EncryptedData,
479    aad: &[u8],
480    key: &SecretKey,
481) -> Result<SecretVec> {
482    use chacha20poly1305::aead::Payload;
483
484    let decrypted_key = key.decrypt()?;
485    let cipher = XChaCha20Poly1305::new_from_slice(&*decrypted_key)
486        .map_err(|_| KeepError::DecryptionFailed)?;
487
488    let plaintext = cipher
489        .decrypt(
490            &XNonce::from(encrypted.nonce),
491            Payload {
492                msg: encrypted.ciphertext.as_ref(),
493                aad,
494            },
495        )
496        .map_err(|_| KeepError::DecryptionFailed)?;
497
498    SecretVec::new(plaintext)
499}
500
501/// Compute Blake2b-256 hash of data.
502pub fn blake2b_256(data: &[u8]) -> [u8; 32] {
503    let mut hasher = Blake2b512::new();
504    hasher.update(data);
505    let result = hasher.finalize();
506
507    let mut output = [0u8; 32];
508    output.copy_from_slice(&result[..32]);
509    output
510}
511
512/// HMAC-SHA256 of `data` keyed by `key`. Keyed so the output is a MAC (forgeable
513/// only with the key), used for tamper-evident hash chains such as the NIP-55
514/// signing-audit log. Accepts a key of any length (HMAC pads/hashes as needed).
515pub fn hmac_sha256(key: &[u8], data: &[u8]) -> [u8; 32] {
516    use hmac::digest::KeyInit;
517    use hmac::{Hmac, Mac};
518    use sha2::Sha256;
519
520    let mut mac =
521        <Hmac<Sha256> as KeyInit>::new_from_slice(key).expect("HMAC accepts keys of any length");
522    mac.update(data);
523    let result = mac.finalize().into_bytes();
524
525    let mut output = [0u8; 32];
526    output.copy_from_slice(&result);
527    output
528}
529
530/// Generate cryptographically secure random bytes.
531pub fn random_bytes<const N: usize>() -> [u8; N] {
532    entropy::random_bytes()
533}
534
535/// Generate cryptographically secure random bytes, returning an error instead
536/// of panicking if the RNG health check fails. Preferred over [`random_bytes`]
537/// in key/secret generation paths that can propagate a `Result` (#685).
538pub fn try_random_bytes<const N: usize>() -> Result<[u8; N]> {
539    Ok(entropy::try_random_bytes()?)
540}
541
542/// NIP-44 encryption using a raw ECDH shared secret.
543///
544/// This module implements NIP-44 v2 encryption/decryption for use with
545/// threshold ECDH, where the shared secret is computed via distributed
546/// key operations rather than from a single private key.
547pub mod nip44 {
548    use chacha20::cipher::StreamCipher;
549    use chacha20::{ChaCha20, KeyIvInit, XChaCha20};
550    use hkdf::Hkdf;
551    use hmac::digest::KeyInit;
552    use hmac::{Hmac, Mac};
553    use sha2::Sha256;
554
555    use super::{entropy, CryptoError, Result};
556    use zeroize::Zeroizing;
557
558    const NIP44_SALT: &[u8] = b"nip44-v2";
559    #[allow(dead_code)]
560    const MIN_PLAINTEXT_SIZE: usize = 1;
561    const MAX_PLAINTEXT_SIZE: usize = 65535;
562
563    fn derive_conversation_key(shared_secret: &[u8; 32]) -> Result<Zeroizing<[u8; 32]>> {
564        let hk = Hkdf::<Sha256>::new(Some(NIP44_SALT), shared_secret);
565        let mut key = Zeroizing::new([0u8; 32]);
566        hk.expand(b"", key.as_mut())
567            .map_err(|_| CryptoError::kdf("NIP-44 conversation key derivation failed"))?;
568        Ok(key)
569    }
570
571    #[allow(clippy::type_complexity)]
572    fn derive_message_keys(
573        conversation_key: &[u8; 32],
574        nonce: &[u8; 32],
575    ) -> Result<(Zeroizing<[u8; 32]>, [u8; 32], Zeroizing<[u8; 32]>)> {
576        let hk = Hkdf::<Sha256>::new(Some(nonce), conversation_key);
577        let mut keys = Zeroizing::new([0u8; 96]);
578        hk.expand(b"nip44-v2", keys.as_mut())
579            .map_err(|_| CryptoError::kdf("NIP-44 message key derivation failed"))?;
580
581        let mut chacha_key = Zeroizing::new([0u8; 32]);
582        let mut chacha_nonce = [0u8; 32];
583        let mut hmac_key = Zeroizing::new([0u8; 32]);
584        chacha_key.copy_from_slice(&keys[0..32]);
585        chacha_nonce.copy_from_slice(&keys[32..64]);
586        hmac_key.copy_from_slice(&keys[64..96]);
587
588        Ok((chacha_key, chacha_nonce, hmac_key))
589    }
590
591    fn pad_plaintext(plaintext: &[u8]) -> Result<Vec<u8>> {
592        if plaintext.is_empty() || plaintext.len() > MAX_PLAINTEXT_SIZE {
593            return Err(CryptoError::encryption("Plaintext size out of range").into());
594        }
595
596        let len = plaintext.len();
597        let padded_len = calc_padded_len(len);
598        let mut padded = vec![0u8; 2 + padded_len];
599        padded[0] = (len >> 8) as u8;
600        padded[1] = (len & 0xff) as u8;
601        padded[2..2 + len].copy_from_slice(plaintext);
602        Ok(padded)
603    }
604
605    fn unpad_plaintext(padded: &[u8]) -> Result<Vec<u8>> {
606        if padded.len() < 2 {
607            return Err(CryptoError::decryption("Padded data too short").into());
608        }
609
610        let len = ((padded[0] as usize) << 8) | (padded[1] as usize);
611        if len == 0 || len > MAX_PLAINTEXT_SIZE || 2 + len > padded.len() {
612            return Err(CryptoError::decryption("Invalid plaintext length").into());
613        }
614
615        Ok(padded[2..2 + len].to_vec())
616    }
617
618    fn calc_padded_len(unpadded_len: usize) -> usize {
619        if unpadded_len <= 32 {
620            return 32;
621        }
622        let next_power = (unpadded_len as f64).log2().ceil() as u32;
623        let chunk = 2_usize.pow(next_power.max(5) - 5);
624        chunk * unpadded_len.div_ceil(chunk)
625    }
626
627    /// Encrypt plaintext using NIP-44 v2 with a raw ECDH shared secret.
628    ///
629    /// Returns the encrypted payload as raw bytes (version + nonce + ciphertext + MAC).
630    pub fn encrypt(shared_secret: &[u8; 32], plaintext: &[u8]) -> Result<Vec<u8>> {
631        let conversation_key = derive_conversation_key(shared_secret)?;
632        let nonce: [u8; 32] = entropy::try_random_bytes()?;
633        let (chacha_key, chacha_nonce, hmac_key) = derive_message_keys(&conversation_key, &nonce)?;
634
635        let padded = pad_plaintext(plaintext)?;
636
637        let mut ciphertext = padded;
638        let mut cipher = XChaCha20::new(
639            (&*chacha_key).into(),
640            <&[u8; 24]>::try_from(&chacha_nonce[..24])
641                .expect("chacha_nonce is 32 bytes; first 24 always valid")
642                .into(),
643        );
644        cipher.apply_keystream(&mut ciphertext);
645
646        let mut mac = <Hmac<Sha256> as KeyInit>::new_from_slice(hmac_key.as_ref())
647            .map_err(|_| CryptoError::encryption("Failed to create HMAC"))?;
648        mac.update(&nonce);
649        mac.update(&ciphertext);
650        let tag = mac.finalize().into_bytes();
651
652        let version = 2u8;
653        let mut result = Vec::with_capacity(1 + 32 + ciphertext.len() + 32);
654        result.push(version);
655        result.extend_from_slice(&nonce);
656        result.extend_from_slice(&ciphertext);
657        result.extend_from_slice(&tag);
658
659        Ok(result)
660    }
661
662    /// Decrypt a NIP-44 v2 payload using a raw ECDH shared secret.
663    ///
664    /// Takes the encrypted payload as raw bytes and returns the plaintext.
665    pub fn decrypt(shared_secret: &[u8; 32], payload: &[u8]) -> Result<Vec<u8>> {
666        if payload.len() < 1 + 32 + 2 + 32 {
667            return Err(CryptoError::decryption("Payload too short").into());
668        }
669
670        let version = payload[0];
671        if version != 2 {
672            return Err(CryptoError::decryption("Unsupported NIP-44 version").into());
673        }
674
675        let nonce: [u8; 32] = payload[1..33]
676            .try_into()
677            .map_err(|_| CryptoError::decryption("Invalid nonce"))?;
678
679        let ciphertext = &payload[33..payload.len() - 32];
680        let expected_tag: [u8; 32] = payload[payload.len() - 32..]
681            .try_into()
682            .map_err(|_| CryptoError::decryption("Invalid tag"))?;
683
684        let conversation_key = derive_conversation_key(shared_secret)?;
685        let (chacha_key, chacha_nonce, hmac_key) = derive_message_keys(&conversation_key, &nonce)?;
686
687        let mut mac = <Hmac<Sha256> as KeyInit>::new_from_slice(hmac_key.as_ref())
688            .map_err(|_| CryptoError::decryption("Failed to create HMAC"))?;
689        mac.update(&nonce);
690        mac.update(ciphertext);
691        mac.verify_slice(&expected_tag)
692            .map_err(|_| CryptoError::decryption("HMAC verification failed"))?;
693
694        let mut plaintext = ciphertext.to_vec();
695        let mut cipher = XChaCha20::new(
696            (&*chacha_key).into(),
697            <&[u8; 24]>::try_from(&chacha_nonce[..24])
698                .expect("chacha_nonce is 32 bytes; first 24 always valid")
699                .into(),
700        );
701        cipher.apply_keystream(&mut plaintext);
702
703        unpad_plaintext(&plaintext)
704    }
705
706    // --- NIP-44 v3 (nostr-land/nip44v3 draft): kind/scope-aware ---
707    //
708    // Differs from v2: keys are derived per-message with the salt
709    // `"nip44-v3\0" || nonce`, ChaCha20 (IETF 96-bit zero nonce) replaces
710    // XChaCha20, and a decryptor-supplied (kind, scope) context is authenticated
711    // alongside the ciphertext so a payload cannot be replayed in a different
712    // context. Raw payload (pre-base64):
713    //   0x03 | nonce(32) | mac(32) | kind(u32be) | scope_len(u32be) | scope | ciphertext
714    const NIP44_V3_VERSION: u8 = 0x03;
715    const NIP44_V3_SALT_PREFIX: &[u8] = b"nip44-v3\x00";
716    // version + nonce(32) + mac(32) + kind(4) + scope_len(4) + min ciphertext(4)
717    const NIP44_V3_MIN_PAYLOAD: usize = 1 + 32 + 32 + 4 + 4 + 4;
718    const NIP44_V3_MIN_PADDING: u64 = 32;
719    const NIP44_V3_PAD_THRESHOLD: u64 = 32768;
720    // The draft uses a u32 length prefix; cap plaintext at i32::MAX so the
721    // length fits the prefix without truncation and v3_target_size cannot
722    // overflow its shift, while still allowing payloads beyond v2's 65535 limit.
723    const NIP44_V3_MAX_PLAINTEXT: usize = i32::MAX as usize;
724
725    #[allow(clippy::type_complexity)]
726    fn v3_derive_keys(
727        shared_secret: &[u8; 32],
728        nonce: &[u8; 32],
729    ) -> Result<(Zeroizing<[u8; 32]>, Zeroizing<[u8; 32]>)> {
730        let mut salt = Vec::with_capacity(NIP44_V3_SALT_PREFIX.len() + 32);
731        salt.extend_from_slice(NIP44_V3_SALT_PREFIX);
732        salt.extend_from_slice(nonce);
733        let hk = Hkdf::<Sha256>::new(Some(&salt), shared_secret);
734        let mut enc = Zeroizing::new([0u8; 32]);
735        let mut mac = Zeroizing::new([0u8; 32]);
736        hk.expand(b"encryption_key", enc.as_mut())
737            .map_err(|_| CryptoError::kdf("NIP-44 v3 encryption key derivation failed"))?;
738        hk.expand(b"mac_key", mac.as_mut())
739            .map_err(|_| CryptoError::kdf("NIP-44 v3 mac key derivation failed"))?;
740        Ok((enc, mac))
741    }
742
743    // Matches the draft's padding schedule (used on the 4-byte-length-prefixed plaintext).
744    fn v3_target_size(len: u64) -> u64 {
745        if len == 0 {
746            return NIP44_V3_MIN_PADDING;
747        }
748        let next_power = 1u64 << (u64::BITS - (len - 1).leading_zeros());
749        let subdivs: u64 = if next_power >= NIP44_V3_PAD_THRESHOLD {
750            8
751        } else {
752            4
753        };
754        let chunk = core::cmp::max(NIP44_V3_MIN_PADDING, next_power / subdivs);
755        chunk * len.div_ceil(chunk)
756    }
757
758    fn v3_pad(plaintext: &[u8]) -> Result<Vec<u8>> {
759        if plaintext.len() > NIP44_V3_MAX_PLAINTEXT {
760            return Err(CryptoError::encryption("NIP-44 v3 plaintext too large").into());
761        }
762        let prefixed = 4u64
763            .checked_add(plaintext.len() as u64)
764            .ok_or_else(|| CryptoError::encryption("NIP-44 v3 plaintext too large"))?;
765        let target = v3_target_size(prefixed);
766        if target > usize::MAX as u64 {
767            return Err(CryptoError::encryption("NIP-44 v3 padded length overflow").into());
768        }
769        let mut out = vec![0u8; target as usize];
770        out[0..4].copy_from_slice(&(plaintext.len() as u32).to_be_bytes());
771        out[4..4 + plaintext.len()].copy_from_slice(plaintext);
772        Ok(out)
773    }
774
775    fn v3_unpad(padded: &[u8]) -> Result<Vec<u8>> {
776        if padded.len() < 4 {
777            return Err(CryptoError::decryption("NIP-44 v3 padded buffer too short").into());
778        }
779        let plen = u32::from_be_bytes([padded[0], padded[1], padded[2], padded[3]]) as usize;
780        if plen > NIP44_V3_MAX_PLAINTEXT
781            || 4usize
782                .checked_add(plen)
783                .is_none_or(|end| end > padded.len())
784        {
785            return Err(CryptoError::decryption("NIP-44 v3 invalid padding length").into());
786        }
787        // The draft does not mandate a canonical padded length, so only require the
788        // trailing region to be all zeroes (checked without early exit on length).
789        let mut diff = 0u8;
790        for &b in &padded[4 + plen..] {
791            diff |= b;
792        }
793        if diff != 0 {
794            return Err(CryptoError::decryption("NIP-44 v3 non-zero padding").into());
795        }
796        Ok(padded[4..4 + plen].to_vec())
797    }
798
799    fn v3_mac_update(
800        mac: &mut Hmac<Sha256>,
801        nonce: &[u8; 32],
802        kind: u32,
803        scope: &[u8],
804        ciphertext: &[u8],
805    ) {
806        mac.update(nonce);
807        mac.update(&kind.to_be_bytes());
808        mac.update(&(scope.len() as u32).to_be_bytes());
809        mac.update(scope);
810        mac.update(ciphertext);
811    }
812
813    /// Encrypt with NIP-44 v3 using a raw ECDH shared secret. `kind`/`scope` are
814    /// authenticated into the payload. Returns the raw payload (pre-base64).
815    pub fn encrypt_v3(
816        shared_secret: &[u8; 32],
817        plaintext: &[u8],
818        kind: u32,
819        scope: &str,
820    ) -> Result<Vec<u8>> {
821        let nonce: [u8; 32] = entropy::try_random_bytes()?;
822        encrypt_v3_with_nonce(shared_secret, plaintext, kind, scope, &nonce)
823    }
824
825    // Nonce-injectable core; production callers must use [encrypt_v3], which supplies
826    // a fresh random nonce.
827    fn encrypt_v3_with_nonce(
828        shared_secret: &[u8; 32],
829        plaintext: &[u8],
830        kind: u32,
831        scope: &str,
832        nonce: &[u8; 32],
833    ) -> Result<Vec<u8>> {
834        let (enc_key, mac_key) = v3_derive_keys(shared_secret, nonce)?;
835        let mut buf = v3_pad(plaintext)?;
836        let zero_nonce = [0u8; 12];
837        let mut cipher = ChaCha20::new((&*enc_key).into(), (&zero_nonce).into());
838        cipher.apply_keystream(&mut buf);
839
840        let scope_bytes = scope.as_bytes();
841        let mut mac = <Hmac<Sha256> as KeyInit>::new_from_slice(&*mac_key)
842            .map_err(|_| CryptoError::encryption("Failed to create NIP-44 v3 HMAC"))?;
843        v3_mac_update(&mut mac, nonce, kind, scope_bytes, &buf);
844        let tag = mac.finalize().into_bytes();
845
846        let mut payload = Vec::with_capacity(1 + 32 + 32 + 4 + 4 + scope_bytes.len() + buf.len());
847        payload.push(NIP44_V3_VERSION);
848        payload.extend_from_slice(nonce);
849        payload.extend_from_slice(&tag);
850        payload.extend_from_slice(&kind.to_be_bytes());
851        payload.extend_from_slice(&(scope_bytes.len() as u32).to_be_bytes());
852        payload.extend_from_slice(scope_bytes);
853        payload.extend_from_slice(&buf);
854        Ok(payload)
855    }
856
857    /// Decrypt a NIP-44 v3 payload, verifying the (kind, scope) context binds to the
858    /// caller's expectations. Returns the plaintext.
859    pub fn decrypt_v3(
860        shared_secret: &[u8; 32],
861        payload: &[u8],
862        expected_kind: u32,
863        expected_scope: &str,
864    ) -> Result<Vec<u8>> {
865        if payload.len() < NIP44_V3_MIN_PAYLOAD {
866            return Err(CryptoError::decryption("NIP-44 v3 payload too short").into());
867        }
868        if payload[0] != NIP44_V3_VERSION {
869            return Err(CryptoError::decryption("Unsupported NIP-44 version").into());
870        }
871        let nonce: [u8; 32] = payload[1..33]
872            .try_into()
873            .map_err(|_| CryptoError::decryption("NIP-44 v3 bad nonce"))?;
874        let provided_mac = &payload[33..65];
875        let kind = u32::from_be_bytes([payload[65], payload[66], payload[67], payload[68]]);
876        let scope_len =
877            u32::from_be_bytes([payload[69], payload[70], payload[71], payload[72]]) as usize;
878        let scope_off = 73usize;
879        let scope_end = scope_off
880            .checked_add(scope_len)
881            .filter(|&end| end <= payload.len())
882            .ok_or_else(|| CryptoError::decryption("NIP-44 v3 scope length out of bounds"))?;
883        let scope = &payload[scope_off..scope_end];
884        let ciphertext = &payload[scope_end..];
885        // Context binding: reject a payload encrypted for a different kind/scope.
886        if kind != expected_kind || scope != expected_scope.as_bytes() {
887            return Err(CryptoError::decryption("NIP-44 v3 context mismatch").into());
888        }
889
890        let (enc_key, mac_key) = v3_derive_keys(shared_secret, &nonce)?;
891        let mut mac = <Hmac<Sha256> as KeyInit>::new_from_slice(&*mac_key)
892            .map_err(|_| CryptoError::decryption("Failed to create NIP-44 v3 HMAC"))?;
893        v3_mac_update(&mut mac, &nonce, kind, scope, ciphertext);
894        mac.verify_slice(provided_mac)
895            .map_err(|_| CryptoError::decryption("NIP-44 v3 invalid MAC"))?;
896
897        let mut buf = ciphertext.to_vec();
898        let zero_nonce = [0u8; 12];
899        let mut cipher = ChaCha20::new((&*enc_key).into(), (&zero_nonce).into());
900        cipher.apply_keystream(&mut buf);
901        v3_unpad(&buf)
902    }
903
904    #[cfg(test)]
905    mod v3_tests {
906        use super::*;
907        use base64::Engine;
908
909        fn unhex(s: &str) -> Vec<u8> {
910            (0..s.len())
911                .step_by(2)
912                .map(|i| u8::from_str_radix(&s[i..i + 2], 16).unwrap())
913                .collect()
914        }
915        fn unhex32(s: &str) -> [u8; 32] {
916            unhex(s).try_into().unwrap()
917        }
918        fn hex_lower(b: &[u8]) -> String {
919            b.iter().map(|x| format!("{x:02x}")).collect()
920        }
921
922        #[test]
923        fn v3_target_size_matches_draft_table() {
924            let table: [(u64, u64); 12] = [
925                (0, 32),
926                (1, 32),
927                (32, 32),
928                (33, 64),
929                (34, 64),
930                (64, 64),
931                (65, 96),
932                (66, 96),
933                (96, 96),
934                (97, 128),
935                (98, 128),
936                (128, 128),
937            ];
938            for (len, expected) in table {
939                assert_eq!(v3_target_size(len), expected, "target_size({len})");
940            }
941        }
942
943        // nostr-land/nip44v3 draft vector (encrypt_decrypt[0]); shared_secret is the
944        // x-only ECDH of the vector's key pair, verified against its published prk.
945        #[test]
946        fn v3_known_answer_vector() {
947            let ss = unhex32("dff79f877ba3953557c8502bf6da24c6f378419d138786e5ddd53034e84077d6");
948            let nonce = unhex32("b5451a6d90ec575b4cdcedf4987429eeab1bbaa192ea3db89eafa058826885a6");
949            let pt = unhex("efbbbf48656c6c6f20776f726c6421");
950            let (enc, mac) = v3_derive_keys(&ss, &nonce).unwrap();
951            assert_eq!(
952                hex_lower(&*enc),
953                "de94e4663af538351a9b75b8af31e968ed8b88241ddbce43ad1d4ae2b984327d"
954            );
955            assert_eq!(
956                hex_lower(&*mac),
957                "70e65d5ff8769e92fbdf163b00b1b317bd4d30fe82de6b00d05cd74fb576febd"
958            );
959            let payload = encrypt_v3_with_nonce(&ss, &pt, 1, "", &nonce).unwrap();
960            assert_eq!(
961                base64::engine::general_purpose::STANDARD.encode(&payload),
962                "A7VFGm2Q7FdbTNzt9Jh0Ke6rG7qhkuo9uJ6voFiCaIWmMJrEDBNRRCorotVxmP7ge14Y+UtDn1/Pn3uzAaNNzHUAAAABAAAAAPJgoFXpn6mjFE0hUZrnZljeaYwSdqBKbVDXcyLgVGC8"
963            );
964            assert_eq!(decrypt_v3(&ss, &payload, 1, "").unwrap(), pt);
965        }
966
967        #[test]
968        fn v3_round_trips_with_kind_and_scope() {
969            let ss = [7u8; 32];
970            let cases: [(u32, &str, &[u8]); 3] = [
971                (1, "", b"hi"),
972                (4, "dm", b"secret message"),
973                (22242, "wss://relay.example.com", b""),
974            ];
975            for (kind, scope, msg) in cases {
976                let payload = encrypt_v3(&ss, msg, kind, scope).unwrap();
977                assert_eq!(decrypt_v3(&ss, &payload, kind, scope).unwrap(), msg);
978            }
979        }
980
981        #[test]
982        fn v3_rejects_context_mismatch_and_tamper() {
983            let ss = [9u8; 32];
984            let payload = encrypt_v3(&ss, b"hello", 4, "dm").unwrap();
985            // Wrong kind or scope must fail (context binding).
986            assert!(decrypt_v3(&ss, &payload, 5, "dm").is_err());
987            assert!(decrypt_v3(&ss, &payload, 4, "other").is_err());
988            // Tampered ciphertext fails the MAC.
989            let mut bad = payload.clone();
990            *bad.last_mut().unwrap() ^= 0x01;
991            assert!(decrypt_v3(&ss, &bad, 4, "dm").is_err());
992            // Wrong key fails.
993            assert!(decrypt_v3(&[8u8; 32], &payload, 4, "dm").is_err());
994        }
995
996        #[test]
997        fn v3_rejects_wrong_version() {
998            let ss = [3u8; 32];
999            let mut payload = encrypt_v3(&ss, b"hi", 1, "").unwrap();
1000            payload[0] = 0x02;
1001            assert!(decrypt_v3(&ss, &payload, 1, "").is_err());
1002        }
1003
1004        #[test]
1005        fn v3_rejects_short_payload() {
1006            let ss = [3u8; 32];
1007            let payload = vec![NIP44_V3_VERSION; NIP44_V3_MIN_PAYLOAD - 1];
1008            assert!(decrypt_v3(&ss, &payload, 1, "").is_err());
1009        }
1010
1011        #[test]
1012        fn v3_rejects_scope_len_out_of_bounds() {
1013            let ss = [3u8; 32];
1014            let mut payload = encrypt_v3(&ss, b"hi", 1, "dm").unwrap();
1015            // scope_len occupies bytes 69..73.
1016            payload[69..73].copy_from_slice(&0xffff_ffffu32.to_be_bytes());
1017            assert!(decrypt_v3(&ss, &payload, 1, "dm").is_err());
1018        }
1019
1020        #[test]
1021        fn v3_unpad_rejects_nonzero_trailing_and_accepts_zero() {
1022            // Declared length 2 with all-zero trailing region decodes cleanly.
1023            let mut good = vec![0u8; 8];
1024            good[0..4].copy_from_slice(&2u32.to_be_bytes());
1025            good[4] = 0xaa;
1026            good[5] = 0xbb;
1027            assert_eq!(v3_unpad(&good).unwrap(), vec![0xaa, 0xbb]);
1028            // A non-zero byte in the trailing region is rejected.
1029            let mut bad = good.clone();
1030            bad[6] = 0x01;
1031            assert!(v3_unpad(&bad).is_err());
1032        }
1033    }
1034}
1035
1036/// NIP-04 encryption using a raw ECDH shared secret.
1037///
1038/// This module implements NIP-04 AES-256-CBC encryption/decryption for use with
1039/// threshold ECDH, where the shared secret is computed via distributed
1040/// key operations rather than from a single private key.
1041pub mod nip04 {
1042    use aes::cipher::{block_padding::Pkcs7, BlockModeDecrypt, BlockModeEncrypt, KeyIvInit};
1043    use base64::Engine;
1044
1045    use super::{entropy, CryptoError, Result};
1046
1047    type Aes256CbcEnc = cbc::Encryptor<aes::Aes256>;
1048    type Aes256CbcDec = cbc::Decryptor<aes::Aes256>;
1049
1050    /// Emit a one-time deprecation warning: NIP-04 (unauthenticated AES-256-CBC)
1051    /// is weak and should be replaced by NIP-44. Logged once per process to
1052    /// flag lingering NIP-04 usage without spamming per call.
1053    fn warn_deprecated_nip04() {
1054        use std::sync::Once;
1055        static WARN: Once = Once::new();
1056        WARN.call_once(|| {
1057            tracing::warn!(
1058                "NIP-04 (AES-256-CBC) is deprecated and cryptographically weak \
1059                 (unauthenticated encryption); prefer NIP-44"
1060            );
1061        });
1062    }
1063
1064    /// Encrypt plaintext using NIP-04 (AES-256-CBC) with a raw ECDH shared secret.
1065    ///
1066    /// Returns the encrypted payload in NIP-04 format: base64(ciphertext)?iv=base64(iv)
1067    pub fn encrypt(shared_secret: &[u8; 32], plaintext: &[u8]) -> Result<String> {
1068        warn_deprecated_nip04();
1069        let iv: [u8; 16] = entropy::try_random_bytes()?;
1070
1071        let cipher = Aes256CbcEnc::new(shared_secret.into(), &iv.into());
1072        let ciphertext = cipher.encrypt_padded_vec::<Pkcs7>(plaintext);
1073
1074        let b64 = base64::engine::general_purpose::STANDARD;
1075        Ok(format!("{}?iv={}", b64.encode(&ciphertext), b64.encode(iv)))
1076    }
1077
1078    /// Decrypt a NIP-04 payload using a raw ECDH shared secret.
1079    ///
1080    /// Takes the encrypted payload in format: base64(ciphertext)?iv=base64(iv)
1081    pub fn decrypt(shared_secret: &[u8; 32], payload: &str) -> Result<Vec<u8>> {
1082        warn_deprecated_nip04();
1083        let (ciphertext_b64, iv_b64) = payload
1084            .split_once("?iv=")
1085            .ok_or_else(|| CryptoError::decryption("Invalid NIP-04 format: missing ?iv="))?;
1086
1087        let b64 = base64::engine::general_purpose::STANDARD;
1088
1089        let ciphertext = b64
1090            .decode(ciphertext_b64)
1091            .map_err(|_| CryptoError::decryption("Invalid base64 ciphertext"))?;
1092
1093        let iv: [u8; 16] = b64
1094            .decode(iv_b64)
1095            .map_err(|_| CryptoError::decryption("Invalid base64 IV"))?
1096            .try_into()
1097            .map_err(|_| CryptoError::decryption("Invalid IV length"))?;
1098
1099        let cipher = Aes256CbcDec::new(shared_secret.into(), &iv.into());
1100        cipher
1101            .decrypt_padded_vec::<Pkcs7>(&ciphertext)
1102            .map_err(|_| CryptoError::decryption("AES decryption failed").into())
1103    }
1104}
1105
1106#[cfg(test)]
1107mod tests {
1108    use super::*;
1109
1110    #[test]
1111    fn try_random_bytes_returns_ok_and_distinct() {
1112        let a: [u8; 32] = try_random_bytes().expect("healthy RNG");
1113        let b: [u8; 32] = try_random_bytes().expect("healthy RNG");
1114        assert_ne!(a, b, "two draws must differ");
1115    }
1116
1117    #[test]
1118    fn entropy_health_error_maps_to_keep_encryption_error() {
1119        // The RNG-failure path returns a recoverable error rather than panicking
1120        // (#685); it surfaces as a crypto/encryption-class KeepError.
1121        let err = crate::error::KeepError::from(crate::entropy::EntropyHealthError);
1122        assert!(matches!(err, crate::error::KeepError::Encryption(_)));
1123    }
1124
1125    #[test]
1126    fn test_hmac_sha256_rfc4231_case1() {
1127        // RFC 4231 test case 1: 20-byte 0x0b key, "Hi There".
1128        let key = [0x0bu8; 20];
1129        let mac = hmac_sha256(&key, b"Hi There");
1130        assert_eq!(
1131            hex::encode(mac),
1132            "b0344c61d8db38535ca8afceaf0bf12b881dc200c9833da726e9376c2e32cff7"
1133        );
1134    }
1135
1136    #[test]
1137    fn test_key_derivation() {
1138        let password = b"test password";
1139        let salt: [u8; SALT_SIZE] = random_bytes();
1140
1141        let key1 = derive_key(password, &salt, Argon2Params::TESTING).unwrap();
1142        let key2 = derive_key(password, &salt, Argon2Params::TESTING).unwrap();
1143
1144        assert_eq!(&*key1.decrypt().unwrap(), &*key2.decrypt().unwrap());
1145
1146        let key3 = derive_key(b"different", &salt, Argon2Params::TESTING).unwrap();
1147        assert_ne!(&*key1.decrypt().unwrap(), &*key3.decrypt().unwrap());
1148    }
1149
1150    #[test]
1151    fn test_encrypt_decrypt_roundtrip() {
1152        let key = SecretKey::generate().unwrap();
1153        let plaintext = b"Hello, Keep!";
1154
1155        let encrypted = encrypt(plaintext, &key).unwrap();
1156        let decrypted = decrypt(&encrypted, &key).unwrap();
1157
1158        assert_eq!(
1159            plaintext.as_slice(),
1160            decrypted.as_slice().unwrap().as_slice()
1161        );
1162    }
1163
1164    #[test]
1165    fn test_decrypt_wrong_key_fails() {
1166        let key = SecretKey::generate().unwrap();
1167        let wrong_key = SecretKey::generate().unwrap();
1168        let plaintext = b"Secret data";
1169
1170        let encrypted = encrypt(plaintext, &key).unwrap();
1171        let result = decrypt(&encrypted, &wrong_key);
1172
1173        assert!(result.is_err());
1174    }
1175
1176    #[test]
1177    fn test_subkey_derivation() {
1178        let master = SecretKey::generate().unwrap();
1179
1180        let subkey1 = derive_subkey(&master, b"header").unwrap();
1181        let subkey2 = derive_subkey(&master, b"data").unwrap();
1182
1183        assert_ne!(&*subkey1.decrypt().unwrap(), &*subkey2.decrypt().unwrap());
1184
1185        let subkey1_again = derive_subkey(&master, b"header").unwrap();
1186        assert_eq!(
1187            &*subkey1.decrypt().unwrap(),
1188            &*subkey1_again.decrypt().unwrap()
1189        );
1190    }
1191
1192    #[test]
1193    fn test_secret_key_encrypted_in_ram() {
1194        let key = SecretKey::generate().unwrap();
1195        let decrypted = key.decrypt().unwrap();
1196        assert!(!decrypted.iter().all(|&b| b == 0));
1197    }
1198
1199    #[test]
1200    fn test_nip04_roundtrip() {
1201        let shared_secret: [u8; 32] = random_bytes();
1202        let plaintext = b"Hello, NIP-04!";
1203
1204        let encrypted = nip04::encrypt(&shared_secret, plaintext).unwrap();
1205        assert!(encrypted.contains("?iv="));
1206
1207        let decrypted = nip04::decrypt(&shared_secret, &encrypted).unwrap();
1208        assert_eq!(plaintext.as_slice(), decrypted.as_slice());
1209    }
1210
1211    #[test]
1212    fn test_nip04_wrong_key_fails() {
1213        let shared_secret: [u8; 32] = random_bytes();
1214        let wrong_secret: [u8; 32] = random_bytes();
1215        let plaintext = b"Secret message";
1216
1217        let encrypted = nip04::encrypt(&shared_secret, plaintext).unwrap();
1218        let result = nip04::decrypt(&wrong_secret, &encrypted);
1219        match result {
1220            Err(_) => {}
1221            Ok(decrypted) => assert_ne!(plaintext.as_slice(), decrypted.as_slice()),
1222        }
1223    }
1224
1225    #[test]
1226    fn test_nip04_invalid_format() {
1227        let shared_secret: [u8; 32] = random_bytes();
1228
1229        let result = nip04::decrypt(&shared_secret, "invalid_no_iv");
1230        assert!(result.is_err());
1231    }
1232
1233    #[test]
1234    fn test_nip44_roundtrip() {
1235        let shared_secret: [u8; 32] = random_bytes();
1236        let plaintext = b"Hello, NIP-44!";
1237
1238        let encrypted = nip44::encrypt(&shared_secret, plaintext).unwrap();
1239        let decrypted = nip44::decrypt(&shared_secret, &encrypted).unwrap();
1240        assert_eq!(plaintext.as_slice(), decrypted.as_slice());
1241    }
1242}