jarsigner 0.2.2

JAR signing library compatible with jarsigner API
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
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
use anyhow::{anyhow, Result};
use base64::engine::general_purpose::STANDARD;
use base64::Engine;
use rand::rngs::OsRng;
use rsa::pkcs1v15::SigningKey;
use rsa::pkcs1v15::VerifyingKey;
use rsa::pkcs8::DecodePrivateKey;
use rsa::pkcs8::EncodePrivateKey;
use rsa::sha2::Sha256;
use rsa::signature::Keypair;
use rsa::signature::SignatureEncoding;
use rsa::signature::Signer;
use rsa::signature::Verifier;
use sha2::Digest;
use spki::{DecodePublicKey, EncodePublicKey};
use std::collections::BTreeMap;
use std::io::{Cursor, Read, Write};
use zip::ZipArchive;

// PKCS#7 / X.509 machinery for producing a real, Java-verifiable signature block.
use cms::cert::{CertificateChoices, IssuerAndSerialNumber};
use cms::content_info::{CmsVersion, ContentInfo};
use cms::signed_data::{
    CertificateSet, EncapsulatedContentInfo, SignedData, SignerIdentifier, SignerInfo, SignerInfos,
};
use const_oid::ObjectIdentifier;
use der::asn1::{Null, OctetString, SetOfVec, UtcTime};
use der::{Any, Decode, Encode};
use rsa::pkcs1v15::Signature;
use spki::{AlgorithmIdentifierOwned, SubjectPublicKeyInfoOwned};
use std::str::FromStr;
use std::time::Duration;
use x509_cert::builder::{Builder, CertificateBuilder, Profile};
use x509_cert::name::Name;
use x509_cert::serial_number::SerialNumber;
use x509_cert::time::{Time, Validity};

const OID_SIGNED_DATA: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.1.7.2");
const OID_DATA: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.1.7.1");
const OID_SHA256: ObjectIdentifier = ObjectIdentifier::new_unwrap("2.16.840.1.101.3.4.2.1");
const OID_RSA: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.1.1.1");

/// Format a `Key: value` manifest header, wrapping it to the JAR spec's 72-byte
/// line limit. Long values (deep class paths, digests) continue on lines that
/// begin with a single space. Java's manifest reader rejects any physical line
/// longer than 72 bytes with "line too long", so this is mandatory, not cosmetic.
///
/// Wrapping is byte-based (the limit is bytes, not chars) but never splits a
/// UTF-8 sequence. The returned string ends with the section-terminating CRLF.
fn fold_header(key: &str, value: &str) -> String {
    let full = format!("{key}: {value}");
    let bytes = full.as_bytes();
    let mut out = String::new();
    let mut start = 0usize;
    // First physical line may be 72 bytes; continuation lines carry a leading
    // space that counts toward the 72, leaving 71 bytes of content.
    let mut limit = 72usize;
    while bytes.len() - start > limit {
        let mut end = start + limit;
        // Don't split in the middle of a multi-byte UTF-8 character.
        while end > start && (bytes[end] & 0xC0) == 0x80 {
            end -= 1;
        }
        out.push_str(std::str::from_utf8(&bytes[start..end]).unwrap_or(""));
        out.push_str("\r\n ");
        start = end;
        limit = 71;
    }
    out.push_str(std::str::from_utf8(&bytes[start..]).unwrap_or(""));
    out.push_str("\r\n");
    out
}

