ironcrypt 0.1.1

Library-first crypto toolkit: Argon2 password hashing, AES-256-GCM / XChaCha20 streaming, RSA/ECC hybrid encryption, and optional CLI/daemon.
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
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
use crate::{
    algorithms::SymmetricAlgorithm,
    audit::{AuditEvent, Operation, Outcome},
    hashing,
    keys::{PrivateKey, PublicKey},
    rsa_utils, IronCryptError, PasswordCriteria, ecc_utils,
};
use aes_gcm::aead::{Aead, KeyInit};
use aes_gcm::{Aes256Gcm, Nonce};
use aes_gcm_stream::{Aes256GcmStreamDecryptor, Aes256GcmStreamEncryptor};
use argon2::password_hash::{PasswordHash, PasswordHasher, PasswordVerifier, SaltString};
use argon2::{Algorithm, Argon2, Params, Version};
use base64::engine::general_purpose::STANDARD as base64_standard;
use base64::Engine;
use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt};
use chacha20poly1305::{XChaCha20Poly1305, XNonce};
use hex;
use p256::pkcs8::spki::{DecodePublicKey};
use p256::pkcs8::{EncodePublicKey, LineEnding};
use rand::rngs::OsRng;
use rand::RngCore;
use rsa::Oaep;
use serde::{Deserialize, Serialize};
use sha2::Sha256;
use std::io::{Cursor, Read, Write};
use zeroize::Zeroize;

/// Represents the configuration for the Argon2 hashing algorithm.
#[derive(Clone, Debug)]
pub struct Argon2Config {
    pub memory_cost: u32,
    pub time_cost: u32,
    pub parallelism: u32,
}

impl Default for Argon2Config {
    fn default() -> Self {
        Self {
            memory_cost: 65536,
            time_cost: 3,
            parallelism: 1,
        }
    }
}

/// Serializable struct containing encryption information for non-streaming data.
#[derive(Serialize, Deserialize, Debug)]
pub struct EncryptedData {
    /// The symmetric algorithm used for data encryption.
    pub symmetric_algorithm: SymmetricAlgorithm,
    /// Information about the recipient, including the encrypted symmetric key.
    pub recipient_info: RecipientInfo,
    /// The nonce used for symmetric encryption.
    pub nonce: String,
    /// The encrypted data.
    pub ciphertext: String,
    /// The hash of the password, if one was used.
    pub password_hash: Option<String>,
}

// --- Streaming API ---

const BUFFER_SIZE: usize = 8192;

/// Serializable header for encrypted streams (V1, single-recipient).
#[derive(Serialize, Deserialize, Debug)]
pub struct EncryptedStreamHeaderV1 {
    pub key_version: String,
    pub encrypted_symmetric_key: String,
    pub nonce: String,
    pub password_hash: Option<String>,
}

/// Holds the encrypted symmetric key for a single recipient (legacy V2).
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct RecipientInfoV2 {
    pub key_version: String,
    pub encrypted_symmetric_key: String,
}

/// Serializable header for encrypted streams (V2, multi-recipient).
#[derive(Serialize, Deserialize, Debug)]
pub struct EncryptedStreamHeaderV2 {
    pub recipients: Vec<RecipientInfoV2>,
    pub nonce: String,
    pub password_hash: Option<String>,
}

/// Holds information for a single recipient, supporting different asymmetric algorithms.
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(tag = "type")]
pub enum RecipientInfo {
    Rsa {
        key_version: String,
        encrypted_symmetric_key: String,
    },
    Ecc {
        key_version: String,
        ephemeral_public_key: String,
        encrypted_symmetric_key: String,
    },
}

/// Serializable header for encrypted streams (V3, multi-algorithm).
#[derive(Serialize, Deserialize, Debug)]
pub struct EncryptedStreamHeaderV3 {
    pub symmetric_algorithm: SymmetricAlgorithm,
    pub recipients: Vec<RecipientInfo>,
    pub nonce: String,
    pub password_hash: Option<String>,
}