/// Build the `.RSA` PKCS#7 (CMS) `SignedData` block for a JAR signature.
///
/// This is a detached signature over the `.SF` file bytes, carrying a
/// deterministic self-signed X.509 certificate for the signing key. Java's JAR
/// verifier (and therefore Forge/NeoForge) requires exactly this structure — a
/// bare RSA signature with no certificate is treated as "unsigned".
///
/// The certificate is fully deterministic (fixed subject / serial / validity),
/// so every jar signed with the same key gets an identical certificate and thus
/// a single, stable signer fingerprint across the whole modpack.
fn build_signature_block(signing_key: &SigningKey<Sha256>, sf_bytes: &[u8]) -> Result<Vec<u8>> {
    // --- 1. Deterministic self-signed certificate ---
    let verifying_key = signing_key.verifying_key();
    let spki = SubjectPublicKeyInfoOwned::from_key(verifying_key)
        .map_err(|e| anyhow!("Failed to encode public key: {}", e))?;
    let subject = Name::from_str("CN=Kojacoord Mod Signing,O=Kojacoord Network")
        .map_err(|e| anyhow!("Failed to build subject name: {}", e))?;
    // 2020-01-01 .. 2049-12-31 (kept inside UtcTime's <2050 range).
    let validity = Validity {
        not_before: Time::UtcTime(
            UtcTime::from_unix_duration(Duration::from_secs(1_577_836_800))
                .map_err(|e| anyhow!("not_before: {}", e))?,
        ),
        not_after: Time::UtcTime(
            UtcTime::from_unix_duration(Duration::from_secs(2_524_521_600))
                .map_err(|e| anyhow!("not_after: {}", e))?,
        ),
    };
    let builder = CertificateBuilder::new(
        Profile::Manual { issuer: None }, // issuer == subject -> self-signed
        SerialNumber::from(1u32),
        validity,
        subject,
        spki,
        signing_key,
    )
    .map_err(|e| anyhow!("Failed to create certificate builder: {}", e))?;
    let cert = builder
        .build::<Signature>()
        .map_err(|e| anyhow!("Failed to build certificate: {}", e))?;

    // --- 2. RSA signature over the .SF content (SHA256withRSA) ---
    // `SigningKey::<Sha256>` hashes its input with SHA-256 internally, so we must
    // sign the raw .SF bytes here (NOT a pre-computed digest — that would hash
    // twice and never verify).
    let signature = signing_key.sign(sf_bytes);
    let sig_bytes = signature.to_vec();

    // --- 3. Assemble the PKCS#7 SignedData (detached, no signed attributes) ---
    let sha256_ai = AlgorithmIdentifierOwned {
        oid: OID_SHA256,
        parameters: None,
    };
    let rsa_ai = AlgorithmIdentifierOwned {
        oid: OID_RSA,
        parameters: Some(Any::encode_from(&Null).map_err(|e| anyhow!("null params: {}", e))?),
    };

    let signer_info = SignerInfo {
        version: CmsVersion::V1,
        sid: SignerIdentifier::IssuerAndSerialNumber(IssuerAndSerialNumber {
            issuer: cert.tbs_certificate.issuer.clone(),
            serial_number: cert.tbs_certificate.serial_number.clone(),
        }),
        digest_alg: sha256_ai.clone(),
        signed_attrs: None,
        signature_algorithm: rsa_ai,
        signature: OctetString::new(sig_bytes).map_err(|e| anyhow!("signature octet: {}", e))?,
        unsigned_attrs: None,
    };

    let signed_data = SignedData {
        version: CmsVersion::V1,
        digest_algorithms: SetOfVec::try_from(vec![sha256_ai])
            .map_err(|e| anyhow!("digest algorithms: {}", e))?,
        encap_content_info: EncapsulatedContentInfo {
            econtent_type: OID_DATA,
            econtent: None, // detached
        },
        certificates: Some(CertificateSet(
            SetOfVec::try_from(vec![CertificateChoices::Certificate(cert)])
                .map_err(|e| anyhow!("certificate set: {}", e))?,
        )),
        crls: None,
        signer_infos: SignerInfos(
            SetOfVec::try_from(vec![signer_info]).map_err(|e| anyhow!("signer infos: {}", e))?,
        ),
    };

    let content_info = ContentInfo {
        content_type: OID_SIGNED_DATA,
        content: Any::encode_from(&signed_data).map_err(|e| anyhow!("wrap SignedData: {}", e))?,
    };
    content_info
        .to_der()
        .map_err(|e| anyhow!("encode ContentInfo: {}", e))
}

/// Signs JAR bytes with the provided RSA private key.
///
/// This function creates a standard JAR signature following the OpenJDK jarsigner format:
/// - MANIFEST.MF with SHA-256 digests of all files (excluding META-INF)
/// - .SF file with manifest digest and individual file digests
/// - .RSA file with PKCS#1 RSA signature of the .SF file
///
/// # Arguments
///
/// * `jar_bytes` - The JAR file contents as bytes
/// * `key_bytes` - RSA private key in PKCS#8 DER format
/// * `_pass` - Passcode parameter kept for API compatibility (not used)
/// * `override_signature` - If true, removes existing signatures before signing
///
/// # Returns
///
/// Returns the signed JAR bytes on success.
///
/// # Errors
///
/// Returns an error if:
/// - The private key cannot be parsed
/// - The JAR cannot be read as a ZIP archive
/// - Signature generation fails
///
/// # Example
///
/// ```no_run
/// use jarsigner::{sign_bytes, generate_key_pair};
///
/// let (private_key, _) = generate_key_pair().unwrap();
/// let jar_bytes = std::fs::read("app.jar").unwrap();
/// let signed_jar = sign_bytes(&jar_bytes, &private_key, "", true).unwrap();
/// ```
pub fn sign_bytes(
    jar_bytes: &[u8],
    key_bytes: &[u8],
    _pass: &str,
    override_signature: bool,
) -> Result<Vec<u8>> {
    sign_bytes_with_cert_chain(
        jar_bytes,
        key_bytes,
        None,
        _pass,
        override_signature,
        &mut |_, _| {},
    )
}

/// Signs JAR bytes with the provided RSA private key and optional certificate chain.
///
/// This is an extended version of `sign_bytes` that accepts an optional certificate chain.
/// Note: Certificate chain support is not fully implemented in this version.
///
/// # Arguments
///
/// * `jar_bytes` - The JAR file contents as bytes
/// * `key_bytes` - RSA private key in PKCS#8 DER format
/// * `_cert_chain` - Optional certificate chain (not currently used)
/// * `_pass` - Passcode parameter kept for API compatibility (not used)
/// * `override_signature` - If true, removes existing signatures before signing
///
/// # Returns
///
/// Returns the signed JAR bytes on success.
pub fn sign_bytes_with_cert_chain<F>(
    jar_bytes: &[u8],
    key_bytes: &[u8],
    _cert_chain: Option<&[Vec<u8>]>,
    _pass: &str,
    override_signature: bool,
    mut progress_callback: F,
) -> Result<Vec<u8>>
where
    F: FnMut(String, bool),
{
    let signing_key = SigningKey::<Sha256>::from_pkcs8_der(key_bytes)
        .map_err(|e| anyhow!("Failed to parse RSA key: {}", e))?;

    let cursor = Cursor::new(jar_bytes);
    let mut zip =
        ZipArchive::new(cursor).map_err(|e| anyhow!("Failed to open JAR as ZIP: {}", e))?;

    // Preserve the input manifest's MAIN section (Main-Class, Class-Path, and
    // critically the loader markers like FMLCorePlugin / TweakClass /
    // MixinConfigs / FMLAT and `Multi-Release: true`) so signing doesn't strip
    // the attributes that make a jar a coremod / multi-release jar. Losing these
    // silently breaks mod loading.
    //
    // Manifests fold long values onto continuation lines that begin with a
    // single space (JAR spec, 72-byte wrap), so we must UNFOLD before parsing —
    // otherwise wrapped values are truncated or dropped.
    let mut preserved_main_attrs: Vec<(String, String)> = Vec::new();
    if let Ok(mut mf) = zip.by_name("META-INF/MANIFEST.MF") {
        let mut buf = String::new();
        if mf.read_to_string(&mut buf).is_ok() {
            let main_section_end = buf.find("\r\n\r\n").or_else(|| buf.find("\n\n")).unwrap_or(buf.len());
            let main_section = &buf[..main_section_end];

            // Unfold continuation lines (a line starting with ' ' continues the
            // previous one) into whole logical header lines.
            let mut logical: Vec<String> = Vec::new();
            for raw in main_section.split('\n') {
                let line = raw.trim_end_matches('\r');
                if line.starts_with(' ') {
                    if let Some(last) = logical.last_mut() {
                        last.push_str(&line[1..]);
                        continue;
                    }
                }
                logical.push(line.to_string());
            }

            for line in &logical {
                if let Some((k, v)) = line.split_once(": ") {
                    // Drop the keys we'll re-emit so we don't duplicate them.
                    if k.eq_ignore_ascii_case("Manifest-Version") || k.eq_ignore_ascii_case("Created-By") {
                        continue;
                    }
                    preserved_main_attrs.push((k.to_string(), v.to_string()));
                }
            }
        }
    }

    // BTreeMap → deterministic entry order, so the same jar+key always produces
    // byte-identical output (stable digests for the anti-cheat to compare).
    let mut file_digests = BTreeMap::new();
    for i in 0..zip.len() {
        let mut file = zip
            .by_index(i)
            .map_err(|e| anyhow!("Failed to get file {}: {}", i, e))?;

        let name = file.name().to_string();

        if name.starts_with("META-INF/") {
            continue;
        }
        // Directory entries carry no content and get no manifest section (real
        // jarsigner skips them); signing them would list bogus zero-byte digests.
        if name.ends_with('/') {
            continue;
        }

        let mut content = Vec::new();
        file.read_to_end(&mut content)
            .map_err(|e| anyhow!("Failed to read file {}: {}", name, e))?;

        let mut hasher = Sha256::new();
        hasher.update(&content);
        let digest = STANDARD.encode(hasher.finalize());
        file_digests.insert(name, digest);
    }

    let mut manifest = String::new();
    manifest.push_str(&fold_header("Manifest-Version", "1.0"));
    manifest.push_str(&fold_header("Created-By", "jarsigned"));
    for (k, v) in &preserved_main_attrs {
        manifest.push_str(&fold_header(k, v));
    }
    manifest.push_str("\r\n");

    // For each entry we emit its manifest section AND record the SHA-256 of that
    // exact section's bytes (including the trailing blank line). Java's verifier
    // marks an entry as *signed* only when the `.SF` carries this per-section
    // digest — the whole-manifest digest alone leaves every entry "unsigned".
    let mut sf_section_digests: Vec<(String, String)> = Vec::new();
    for (name, digest) in &file_digests {
        let section = format!(
            "{}{}\r\n",
            fold_header("Name", name),
            fold_header("SHA-256-Digest", digest)
        );
        let mut section_hasher = Sha256::new();
        section_hasher.update(section.as_bytes());
        sf_section_digests.push((name.clone(), STANDARD.encode(section_hasher.finalize())));
        manifest.push_str(&section);
    }

    let manifest_bytes = manifest.as_bytes();
    let mut manifest_hasher = Sha256::new();
    manifest_hasher.update(manifest_bytes);
    let manifest_digest = manifest_hasher.finalize();

    // Minimal, spec-compliant signature file. The whole-manifest digest lets the
    // Java verifier authenticate every entry through its fast path, so we omit
    // the per-entry section digests and the main-attributes digest — both have
    // fiddly exact-byte boundaries that, if off, turn "unsigned" into a hard
    // SecurityException at mod load.
    let mut sf_content = String::new();
    sf_content.push_str(&fold_header("Signature-Version", "1.0"));
    sf_content.push_str(&fold_header("Created-By", "jarsigned"));
    sf_content.push_str(&fold_header(
        "SHA-256-Digest-Manifest",
        &STANDARD.encode(manifest_digest),
    ));
    sf_content.push_str("\r\n");

    // Per-entry section digests — these are what actually mark each entry as
    // signed. The digest is over the entry's MANIFEST section bytes, not the
    // file bytes.
    for (name, section_digest) in &sf_section_digests {
        sf_content.push_str(&fold_header("Name", name));
        sf_content.push_str(&fold_header("SHA-256-Digest", section_digest));
        sf_content.push_str("\r\n");
    }

    let sf_bytes = sf_content.as_bytes();

    // Real PKCS#7 SignedData block (with a self-signed certificate) over the .SF
    // bytes. This is what Java/Forge actually verify; the previous code emitted a
    // bare RSA signature with no certificate, so every mod showed up as unsigned.
    let cms_der = build_signature_block(&signing_key, sf_bytes)?;

    let sig_block_ext = "RSA";

    let cursor = Cursor::new(jar_bytes);
    let mut zip =
        ZipArchive::new(cursor).map_err(|e| anyhow!("Failed to re-open JAR as ZIP: {}", e))?;

    let mut modified_jar = Vec::new();
    {
        let mut writer = zip::ZipWriter::new(Cursor::new(&mut modified_jar));

        let text_options: zip::write::FileOptions<'_, ()> =
            zip::write::FileOptions::default().compression_method(zip::CompressionMethod::Stored);

        // The manifest and signature files MUST come first in the archive, so a
        // streaming reader (JarInputStream — used by Forge's mod scanner and
        // Java's own on-the-fly verification) sees them before the entries they
        // sign. Appending them last leaves every entry "not signed in
        // JarInputStream".
        writer
            .start_file("META-INF/MANIFEST.MF", text_options)
            .map_err(|e| anyhow!("Failed to create MANIFEST.MF: {}", e))?;
        writer
            .write_all(manifest_bytes)
            .map_err(|e| anyhow!("Failed to write MANIFEST.MF: {}", e))?;

        writer
            .start_file("META-INF/SIGNATURE.SF", text_options)
            .map_err(|e| anyhow!("Failed to create SIGNATURE.SF: {}", e))?;
        writer
            .write_all(sf_bytes)
            .map_err(|e| anyhow!("Failed to write SF file: {}", e))?;

        let sig_block_name = format!("META-INF/SIGNATURE.{}", sig_block_ext);
        writer
            .start_file(&sig_block_name, text_options)
            .map_err(|e| anyhow!("Failed to create signature block file: {}", e))?;
        writer
            .write_all(&cms_der)
            .map_err(|e| anyhow!("Failed to write signature block: {}", e))?;

        // Then every original entry, minus any previous signature files and the
        // old manifest (which we've replaced). We drop the explicit `META-INF/`
        // directory entry too — MANIFEST.MF above already creates that path, and
        // re-adding it out of order trips JarInputStream.
        for i in 0..zip.len() {
            let mut file = zip
                .by_index(i)
                .map_err(|e| anyhow!("Failed to get file {}: {}", i, e))?;

            let name = file.name().to_string();

            let lower_name = name.to_ascii_lowercase();
            // Always drop the old manifest (we rewrote it) and the bare META-INF/
            // dir entry (recreated implicitly, in order, by MANIFEST.MF above).
            if lower_name == "meta-inf/" || lower_name == "meta-inf/manifest.mf" {
                continue;
            }
            // Strip pre-existing signatures only when overriding.
            if override_signature
                && name.starts_with("META-INF/")
                && (lower_name.ends_with(".sf")
                    || lower_name.ends_with(".rsa")
                    || lower_name.ends_with(".dsa")
                    || lower_name.ends_with(".ec"))
            {
                continue;
            }

            progress_callback(name.clone(), false);

            let options: zip::write::FileOptions<'_, ()> = zip::write::FileOptions::default()
                .compression_method(file.compression())
                .unix_permissions(file.unix_mode().unwrap_or(0o644));

            writer
                .start_file(&name, options)
                .map_err(|e| anyhow!("Failed to start file {}: {}", name, e))?;

            std::io::copy(&mut file, &mut writer)
                .map_err(|e| anyhow!("Failed to copy file {}: {}", name, e))?;

            progress_callback(name.clone(), true);
        }

        writer
            .finish()
            .map_err(|e| anyhow!("Failed to finish ZIP: {}", e))?;
    }

    Ok(modified_jar)
}