/// Sensitive metadata that gets encrypted within the V4 header.
#[derive(Serialize, Deserialize, Debug)]
pub struct SensitiveHeaderData {
    pub nonce: String,
    pub password_hash: Option<String>,
    pub signature: Option<String>,
    pub signature_algorithm: Option<String>,
    pub signer_key_version: Option<String>,
}

/// Serializable header for encrypted streams (V4, with encrypted metadata).
#[derive(Serialize, Deserialize, Debug)]
pub struct EncryptedStreamHeaderV4 {
    pub symmetric_algorithm: SymmetricAlgorithm,
    pub recipients: Vec<RecipientInfo>,
    pub encrypted_metadata: String,
    pub metadata_nonce: String,
}

/// An enum to handle different versions of the stream header for backward compatibility.
#[derive(Serialize, Deserialize, Debug)]
#[serde(untagged)]
pub enum StreamHeader {
    V4(EncryptedStreamHeaderV4),
    V3(EncryptedStreamHeaderV3),
    V2(EncryptedStreamHeaderV2),
    V1(EncryptedStreamHeaderV1),
}

/// Encrypts a data stream using a configurable combination of algorithms.
#[allow(clippy::too_many_arguments)]
pub fn encrypt_stream<'a, R: Read, W: Write>(
    source: &mut R,
    destination: &mut W,
    password: &mut String,
    recipients: impl IntoIterator<Item = (&'a PublicKey, &'a str)> + Clone,
    signing_key: Option<(&'a PrivateKey, &'a str)>,
    criteria: &PasswordCriteria,
    argon_cfg: Argon2Config,
    hash_password: bool,
    sym_algo: SymmetricAlgorithm,
) -> Result<(), IronCryptError> {
    let mut event = AuditEvent::new(Operation::Write);
    event.symmetric_algorithm = Some(format!("{:?}", sym_algo));
    event.recipient_key_versions = recipients.clone().into_iter().map(|(_, v)| v.to_string()).collect();
    if let Some((key, version)) = signing_key {
        event.signer_key_version = Some(version.to_string());
        event.signature_algorithm = Some(match key {
            PrivateKey::Rsa(_) => "rsa-pss-sha256".to_string(),
            PrivateKey::Ecc(_) => "ecdsa-p256-sha256".to_string(),
        });
    }

    let result = (|| {
        // Pre-buffer only when required: signing needs the full plaintext for the
        // header signature; XChaCha20-Poly1305 is one-shot AEAD (no stream API here).
        // AES-GCM without signing streams directly from `source`.
        let must_prebuffer =
            signing_key.is_some() || matches!(sym_algo, SymmetricAlgorithm::ChaCha20Poly1305);

        let prebuffered: Option<Vec<u8>> = if must_prebuffer {
            let mut source_data = Vec::new();
            source.read_to_end(&mut source_data)?;
            Some(source_data)
        } else {
            None
        };

        let (signature, signature_algorithm, signer_key_version) =
            if let Some((key, version)) = signing_key {
                let source_data = prebuffered.as_ref().expect("signing requires prebuffer");
                let hash = hashing::hash_bytes(source_data)?;
                let (sig, algo) = match key {
                    PrivateKey::Rsa(rsa_private_key) => (
                        rsa_utils::sign_hash_pss(rsa_private_key, &hash)?,
                        "rsa-pss-sha256".to_string(),
                    ),
                    PrivateKey::Ecc(ecc_secret_key) => (
                        ecc_utils::sign_hash_ecc(ecc_secret_key, &hash)?,
                        "ecdsa-p256-sha256".to_string(),
                    ),
                };
                (
                    Some(hex::encode(sig)),
                    Some(algo),
                    Some(version.to_string()),
                )
            } else {
                (None, None, None)
            };

        let password_hash = if hash_password {
            criteria.validate(password)?;
            let params = Params::new(
                argon_cfg.memory_cost,
                argon_cfg.time_cost,
                argon_cfg.parallelism,
                None,
            )?;
            let argon2 = Argon2::new(Algorithm::Argon2id, Version::V0x13, params);
            let salt = SaltString::generate(&mut OsRng);
            let hash_str = argon2.hash_password(password.as_bytes(), &salt)?.to_string();
            Some(base64_standard.encode(hash_str))
        } else {
            None
        };
        password.zeroize();

        let mut symmetric_key = [0u8; 32];
        OsRng.fill_bytes(&mut symmetric_key);

        let file_content_nonce_len = match sym_algo {
            SymmetricAlgorithm::Aes256Gcm => 12,
            SymmetricAlgorithm::ChaCha20Poly1305 => 24,
        };
        let mut file_content_nonce_bytes = vec![0u8; file_content_nonce_len];
        OsRng.fill_bytes(&mut file_content_nonce_bytes);

        let mut recipient_infos = Vec::new();

        for (public_key, key_version) in recipients {
            let recipient_info = match public_key {
                PublicKey::Rsa(rsa_pub_key) => {
                    let padding = Oaep::new::<Sha256>();
                    let encrypted_symmetric_key =
                        rsa_pub_key.encrypt(&mut OsRng, padding, &symmetric_key)?;
                    RecipientInfo::Rsa {
                        key_version: key_version.to_string(),
                        encrypted_symmetric_key: base64_standard.encode(&encrypted_symmetric_key),
                    }
                }
                PublicKey::Ecc(ecc_pub_key) => {
                    let kek = ecc_utils::ecies_key_encap(ecc_pub_key, &symmetric_key)?;
                    let ephemeral_public_key_pem = kek.ephemeral_pk.to_public_key_pem(LineEnding::LF)?;
                    RecipientInfo::Ecc {
                        key_version: key_version.to_string(),
                        ephemeral_public_key: base64_standard.encode(ephemeral_public_key_pem),
                        encrypted_symmetric_key: base64_standard.encode(kek.encapsulated_key),
                    }
                }
            };
            recipient_infos.push(recipient_info);
        }

        if recipient_infos.is_empty() {
            return Err(IronCryptError::EncryptionError(
                "No recipients provided for encryption.".to_string(),
            ));
        }

        let sensitive_metadata = SensitiveHeaderData {
            nonce: base64_standard.encode(&file_content_nonce_bytes),
            password_hash,
            signature,
            signature_algorithm,
            signer_key_version,
        };
        let sensitive_metadata_json = serde_json::to_string(&sensitive_metadata)?;
        let mut metadata_nonce_bytes = vec![0u8; 12];
        OsRng.fill_bytes(&mut metadata_nonce_bytes);
        let cipher = Aes256Gcm::new(&symmetric_key.into());
        let encrypted_metadata = cipher
            .encrypt(Nonce::from_slice(&metadata_nonce_bytes), sensitive_metadata_json.as_bytes())
            .map_err(|e| IronCryptError::EncryptionError(format!("Metadata encryption failed: {}", e)))?;

        let header = StreamHeader::V4(EncryptedStreamHeaderV4 {
            symmetric_algorithm: sym_algo,
            recipients: recipient_infos,
            encrypted_metadata: base64_standard.encode(&encrypted_metadata),
            metadata_nonce: base64_standard.encode(&metadata_nonce_bytes),
        });

        let header_json = serde_json::to_string(&header)?;
        destination.write_u64::<BigEndian>(header_json.len() as u64)?;
        destination.write_all(header_json.as_bytes())?;

        match sym_algo {
            SymmetricAlgorithm::Aes256Gcm => {
                let mut encryptor =
                    Aes256GcmStreamEncryptor::new(symmetric_key, &file_content_nonce_bytes);
                symmetric_key.zeroize();
                let mut buffer = [0u8; BUFFER_SIZE];
                if let Some(ref data) = prebuffered {
                    let mut source_cursor = Cursor::new(data.as_slice());
                    loop {
                        let bytes_read = source_cursor.read(&mut buffer)?;
                        if bytes_read == 0 {
                            break;
                        }
                        let ciphertext_chunk = encryptor.update(&buffer[..bytes_read]);
                        destination.write_all(&ciphertext_chunk)?;
                    }
                } else {
                    loop {
                        let bytes_read = source.read(&mut buffer)?;
                        if bytes_read == 0 {
                            break;
                        }
                        let ciphertext_chunk = encryptor.update(&buffer[..bytes_read]);
                        destination.write_all(&ciphertext_chunk)?;
                    }
                }
                let (final_chunk, tag) = encryptor.finalize();
                destination.write_all(&final_chunk)?;
                destination.write_all(&tag)?;
            }
            SymmetricAlgorithm::ChaCha20Poly1305 => {
                let plaintext = prebuffered.as_ref().expect("ChaCha requires prebuffer");
                let cipher = XChaCha20Poly1305::new_from_slice(&symmetric_key)?;
                let nonce = XNonce::from_slice(&file_content_nonce_bytes);
                let ciphertext = cipher.encrypt(nonce, plaintext.as_ref())?;
                destination.write_all(&ciphertext)?;
                symmetric_key.zeroize();
            }
        }

        symmetric_key.zeroize();
        Ok(())
    })();

    if let Err(e) = &result {
        event.outcome = Outcome::Failure;
        event.error_message = Some(e.to_string());
    }

    event.log();

    result
}