/// Extracts the signature block bytes from a signed JAR.
///
/// Searches for signature files (.SF, .RSA, .DSA) in the META-INF directory
/// and returns their contents.
///
/// # Arguments
///
/// * `signed_jar_bytes` - The signed JAR file contents as bytes
///
/// # Returns
///
/// Returns `Some(signature_bytes)` if a signature file is found,
/// or `None` if no signature files are present.
///
/// # Errors
///
/// Returns an error if the JAR cannot be read as a ZIP archive.
pub fn extract_signature_bytes(signed_jar_bytes: &[u8]) -> Result<Option<Vec<u8>>> {
    let cursor = Cursor::new(signed_jar_bytes);
    let mut zip =
        ZipArchive::new(cursor).map_err(|e| anyhow!("Failed to open signed JAR: {}", e))?;

    for i in 0..zip.len() {
        let mut file = zip
            .by_index(i)
            .map_err(|e| anyhow!("Failed to get file {}: {}", i, e))?;

        let name = file.name().to_string();
        if name.starts_with("META-INF/")
            && (name.ends_with(".SF") || name.ends_with(".RSA") || name.ends_with(".DSA"))
        {
            let mut sig_bytes = Vec::new();
            std::io::copy(&mut file, &mut sig_bytes)
                .map_err(|e| anyhow!("Failed to read signature file {}: {}", name, e))?;
            return Ok(Some(sig_bytes));
        }
    }

    Ok(None)
}

/// Generates a new RSA key pair for JAR signing.
///
/// Creates a 2048-bit RSA key pair suitable for JAR signing.
/// The private key is returned in PKCS#8 DER format.
///
/// # Returns
///
/// Returns a tuple of (private_key_der, public_key_der) where both are in DER format.
///
/// # Errors
///
/// Returns an error if key generation fails.
///
/// # Example
///
/// ```no_run
/// use jarsigner::generate_key_pair;
///
/// let (private_key, public_key) = generate_key_pair().unwrap();
/// ```
pub fn generate_key_pair() -> Result<(Vec<u8>, Vec<u8>)> {
    let mut rng = OsRng;
    let bits = 2048;
    let private_key = rsa::RsaPrivateKey::new(&mut rng, bits)
        .map_err(|e| anyhow!("Failed to generate RSA key: {}", e))?;
    let signing_key = SigningKey::<Sha256>::new(private_key);
    let verifying_key = signing_key.verifying_key();

    let private_der = signing_key
        .to_pkcs8_der()
        .map_err(|e| anyhow!("Failed to encode private key: {}", e))?
        .to_bytes()
        .to_vec();

    let public_der = verifying_key
        .to_public_key_der()
        .map_err(|e| anyhow!("Failed to encode public key: {}", e))?
        .as_bytes()
        .to_vec();

    Ok((private_der, public_der))
}

/// Generates a complete signing key pair.
///
/// This is a convenience function that wraps `generate_key_pair`.
/// Note: Certificate generation is not implemented in this version.
///
/// # Returns
///
/// Returns a tuple of (private_key_der, public_key_der) in DER format.
///
/// # Errors
///
/// Returns an error if key generation fails.
pub fn generate_signing_credentials() -> Result<(Vec<u8>, Vec<u8>)> {
    generate_key_pair()
}