/// Decrypts a data stream.
#[allow(clippy::too_many_arguments)]
pub fn decrypt_stream<R: Read, W: Write>(
    source: &mut R,
    destination: &mut W,
    private_key: &PrivateKey,
    key_version: &str,
    password: &str,
    verifying_key: Option<&PublicKey>,
) -> Result<(), IronCryptError> {
    let mut event = AuditEvent::new(Operation::Read);
    event.key_version = Some(key_version.to_string());

    let result = (|| {
        let header_len = source.read_u64::<BigEndian>()?;
        let mut header_bytes = vec![0; header_len as usize];
        source.read_exact(&mut header_bytes)?;
        let header: StreamHeader = serde_json::from_slice(&header_bytes)?;

        let (symmetric_key, nonce_bytes, sym_algo, signature_info, password_ok) = match header {
            StreamHeader::V4(h) => {
                event.symmetric_algorithm = Some(format!("{:?}", h.symmetric_algorithm));
                let recipient_info = h
                    .recipients
                    .iter()
                    .find(|r| match r {
                        RecipientInfo::Rsa { key_version: v, .. } => v == key_version,
                        RecipientInfo::Ecc { key_version: v, .. } => v == key_version,
                    })
                    .ok_or_else(|| {
                        IronCryptError::DecryptionError(format!(
                            "No key found for recipient version '{}'",
                            key_version
                        ))
                    })?;

                let sk = match (private_key, recipient_info) {
                    (
                        PrivateKey::Rsa(rsa_priv_key),
                        RecipientInfo::Rsa {
                            encrypted_symmetric_key,
                            ..
                        },
                    ) => {
                        let key_bytes = base64_standard.decode(encrypted_symmetric_key)?;
                        rsa_priv_key.decrypt(Oaep::new::<Sha256>(), &key_bytes)?
                    }
                    (
                        PrivateKey::Ecc(ecc_priv_key),
                        RecipientInfo::Ecc {
                            ephemeral_public_key,
                            encrypted_symmetric_key,
                            ..
                        },
                    ) => {
                        let eph_pub_key_pem = base64_standard.decode(ephemeral_public_key)?;
                        let eph_pub_key = p256::PublicKey::from_public_key_pem(
                            &String::from_utf8(eph_pub_key_pem)?,
                        )?;
                        let encapsulated_key = base64_standard.decode(encrypted_symmetric_key)?;

                        ecc_utils::ecies_key_decap(ecc_priv_key, &eph_pub_key, &encapsulated_key)?
                    }
                    _ => {
                        return Err(IronCryptError::DecryptionError(
                            "Mismatched private key and recipient info type".into(),
                        ))
                    }
                };

                let metadata_nonce = base64_standard.decode(h.metadata_nonce)?;
                let encrypted_metadata = base64_standard.decode(h.encrypted_metadata)?;
                let cipher = Aes256Gcm::new_from_slice(&sk)?;
                let sensitive_metadata_json = cipher.decrypt(Nonce::from_slice(&metadata_nonce), encrypted_metadata.as_ref())
                    .map_err(|e| IronCryptError::DecryptionError(format!("Failed to decrypt metadata: {}", e)))?;
                let sensitive_metadata: SensitiveHeaderData = serde_json::from_slice(&sensitive_metadata_json)?;

                let password_ok = if let Some(expected_hash_b64) = &sensitive_metadata.password_hash {
                    check_password_hash(expected_hash_b64, password)
                } else {
                    true
                };

                let sig_info = if let (Some(sig), Some(algo), Some(version)) =
                    (sensitive_metadata.signature, sensitive_metadata.signature_algorithm, sensitive_metadata.signer_key_version)
                {
                    event.signature_algorithm = Some(algo.clone());
                    event.signer_key_version = Some(version.clone());
                    Some((sig, algo, version))
                } else {
                    None
                };

                (
                    sk,
                    base64_standard.decode(sensitive_metadata.nonce)?,
                    h.symmetric_algorithm,
                    sig_info,
                    password_ok,
                )
            }
            StreamHeader::V3(h) => {
                event.symmetric_algorithm = Some(format!("{:?}", h.symmetric_algorithm));
                let recipient_info = h
                    .recipients
                    .iter()
                    .find(|r| match r {
                        RecipientInfo::Rsa { key_version: v, .. } => v == key_version,
                        RecipientInfo::Ecc { key_version: v, .. } => v == key_version,
                    })
                    .ok_or_else(|| {
                        IronCryptError::DecryptionError(format!(
                            "No key found for recipient version '{}'",
                            key_version
                        ))
                    })?;

                let sk = match (private_key, recipient_info) {
                    (
                        PrivateKey::Rsa(rsa_priv_key),
                        RecipientInfo::Rsa {
                            encrypted_symmetric_key,
                            ..
                        },
                    ) => {
                        let key_bytes = base64_standard.decode(encrypted_symmetric_key)?;
                        rsa_priv_key.decrypt(Oaep::new::<Sha256>(), &key_bytes)?
                    }
                    (
                        PrivateKey::Ecc(ecc_priv_key),
                        RecipientInfo::Ecc {
                            ephemeral_public_key,
                            encrypted_symmetric_key,
                            ..
                        },
                    ) => {
                        let eph_pub_key_pem = base64_standard.decode(ephemeral_public_key)?;
                        let eph_pub_key = p256::PublicKey::from_public_key_pem(
                            &String::from_utf8(eph_pub_key_pem)?,
                        )?;
                        let encapsulated_key = base64_standard.decode(encrypted_symmetric_key)?;

                        ecc_utils::ecies_key_decap(ecc_priv_key, &eph_pub_key, &encapsulated_key)?
                    }
                    _ => {
                        return Err(IronCryptError::DecryptionError(
                            "Mismatched private key and recipient info type".into(),
                        ))
                    }
                };

                let password_ok = if let Some(expected_hash_b64) = &h.password_hash {
                    check_password_hash(expected_hash_b64, password)
                } else {
                    true
                };

                let sig_info = None;

                (
                    sk,
                    base64_standard.decode(h.nonce)?,
                    h.symmetric_algorithm,
                    sig_info,
                    password_ok,
                )
            }
            // Backward compatibility for V1 and V2
            StreamHeader::V1(h) => {
                let password_ok = if let Some(hash) = &h.password_hash {
                    check_password_hash(hash, password)
                } else {
                    true
                };
                (
                    {
                        event.symmetric_algorithm = Some(format!("{:?}", SymmetricAlgorithm::Aes256Gcm));
                        let key_bytes = base64_standard.decode(&h.encrypted_symmetric_key)?;
                        if let PrivateKey::Rsa(rsa_priv_key) = private_key {
                            rsa_priv_key.decrypt(Oaep::new::<Sha256>(), &key_bytes)?
                        } else {
                            return Err(IronCryptError::DecryptionError(
                                "V1 headers only support RSA keys".into(),
                            ));
                        }
                    },
                    base64_standard.decode(&h.nonce)?,
                    SymmetricAlgorithm::Aes256Gcm,
                    None,
                    password_ok,
                )
            }
            StreamHeader::V2(h) => {
                let password_ok = if let Some(hash) = &h.password_hash {
                    check_password_hash(hash, password)
                } else {
                    true
                };
                (
                    {
                        event.symmetric_algorithm = Some(format!("{:?}", SymmetricAlgorithm::Aes256Gcm));
                        let recipient_info = h
                            .recipients
                            .iter()
                            .find(|r| r.key_version == key_version)
                            .ok_or_else(|| {
                                IronCryptError::DecryptionError(format!(
                                    "No key found for recipient version '{}'",
                                    key_version
                                ))
                            })?;
                        let key_bytes =
                            base64_standard.decode(&recipient_info.encrypted_symmetric_key)?;
                        if let PrivateKey::Rsa(rsa_priv_key) = private_key {
                            rsa_priv_key.decrypt(Oaep::new::<Sha256>(), &key_bytes)?
                        } else {
                            return Err(IronCryptError::DecryptionError(
                                "V2 headers only support RSA keys".into(),
                            ));
                        }
                    },
                    base64_standard.decode(&h.nonce)?,
                    SymmetricAlgorithm::Aes256Gcm,
                    None,
                    password_ok,
                )
            }
        };

        // Reject wrong passwords before any plaintext leaves this function.
        if !password_ok {
            return Err(IronCryptError::PasswordVerificationError);
        }

        let needs_buffer = signature_info.is_some()
            || matches!(sym_algo, SymmetricAlgorithm::ChaCha20Poly1305);

        if needs_buffer {
            let mut plaintext_buffer = Vec::new();
            match sym_algo {
                SymmetricAlgorithm::Aes256Gcm => {
                    let key_array: [u8; 32] = symmetric_key.as_slice().try_into().map_err(|_| {
                        IronCryptError::DecryptionError(
                            "Decrypted key has incorrect size.".to_string(),
                        )
                    })?;
                    let mut decryptor = Aes256GcmStreamDecryptor::new(key_array, &nonce_bytes);

                    let mut buffer = [0u8; BUFFER_SIZE];
                    loop {
                        let bytes_read = source.read(&mut buffer)?;
                        if bytes_read == 0 {
                            break;
                        }
                        let plaintext_chunk = decryptor.update(&buffer[..bytes_read]);
                        plaintext_buffer.extend_from_slice(&plaintext_chunk);
                    }
                    let final_chunk = decryptor.finalize()?;
                    plaintext_buffer.extend_from_slice(&final_chunk);
                }
                SymmetricAlgorithm::ChaCha20Poly1305 => {
                    let mut source_data = Vec::new();
                    source.read_to_end(&mut source_data)?;
                    let cipher = XChaCha20Poly1305::new_from_slice(&symmetric_key)?;
                    let nonce = XNonce::from_slice(&nonce_bytes);
                    plaintext_buffer = cipher.decrypt(nonce, source_data.as_ref())?;
                }
            }

            if let Some((signature_hex, algo, _signer_version)) = signature_info {
                let key_for_verification = verifying_key.ok_or_else(|| {
                    IronCryptError::SignatureVerificationFailed(
                        "Signature found in file but no verification key was provided.".to_string(),
                    )
                })?;

                let hash = hashing::hash_bytes(&plaintext_buffer)?;
                let signature = hex::decode(signature_hex).map_err(|e| {
                    IronCryptError::SignatureError(format!("Failed to decode signature: {}", e))
                })?;

                match (algo.as_str(), key_for_verification) {
                    ("rsa-pss-sha256", PublicKey::Rsa(k)) => {
                        rsa_utils::verify_signature_pss(k, &hash, &signature)?;
                    }
                    ("rsa-pkcs1v15-sha256", PublicKey::Rsa(k)) => {
                        rsa_utils::verify_signature_pkcs1v15(k, &hash, &signature)?;
                    }
                    ("ecdsa-p256-sha256", PublicKey::Ecc(k)) => {
                        ecc_utils::verify_signature_ecc(k, &hash, &signature)?;
                    }
                    (other, _) => {
                        return Err(IronCryptError::SignatureVerificationFailed(format!(
                            "Unsupported signature algorithm or key type: {}",
                            other
                        )));
                    }
                }
            }

            destination.write_all(&plaintext_buffer)?;
        } else {
            // AES-GCM without signature: decrypt and write in streaming fashion.
            let key_array: [u8; 32] = symmetric_key.as_slice().try_into().map_err(|_| {
                IronCryptError::DecryptionError("Decrypted key has incorrect size.".to_string())
            })?;
            let mut decryptor = Aes256GcmStreamDecryptor::new(key_array, &nonce_bytes);

            let mut buffer = [0u8; BUFFER_SIZE];
            loop {
                let bytes_read = source.read(&mut buffer)?;
                if bytes_read == 0 {
                    break;
                }
                let plaintext_chunk = decryptor.update(&buffer[..bytes_read]);
                destination.write_all(&plaintext_chunk)?;
            }
            let final_chunk = decryptor.finalize()?;
            destination.write_all(&final_chunk)?;
        }

        Ok(())
    })();

    if let Err(e) = &result {
        event.outcome = Outcome::Failure;
        event.error_message = Some(e.to_string());
    }

    event.log();

    result
}