/// Checks if a JAR is signed.
///
/// Searches for signature files (.SF, .RSA, .DSA) in the META-INF directory
/// to determine if the JAR has been signed.
///
/// # Arguments
///
/// * `jar_bytes` - The JAR file contents as bytes
///
/// # Returns
///
/// Returns `true` if signature files are present, `false` otherwise.
///
/// # Errors
///
/// Returns an error if the JAR cannot be read as a ZIP archive.
///
/// # Example
///
/// ```no_run
/// use jarsigner::is_signed;
///
/// let jar_bytes = std::fs::read("app.jar").unwrap();
/// let signed = is_signed(&jar_bytes).unwrap();
/// ```
pub fn is_signed(jar_bytes: &[u8]) -> Result<bool> {
    let cursor = Cursor::new(jar_bytes);
    let mut zip = ZipArchive::new(cursor).map_err(|e| anyhow!("Failed to open JAR: {}", e))?;

    for i in 0..zip.len() {
        let file = zip
            .by_index(i)
            .map_err(|e| anyhow!("Failed to get file {}: {}", i, e))?;

        let name = file.name();
        if name.starts_with("META-INF/")
            && (name.ends_with(".SF") || name.ends_with(".RSA") || name.ends_with(".DSA"))
        {
            return Ok(true);
        }
    }

    Ok(false)
}

/// Verifies a JAR signature using the provided public key.
///
/// This function performs a simplified signature verification by checking
/// the RSA signature on the .SF file digest.
///
/// # Arguments
///
/// * `jar_bytes` - The signed JAR file contents as bytes
/// * `public_key_bytes` - RSA public key in DER format
///
/// # Returns
///
/// Returns `true` if the signature is valid, `false` otherwise.
///
/// # Errors
///
/// Returns an error if:
/// - The JAR cannot be read
/// - Signature files are missing
/// - The public key cannot be parsed
///
/// # Note
///
/// This is a simplified verification. Full certificate chain verification
/// is not implemented in this version.
pub fn verify(jar_bytes: &[u8], public_key_bytes: &[u8]) -> Result<bool> {
    let cursor = Cursor::new(jar_bytes);
    let mut zip = ZipArchive::new(cursor).map_err(|e| anyhow!("Failed to open JAR: {}", e))?;

    let mut sf_content = None;
    let mut rsa_content = None;

    for i in 0..zip.len() {
        let mut file = zip
            .by_index(i)
            .map_err(|e| anyhow!("Failed to get file {}: {}", i, e))?;

        let name = file.name();
        if name.starts_with("META-INF/") {
            if name.ends_with(".SF") {
                let mut content = Vec::new();
                std::io::copy(&mut file, &mut content)
                    .map_err(|e| anyhow!("Failed to read SF file: {}", e))?;
                sf_content = Some(content);
            } else if name.ends_with(".RSA") || name.ends_with(".DSA") {
                let mut content = Vec::new();
                std::io::copy(&mut file, &mut content)
                    .map_err(|e| anyhow!("Failed to read RSA file: {}", e))?;
                rsa_content = Some(content);
            }
        }
    }

    let sf_bytes = sf_content.ok_or_else(|| anyhow!("No .SF file found"))?;
    let rsa_bytes = rsa_content.ok_or_else(|| anyhow!("No .RSA/.DSA file found"))?;

    let verifying_key = VerifyingKey::<Sha256>::from_public_key_der(public_key_bytes)
        .map_err(|e| anyhow!("Failed to parse public key: {}", e))?;

    // The .RSA block is a PKCS#7 ContentInfo wrapping a SignedData; pull the raw
    // RSA signature out of the (single) SignerInfo. The signature is computed
    // over the .SF content directly (SHA256withRSA), so verify against sf_bytes.
    let content_info = ContentInfo::from_der(&rsa_bytes)
        .map_err(|e| anyhow!("Failed to parse PKCS#7 block: {}", e))?;
    let signed_data: SignedData = content_info
        .content
        .decode_as()
        .map_err(|e| anyhow!("Failed to decode SignedData: {}", e))?;
    let signer_info = signed_data
        .signer_infos
        .0
        .as_slice()
        .first()
        .ok_or_else(|| anyhow!("No SignerInfo in signature block"))?;

    let signature = rsa::pkcs1v15::Signature::try_from(signer_info.signature.as_bytes())
        .map_err(|_| anyhow!("Invalid signature format"))?;

    verifying_key
        .verify(&sf_bytes, &signature)
        .map_err(|_| anyhow!("Signature verification failed"))?;

    Ok(true)
}

/// Extracts the public key from a signed JAR.
///
/// Attempts to extract the public key from the signature block.
/// Note: This is a placeholder implementation and currently always returns None.
///
/// # Arguments
///
/// * `jar_bytes` - The signed JAR file contents as bytes
///
/// # Returns
///
/// Returns `Some(public_key_der)` if the public key can be extracted,
/// or `None` if extraction is not possible.
///
/// # Note
///
/// Full CMS/PKCS#7 parsing is not implemented in this version.
pub fn extract_public_key(jar_bytes: &[u8]) -> Result<Option<Vec<u8>>> {
    let cursor = Cursor::new(jar_bytes);
    let mut zip = ZipArchive::new(cursor).map_err(|e| anyhow!("Failed to open JAR: {}", e))?;

    for i in 0..zip.len() {
        let mut file = zip
            .by_index(i)
            .map_err(|e| anyhow!("Failed to get file {}: {}", i, e))?;

        let name = file.name();
        if name.starts_with("META-INF/") && (name.ends_with(".RSA") || name.ends_with(".DSA")) {
            let mut content = Vec::new();
            std::io::copy(&mut file, &mut content)
                .map_err(|e| anyhow!("Failed to read signature file: {}", e))?;

            if content.len() > 100 {
                return Ok(None);
            }
        }
    }

    Ok(None)
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::io::Write;
    use zip::write::FileOptions;

    fn create_test_jar() -> Vec<u8> {
        let mut buffer = Vec::new();
        {
            let mut writer = zip::ZipWriter::new(std::io::Cursor::new(&mut buffer));

            let options: zip::write::FileOptions<'_, ()> =
                FileOptions::default().compression_method(zip::CompressionMethod::Stored);

            writer.start_file("test.txt", options).unwrap();
            writer.write_all(b"Hello, World!").unwrap();

            writer
                .start_file(
                    "META-INF/",
                    (FileOptions::default() as zip::write::FileOptions<'_, ()>)
                        .unix_permissions(0o40755),
                )
                .unwrap();
            writer.start_file("META-INF/config.xml", options).unwrap();
            writer.write_all(b"<config/>").unwrap();

            writer.finish().unwrap();
        }
        buffer
    }

    #[test]
    fn test_generate_key_pair() {
        let (priv_key, pub_key) = generate_key_pair().unwrap();
        assert!(!priv_key.is_empty());
        assert!(!pub_key.is_empty());
        assert!(priv_key.len() > 100);
        assert!(pub_key.len() > 100);
    }

    #[test]
    fn test_generate_signing_credentials() {
        let (priv_key, pub_key) = generate_signing_credentials().unwrap();
        assert!(!priv_key.is_empty());
        assert!(!pub_key.is_empty());
        assert!(priv_key.len() > 100);
        assert!(pub_key.len() > 100);
    }

    #[test]
    fn test_sign_bytes() {
        let jar_bytes = create_test_jar();
        let (priv_key, _) = generate_key_pair().unwrap();

        let signed_jar = sign_bytes(&jar_bytes, &priv_key, "", false).unwrap();

        assert!(!signed_jar.is_empty());
        assert!(signed_jar.len() > jar_bytes.len());
    }

    #[test]
    fn test_sign_bytes_with_cert_chain() {
        let jar_bytes = create_test_jar();
        let (priv_key, _) = generate_signing_credentials().unwrap();
        let cert_chain: Vec<Vec<u8>> = vec![];

        let signed_jar = sign_bytes_with_cert_chain(
            &jar_bytes,
            &priv_key,
            Some(&cert_chain),
            "",
            false,
            &mut |_, _| {},
        )
        .unwrap();

        assert!(!signed_jar.is_empty());
        assert!(signed_jar.len() > jar_bytes.len());
    }

    #[test]
    fn test_sign_bytes_override_signature() {
        let jar_bytes = create_test_jar();
        let (priv_key, _) = generate_key_pair().unwrap();

        let signed_once = sign_bytes(&jar_bytes, &priv_key, "", false).unwrap();
        let signed_twice = sign_bytes(&signed_once, &priv_key, "", true).unwrap();

        assert!(!signed_twice.is_empty());
    }

    #[test]
    fn test_is_signed() {
        let jar_bytes = create_test_jar();
        let (priv_key, _) = generate_key_pair().unwrap();

        assert!(!is_signed(&jar_bytes).unwrap());

        let signed_jar = sign_bytes(&jar_bytes, &priv_key, "", false).unwrap();
        assert!(is_signed(&signed_jar).unwrap());
    }

    #[test]
    fn test_extract_signature_bytes() {
        let jar_bytes = create_test_jar();
        let (priv_key, _) = generate_key_pair().unwrap();

        let result = extract_signature_bytes(&jar_bytes);
        assert!(result.is_ok());
        assert!(result.unwrap().is_none());

        let signed_jar = sign_bytes(&jar_bytes, &priv_key, "", false).unwrap();
        let result = extract_signature_bytes(&signed_jar);
        assert!(result.is_ok());
        assert!(result.unwrap().is_some());
    }

    #[test]
    fn test_verify() {
        let jar_bytes = create_test_jar();
        let (priv_key, pub_key) = generate_key_pair().unwrap();

        let signed_jar = sign_bytes(&jar_bytes, &priv_key, "", false).unwrap();

        let result = verify(&signed_jar, &pub_key);
        assert!(result.is_ok());
    }

    #[test]
    fn test_extract_public_key() {
        let jar_bytes = create_test_jar();
        let (priv_key, _) = generate_signing_credentials().unwrap();
        let cert_chain: Vec<Vec<u8>> = vec![];

        let signed_jar = sign_bytes_with_cert_chain(
            &jar_bytes,
            &priv_key,
            Some(&cert_chain),
            "",
            false,
            &mut |_, _| {},
        )
        .unwrap();

        let result = extract_public_key(&signed_jar);
        assert!(result.is_ok());
    }

    #[test]
    fn test_sign_empty_jar() {
        let mut buffer = Vec::new();
        {
            let writer = zip::ZipWriter::new(std::io::Cursor::new(&mut buffer));
            writer.finish().unwrap();
        }

        let (priv_key, _) = generate_key_pair().unwrap();
        let signed_jar = sign_bytes(&buffer, &priv_key, "", false).unwrap();

        assert!(!signed_jar.is_empty());
    }

    #[test]
    fn test_sign_jar_with_meta_inf_files() {
        let jar_bytes = create_test_jar();
        let (priv_key, _) = generate_key_pair().unwrap();

        let signed_jar = sign_bytes(&jar_bytes, &priv_key, "", false).unwrap();

        let cursor = std::io::Cursor::new(&signed_jar);
        let mut zip = ZipArchive::new(cursor).unwrap();

        let mut has_manifest = false;
        let mut has_sf = false;
        let mut has_rsa = false;

        for i in 0..zip.len() {
            let file = zip.by_index(i).unwrap();
            let name = file.name();

            if name == "META-INF/MANIFEST.MF" {
                has_manifest = true;
            } else if name == "META-INF/SIGNATURE.SF" {
                has_sf = true;
            } else if name == "META-INF/SIGNATURE.RSA" {
                has_rsa = true;
            }
        }

        assert!(has_manifest);
        assert!(has_sf);
        assert!(has_rsa);
    }

    #[test]
    fn test_sign_preserves_main_manifest_attributes() {
        // A coremod / multi-release manifest. These attributes MUST survive
        // signing or Forge won't recognise the jar as a coremod and the ASM
        // upgrade (mixinbooter etc.) never happens.
        let mut buffer = Vec::new();
        {
            let mut writer = zip::ZipWriter::new(std::io::Cursor::new(&mut buffer));
            let stored: zip::write::FileOptions<'_, ()> =
                FileOptions::default().compression_method(zip::CompressionMethod::Stored);
            writer.start_file("META-INF/MANIFEST.MF", stored).unwrap();
            writer
                .write_all(
                    b"Manifest-Version: 1.0\r\n\
                      Multi-Release: true\r\n\
                      FMLCorePlugin: com.example.CorePlugin\r\n\
                      FMLCorePluginContainsFMLMod: true\r\n\
                      TweakClass: org.spongepowered.asm.launch.MixinTweaker\r\n\
                      MixinConfigs: mixins.example.json\r\n\r\n",
                )
                .unwrap();
            writer.start_file("a/B.class", stored).unwrap();
            writer.write_all(b"\xca\xfe\xba\xbe").unwrap();
            writer.finish().unwrap();
        }

        let (priv_key, _) = generate_key_pair().unwrap();
        let signed = sign_bytes(&buffer, &priv_key, "", true).unwrap();

        let mut zip = ZipArchive::new(std::io::Cursor::new(&signed)).unwrap();
        let mut mf = String::new();
        zip.by_name("META-INF/MANIFEST.MF").unwrap().read_to_string(&mut mf).unwrap();
        let main = mf.split("\r\n\r\n").next().unwrap();
        for attr in [
            "Multi-Release: true",
            "FMLCorePlugin: com.example.CorePlugin",
            "FMLCorePluginContainsFMLMod: true",
            "TweakClass: org.spongepowered.asm.launch.MixinTweaker",
            "MixinConfigs: mixins.example.json",
        ] {
            assert!(main.contains(attr), "signing dropped manifest attribute: {attr}\nGot:\n{main}");
        }
    }

    #[test]
    fn test_invalid_key() {
        let jar_bytes = create_test_jar();
        let invalid_key = b"invalid key data";

        let result = sign_bytes(&jar_bytes, invalid_key, "", false);
        assert!(result.is_err());
    }

    #[test]
    fn test_invalid_jar() {
        let invalid_jar = b"not a jar";
        let (priv_key, _) = generate_key_pair().unwrap();

        let result = sign_bytes(invalid_jar, &priv_key, "", false);
        assert!(result.is_err());
    }
}