/// Verifies a password against a base64-encoded Argon2 hash.
pub(crate) fn check_password_hash(hash_b64: &str, password: &str) -> bool {
    let Ok(expected_hash_bytes) = base64_standard.decode(hash_b64) else {
        return false;
    };
    let Ok(expected_hash_str) = String::from_utf8(expected_hash_bytes) else {
        return false;
    };

    let Ok(parsed_hash) = PasswordHash::new(&expected_hash_str) else {
        return false;
    };

    Argon2::default()
        .verify_password(password.as_bytes(), &parsed_hash)
        .is_ok()
}

/// Derives a dedicated AES-GCM nonce for sealing an optional password hash field.
fn derive_password_hash_nonce(content_nonce: &[u8]) -> [u8; 12] {
    use sha2::{Digest, Sha256};
    let mut hasher = Sha256::new();
    hasher.update(b"ironcrypt-pwd-hash-nonce-v1");
    hasher.update(content_nonce);
    let digest = hasher.finalize();
    let mut out = [0u8; 12];
    out.copy_from_slice(&digest[..12]);
    out
}

/// Encrypts an Argon2 hash string so it is never stored in cleartext inside EncryptedData JSON.
pub(crate) fn seal_password_hash(
    symmetric_key: &[u8],
    content_nonce: &[u8],
    hash_str: &str,
) -> Result<String, IronCryptError> {
    let nonce = derive_password_hash_nonce(content_nonce);
    let cipher = Aes256Gcm::new_from_slice(symmetric_key)?;
    let ciphertext = cipher
        .encrypt(Nonce::from_slice(&nonce), hash_str.as_bytes())
        .map_err(|e| IronCryptError::EncryptionError(format!("Failed to seal password hash: {e}")))?;
    Ok(base64_standard.encode(ciphertext))
}

/// Verifies a password against a sealed (or legacy cleartext) password_hash field.
pub(crate) fn verify_sealed_or_legacy_password_hash(
    symmetric_key: &[u8],
    content_nonce: &[u8],
    password_hash_field: &str,
    password: &str,
) -> bool {
    // Preferred: sealed Argon2 string encrypted under the content key.
    if let Ok(sealed_bytes) = base64_standard.decode(password_hash_field) {
        let nonce = derive_password_hash_nonce(content_nonce);
        if let Ok(cipher) = Aes256Gcm::new_from_slice(symmetric_key) {
            if let Ok(hash_bytes) =
                cipher.decrypt(Nonce::from_slice(&nonce), sealed_bytes.as_ref())
            {
                if let Ok(hash_str) = String::from_utf8(hash_bytes) {
                    if let Ok(parsed) = PasswordHash::new(&hash_str) {
                        return Argon2::default()
                            .verify_password(password.as_bytes(), &parsed)
                            .is_ok();
                    }
                }
            }
        }
    }

    // Legacy payloads stored the Argon2 PHC string base64-encoded in cleartext.
    check_password_hash(password_hash_field, password)
}