aboutsummaryrefslogtreecommitdiffstats
path: root/libraries/spongycastle/pg/src/test/java/org/spongycastle/openpgp/test/PGPSignatureTest.java
blob: 4bb686d4714118eb2868b2f7c30866968cddaefe (plain)
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
package org.spongycastle.openpgp.test;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.NoSuchProviderException;
import java.security.Security;
import java.security.SignatureException;
import java.util.Date;

import org.spongycastle.bcpg.CompressionAlgorithmTags;
import org.spongycastle.bcpg.HashAlgorithmTags;
import org.spongycastle.bcpg.PublicKeyAlgorithmTags;
import org.spongycastle.bcpg.SignatureSubpacketTags;
import org.spongycastle.bcpg.SymmetricKeyAlgorithmTags;
import org.spongycastle.bcpg.sig.KeyFlags;
import org.spongycastle.bcpg.sig.NotationData;
import org.spongycastle.jce.provider.BouncyCastleProvider;
import org.spongycastle.openpgp.PGPException;
import org.spongycastle.openpgp.PGPLiteralData;
import org.spongycastle.openpgp.PGPLiteralDataGenerator;
import org.spongycastle.openpgp.PGPObjectFactory;
import org.spongycastle.openpgp.PGPOnePassSignature;
import org.spongycastle.openpgp.PGPOnePassSignatureList;
import org.spongycastle.openpgp.PGPPrivateKey;
import org.spongycastle.openpgp.PGPPublicKey;
import org.spongycastle.openpgp.PGPSecretKey;
import org.spongycastle.openpgp.PGPSecretKeyRing;
import org.spongycastle.openpgp.PGPSignature;
import org.spongycastle.openpgp.PGPSignatureGenerator;
import org.spongycastle.openpgp.PGPSignatureList;
import org.spongycastle.openpgp.PGPSignatureSubpacketGenerator;
import org.spongycastle.openpgp.PGPSignatureSubpacketVector;
import org.spongycastle.openpgp.PGPV3SignatureGenerator;
import org.spongycastle.openpgp.operator.jcajce.JcaKeyFingerprintCalculator;
import org.spongycastle.openpgp.operator.jcajce.JcaPGPContentSignerBuilder;
import org.spongycastle.openpgp.operator.jcajce.JcaPGPContentVerifierBuilderProvider;
import org.spongycastle.openpgp.operator.jcajce.JcePBESecretKeyDecryptorBuilder;
import org.spongycastle.util.encoders.Base64;
import org.spongycastle.util.io.Streams;
import org.spongycastle.util.test.SimpleTest;
import org.spongycastle.util.test.UncloseableOutputStream;

public class PGPSignatureTest
    extends SimpleTest
{
    private static final int[] NO_PREFERENCES = null;
    private static final int[] PREFERRED_SYMMETRIC_ALGORITHMS = new int[] { SymmetricKeyAlgorithmTags.AES_128, SymmetricKeyAlgorithmTags.TRIPLE_DES };
    private static final int[] PREFERRED_HASH_ALGORITHMS = new int[] { HashAlgorithmTags.SHA1, HashAlgorithmTags.SHA256 };
    private static final int[] PREFERRED_COMPRESSION_ALGORITHMS = new int[] { CompressionAlgorithmTags.ZLIB };
    
    private static final int TEST_EXPIRATION_TIME = 10000;
    private static final String TEST_USER_ID = "test user id";
    private static final byte[] TEST_DATA = "hello world!\nhello world!\n".getBytes();
    private static final byte[] TEST_DATA_WITH_CRLF = "hello world!\r\nhello world!\r\n".getBytes();

    byte[] dsaKeyRing = Base64.decode(
          "lQHhBD9HBzURBACzkxRCVGJg5+Ld9DU4Xpnd4LCKgMq7YOY7Gi0EgK92gbaa6+zQ"
        + "oQFqz1tt3QUmpz3YVkm/zLESBBtC1ACIXGggUdFMUr5I87+1Cb6vzefAtGt8N5VV"
        + "1F/MXv1gJz4Bu6HyxL/ncfe71jsNhav0i4yAjf2etWFj53zK6R+Ojg5H6wCgpL9/"
        + "tXVfGP8SqFvyrN/437MlFSUEAIN3V6j/MUllyrZglrtr2+RWIwRrG/ACmrF6hTug"
        + "Ol4cQxaDYNcntXbhlTlJs9MxjTH3xxzylyirCyq7HzGJxZzSt6FTeh1DFYzhJ7Qu"
        + "YR1xrSdA6Y0mUv0ixD5A4nPHjupQ5QCqHGeRfFD/oHzD4zqBnJp/BJ3LvQ66bERJ"
        + "mKl5A/4uj3HoVxpb0vvyENfRqKMmGBISycY4MoH5uWfb23FffsT9r9KL6nJ4syLz"
        + "aRR0gvcbcjkc9Z3epI7gr3jTrb4d8WPxsDbT/W1tv9bG/EHawomLcihtuUU68Uej"
        + "6/wZot1XJqu2nQlku57+M/V2X1y26VKsipolPfja4uyBOOyvbP4DAwIDIBTxWjkC"
        + "GGAWQO2jy9CTvLHJEoTO7moHrp1FxOVpQ8iJHyRqZzLllO26OzgohbiPYz8u9qCu"
        + "lZ9Xn7QzRXJpYyBFY2hpZG5hIChEU0EgVGVzdCBLZXkpIDxlcmljQGJvdW5jeWNh"
        + "c3RsZS5vcmc+iFkEExECABkFAj9HBzUECwcDAgMVAgMDFgIBAh4BAheAAAoJEM0j"
        + "9enEyjRDAlwAnjTjjt57NKIgyym7OTCwzIU3xgFpAJ0VO5m5PfQKmGJRhaewLSZD"
        + "4nXkHg==");
    
    char[]    dsaPass = "hello world".toCharArray();

    byte[]    rsaKeyRing = Base64.decode(
          "lQIEBEBXUNMBBADScQczBibewnbCzCswc/9ut8R0fwlltBRxMW0NMdKJY2LF"
        + "7k2COeLOCIU95loJGV6ulbpDCXEO2Jyq8/qGw1qD3SCZNXxKs3GS8Iyh9Uwd"
        + "VL07nMMYl5NiQRsFB7wOb86+94tYWgvikVA5BRP5y3+O3GItnXnpWSJyREUy"
        + "6WI2QQAGKf4JAwIVmnRs4jtTX2DD05zy2mepEQ8bsqVAKIx7lEwvMVNcvg4Y"
        + "8vFLh9Mf/uNciwL4Se/ehfKQ/AT0JmBZduYMqRU2zhiBmxj4cXUQ0s36ysj7"
        + "fyDngGocDnM3cwPxaTF1ZRBQHSLewP7dqE7M73usFSz8vwD/0xNOHFRLKbsO"
        + "RqDlLA1Cg2Yd0wWPS0o7+qqk9ndqrjjSwMM8ftnzFGjShAdg4Ca7fFkcNePP"
        + "/rrwIH472FuRb7RbWzwXA4+4ZBdl8D4An0dwtfvAO+jCZSrLjmSpxEOveJxY"
        + "GduyR4IA4lemvAG51YHTHd4NXheuEqsIkn1yarwaaj47lFPnxNOElOREMdZb"
        + "nkWQb1jfgqO24imEZgrLMkK9bJfoDnlF4k6r6hZOp5FSFvc5kJB4cVo1QJl4"
        + "pwCSdoU6luwCggrlZhDnkGCSuQUUW45NE7Br22NGqn4/gHs0KCsWbAezApGj"
        + "qYUCfX1bcpPzUMzUlBaD5rz2vPeO58CDtBJ0ZXN0ZXIgPHRlc3RAdGVzdD6I"
        + "sgQTAQIAHAUCQFdQ0wIbAwQLBwMCAxUCAwMWAgECHgECF4AACgkQs8JyyQfH"
        + "97I1QgP8Cd+35maM2cbWV9iVRO+c5456KDi3oIUSNdPf1NQrCAtJqEUhmMSt"
        + "QbdiaFEkPrORISI/2htXruYn0aIpkCfbUheHOu0sef7s6pHmI2kOQPzR+C/j"
        + "8D9QvWsPOOso81KU2axUY8zIer64Uzqc4szMIlLw06c8vea27RfgjBpSCryw"
        + "AgAA");

    char[]    rsaPass = "2002 Buffalo Sabres".toCharArray();

    byte[]    nullPacketsSubKeyBinding = Base64.decode(
            "iDYEGBECAAAAACp9AJ9PlJCrFpi+INwG7z61eku2Wg1HaQCgl33X5Egj+Kf7F9CXIWj2iFCvQDo=");
    
    public void performTest()
        throws Exception
    {
        //
        // RSA tests
        //
        PGPSecretKeyRing pgpPriv = new PGPSecretKeyRing(rsaKeyRing, new JcaKeyFingerprintCalculator());
        PGPSecretKey secretKey = pgpPriv.getSecretKey();
        PGPPrivateKey pgpPrivKey = secretKey.extractPrivateKey(new JcePBESecretKeyDecryptorBuilder().setProvider("SC").build(rsaPass));

        try
        {
            testSig(PublicKeyAlgorithmTags.DSA, HashAlgorithmTags.SHA1, secretKey.getPublicKey(), pgpPrivKey);

            fail("RSA wrong key test failed.");
        }
        catch (PGPException e)
        {
            // expected
        }

        try
        {
            testSigV3(PublicKeyAlgorithmTags.DSA, HashAlgorithmTags.SHA1, secretKey.getPublicKey(), pgpPrivKey);

            fail("RSA V3 wrong key test failed.");
        }
        catch (PGPException e)
        {
            // expected
        }

        //
        // certifications
        //
        PGPSignatureGenerator sGen = new PGPSignatureGenerator(new JcaPGPContentSignerBuilder(PublicKeyAlgorithmTags.RSA_GENERAL, HashAlgorithmTags.SHA1).setProvider("SC"));

        sGen.init(PGPSignature.KEY_REVOCATION, pgpPrivKey);

        PGPSignature sig = sGen.generateCertification(secretKey.getPublicKey());

        sig.init(new JcaPGPContentVerifierBuilderProvider().setProvider("SC"), secretKey.getPublicKey());

        if (!sig.verifyCertification(secretKey.getPublicKey()))
        {
            fail("revocation verification failed.");
        }

        PGPSecretKeyRing pgpDSAPriv = new PGPSecretKeyRing(dsaKeyRing, new JcaKeyFingerprintCalculator());
        PGPSecretKey secretDSAKey = pgpDSAPriv.getSecretKey();
        PGPPrivateKey pgpPrivDSAKey = secretDSAKey.extractPrivateKey(new JcePBESecretKeyDecryptorBuilder().setProvider("SC").build(dsaPass));

        sGen = new PGPSignatureGenerator(new JcaPGPContentSignerBuilder(PublicKeyAlgorithmTags.DSA, HashAlgorithmTags.SHA1).setProvider("SC"));

        sGen.init(PGPSignature.SUBKEY_BINDING, pgpPrivDSAKey);

        PGPSignatureSubpacketGenerator    unhashedGen = new PGPSignatureSubpacketGenerator();
        PGPSignatureSubpacketGenerator    hashedGen = new PGPSignatureSubpacketGenerator();

        hashedGen.setSignatureExpirationTime(false, TEST_EXPIRATION_TIME);
        hashedGen.setSignerUserID(true, TEST_USER_ID);
        hashedGen.setPreferredCompressionAlgorithms(false, PREFERRED_COMPRESSION_ALGORITHMS);
        hashedGen.setPreferredHashAlgorithms(false, PREFERRED_HASH_ALGORITHMS);
        hashedGen.setPreferredSymmetricAlgorithms(false, PREFERRED_SYMMETRIC_ALGORITHMS);

        sGen.setHashedSubpackets(hashedGen.generate());
        sGen.setUnhashedSubpackets(unhashedGen.generate());

        sig = sGen.generateCertification(secretDSAKey.getPublicKey(), secretKey.getPublicKey());

        byte[] sigBytes = sig.getEncoded();

        PGPObjectFactory f = new PGPObjectFactory(sigBytes);

        sig = ((PGPSignatureList) f.nextObject()).get(0);

        sig.init(new JcaPGPContentVerifierBuilderProvider().setProvider("SC"), secretDSAKey.getPublicKey());

        if (!sig.verifyCertification(secretDSAKey.getPublicKey(), secretKey.getPublicKey()))
        {
            fail("subkey binding verification failed.");
        }

        PGPSignatureSubpacketVector hashedPcks = sig.getHashedSubPackets();
        PGPSignatureSubpacketVector unhashedPcks = sig.getUnhashedSubPackets();

        if (hashedPcks.size() != 6)
        {
            fail("wrong number of hashed packets found.");
        }

        if (unhashedPcks.size() != 1)
        {
            fail("wrong number of unhashed packets found.");
        }

        if (!hashedPcks.getSignerUserID().equals(TEST_USER_ID))
        {
            fail("test userid not matching");
        }

        if (hashedPcks.getSignatureExpirationTime() != TEST_EXPIRATION_TIME)
        {
            fail("test signature expiration time not matching");
        }

        if (unhashedPcks.getIssuerKeyID() != secretDSAKey.getKeyID())
        {
            fail("wrong issuer key ID found in certification");
        }

        int[] prefAlgs = hashedPcks.getPreferredCompressionAlgorithms();
        preferredAlgorithmCheck("compression", PREFERRED_COMPRESSION_ALGORITHMS, prefAlgs);

        prefAlgs = hashedPcks.getPreferredHashAlgorithms();
        preferredAlgorithmCheck("hash", PREFERRED_HASH_ALGORITHMS, prefAlgs);

        prefAlgs = hashedPcks.getPreferredSymmetricAlgorithms();
        preferredAlgorithmCheck("symmetric", PREFERRED_SYMMETRIC_ALGORITHMS, prefAlgs);

        int[] criticalHashed = hashedPcks.getCriticalTags();

        if (criticalHashed.length != 1)
        {
            fail("wrong number of critical packets found.");
        }

        if (criticalHashed[0] != SignatureSubpacketTags.SIGNER_USER_ID)
        {
            fail("wrong critical packet found in tag list.");
        }

        //
        // no packets passed
        //
        sGen = new PGPSignatureGenerator(new JcaPGPContentSignerBuilder(PublicKeyAlgorithmTags.DSA, HashAlgorithmTags.SHA1).setProvider("SC"));

        sGen.init(PGPSignature.SUBKEY_BINDING, pgpPrivDSAKey);

        sGen.setHashedSubpackets(null);
        sGen.setUnhashedSubpackets(null);

        sig = sGen.generateCertification(TEST_USER_ID, secretKey.getPublicKey());

        sig.init(new JcaPGPContentVerifierBuilderProvider().setProvider("SC"), secretDSAKey.getPublicKey());

        if (!sig.verifyCertification(TEST_USER_ID, secretKey.getPublicKey()))
        {
            fail("subkey binding verification failed.");
        }

        hashedPcks = sig.getHashedSubPackets();

        if (hashedPcks.size() != 1)
        {
            fail("found wrong number of hashed packets");
        }

        unhashedPcks = sig.getUnhashedSubPackets();

        if (unhashedPcks.size() != 1)
        {
            fail("found wrong number of unhashed packets");
        }

        try
        {
            sig.verifyCertification(secretKey.getPublicKey());

            fail("failed to detect non-key signature.");
        }
        catch (PGPException e)
        {
            // expected
        }

        //
        // override hash packets
        //
        sGen = new PGPSignatureGenerator(new JcaPGPContentSignerBuilder(PublicKeyAlgorithmTags.DSA, HashAlgorithmTags.SHA1).setProvider("SC"));

        sGen.init(PGPSignature.SUBKEY_BINDING, pgpPrivDSAKey);

        hashedGen = new PGPSignatureSubpacketGenerator();

        hashedGen.setSignatureCreationTime(false, new Date(0L));

        sGen.setHashedSubpackets(hashedGen.generate());

        sGen.setUnhashedSubpackets(null);

        sig = sGen.generateCertification(TEST_USER_ID, secretKey.getPublicKey());

        sig.init(new JcaPGPContentVerifierBuilderProvider().setProvider("SC"), secretDSAKey.getPublicKey());

        if (!sig.verifyCertification(TEST_USER_ID, secretKey.getPublicKey()))
        {
            fail("subkey binding verification failed.");
        }

        hashedPcks = sig.getHashedSubPackets();

        if (hashedPcks.size() != 1)
        {
            fail("found wrong number of hashed packets in override test");
        }

        if (!hashedPcks.hasSubpacket(SignatureSubpacketTags.CREATION_TIME))
        {
            fail("hasSubpacket test for creation time failed");
        }

        if (!hashedPcks.getSignatureCreationTime().equals(new Date(0L)))
        {
            fail("creation of overriden date failed.");
        }

        prefAlgs = hashedPcks.getPreferredCompressionAlgorithms();
        preferredAlgorithmCheck("compression", NO_PREFERENCES, prefAlgs);

        prefAlgs = hashedPcks.getPreferredHashAlgorithms();
        preferredAlgorithmCheck("hash", NO_PREFERENCES, prefAlgs);

        prefAlgs = hashedPcks.getPreferredSymmetricAlgorithms();
        preferredAlgorithmCheck("symmetric", NO_PREFERENCES, prefAlgs);

        if (hashedPcks.getKeyExpirationTime() != 0)
        {
            fail("unexpected key expiration time found");
        }

        if (hashedPcks.getSignatureExpirationTime() != 0)
        {
            fail("unexpected signature expiration time found");
        }

        if (hashedPcks.getSignerUserID() != null)
        {
            fail("unexpected signer user ID found");
        }

        criticalHashed = hashedPcks.getCriticalTags();

        if (criticalHashed.length != 0)
        {
            fail("critical packets found when none expected");
        }

        unhashedPcks = sig.getUnhashedSubPackets();

        if (unhashedPcks.size() != 1)
        {
            fail("found wrong number of unhashed packets in override test");
        }

        //
        // general signatures
        //
        testSig(PublicKeyAlgorithmTags.RSA_GENERAL, HashAlgorithmTags.SHA256, secretKey.getPublicKey(), pgpPrivKey);
        testSig(PublicKeyAlgorithmTags.RSA_GENERAL, HashAlgorithmTags.SHA384, secretKey.getPublicKey(), pgpPrivKey);
        testSig(PublicKeyAlgorithmTags.RSA_GENERAL, HashAlgorithmTags.SHA512, secretKey.getPublicKey(), pgpPrivKey);
        testSigV3(PublicKeyAlgorithmTags.RSA_GENERAL, HashAlgorithmTags.SHA1, secretKey.getPublicKey(), pgpPrivKey);
        testTextSig(PublicKeyAlgorithmTags.RSA_GENERAL, HashAlgorithmTags.SHA1, secretKey.getPublicKey(), pgpPrivKey, TEST_DATA_WITH_CRLF, TEST_DATA_WITH_CRLF);
        testTextSig(PublicKeyAlgorithmTags.RSA_GENERAL, HashAlgorithmTags.SHA1, secretKey.getPublicKey(), pgpPrivKey, TEST_DATA, TEST_DATA_WITH_CRLF);
        testTextSigV3(PublicKeyAlgorithmTags.RSA_GENERAL, HashAlgorithmTags.SHA1, secretKey.getPublicKey(), pgpPrivKey, TEST_DATA_WITH_CRLF, TEST_DATA_WITH_CRLF);
        testTextSigV3(PublicKeyAlgorithmTags.RSA_GENERAL, HashAlgorithmTags.SHA1, secretKey.getPublicKey(), pgpPrivKey, TEST_DATA, TEST_DATA_WITH_CRLF);

        //
        // DSA Tests
        //
        pgpPriv = new PGPSecretKeyRing(dsaKeyRing, new JcaKeyFingerprintCalculator());
        secretKey = pgpPriv.getSecretKey();
        pgpPrivKey = secretKey.extractPrivateKey(new JcePBESecretKeyDecryptorBuilder().setProvider("SC").build(dsaPass));

        try
        {
            testSig(PublicKeyAlgorithmTags.RSA_GENERAL, HashAlgorithmTags.SHA1, secretKey.getPublicKey(), pgpPrivKey);

            fail("DSA wrong key test failed.");
        }
        catch (PGPException e)
        {
            // expected
        }

        try
        {
            testSigV3(PublicKeyAlgorithmTags.RSA_GENERAL, HashAlgorithmTags.SHA1, secretKey.getPublicKey(), pgpPrivKey);

            fail("DSA V3 wrong key test failed.");
        }
        catch (PGPException e)
        {
            // expected
        }

        testSig(PublicKeyAlgorithmTags.DSA, HashAlgorithmTags.SHA1, secretKey.getPublicKey(), pgpPrivKey);
        testSigV3(PublicKeyAlgorithmTags.DSA, HashAlgorithmTags.SHA1, secretKey.getPublicKey(), pgpPrivKey);
        testTextSig(PublicKeyAlgorithmTags.DSA, HashAlgorithmTags.SHA1, secretKey.getPublicKey(), pgpPrivKey, TEST_DATA_WITH_CRLF, TEST_DATA_WITH_CRLF);
        testTextSig(PublicKeyAlgorithmTags.DSA, HashAlgorithmTags.SHA1, secretKey.getPublicKey(), pgpPrivKey, TEST_DATA, TEST_DATA_WITH_CRLF);
        testTextSigV3(PublicKeyAlgorithmTags.DSA, HashAlgorithmTags.SHA1, secretKey.getPublicKey(), pgpPrivKey, TEST_DATA_WITH_CRLF, TEST_DATA_WITH_CRLF);
        testTextSigV3(PublicKeyAlgorithmTags.DSA, HashAlgorithmTags.SHA1, secretKey.getPublicKey(), pgpPrivKey, TEST_DATA, TEST_DATA_WITH_CRLF);

        // special cases
        //
        testMissingSubpackets(nullPacketsSubKeyBinding);

        testMissingSubpackets(generateV3BinarySig(pgpPrivKey, PublicKeyAlgorithmTags.DSA, HashAlgorithmTags.SHA1));

        // keyflags
        testKeyFlagsValues();

        testSubpacketGenerator();
    }

    private void testSubpacketGenerator()
    {
        PGPSignatureSubpacketGenerator sGen = new PGPSignatureSubpacketGenerator();

        String name1 = genString(64);
        String value1 = genString(72);

        sGen.setNotationData(true, true, name1, value1);

        PGPSignatureSubpacketVector sVec = sGen.generate();

        NotationData[] nd = sVec.getNotationDataOccurences();

        if (nd.length != 1 || !nd[0].isHumanReadable())
        {
            fail("length and readability test 1 failed");
        }

        if (!nd[0].getNotationName().equals(name1) || !nd[0].getNotationValue().equals(value1))
        {
            fail("name/value test 1 failed");
        }

        String name2 = genString(256);
        String value2 = genString(264);

        sGen.setNotationData(true, false, name2, value2);

        sVec = sGen.generate();

        nd = sVec.getNotationDataOccurences();

        if (nd.length != 2 || !nd[0].isHumanReadable() || nd[1].isHumanReadable())
        {
            fail("length and readability test 2 failed");
        }

        if (!nd[0].getNotationName().equals(name1) || !nd[0].getNotationValue().equals(value1))
        {
            fail("name/value test 2.1 failed");
        }

        if (!nd[1].getNotationName().equals(name2) || !nd[1].getNotationValue().equals(value2))
        {
            fail("name/value test 2.2 failed");
        }

        String name3 = genString(0xffff);
        String value3 = genString(0xffff);

        sGen.setNotationData(true, false, name3, value3);

        sVec = sGen.generate();

        nd = sVec.getNotationDataOccurences();

        if (nd.length != 3 || !nd[0].isHumanReadable() || nd[1].isHumanReadable() || nd[2].isHumanReadable())
        {
            fail("length and readability test 3 failed");
        }

        if (!nd[0].getNotationName().equals(name1) || !nd[0].getNotationValue().equals(value1))
        {
            fail("name/value test 3.1 failed");
        }

        if (!nd[1].getNotationName().equals(name2) || !nd[1].getNotationValue().equals(value2))
        {
            fail("name/value test 3.2 failed");
        }

        if (!nd[2].getNotationName().equals(name3) || !nd[2].getNotationValue().equals(value3))
        {
            fail("name/value test 3.3 failed");
        }

        String name4 = genString(0xffff1);
        String value4 = genString(0xfffff);

        try
        {
            sGen.setNotationData(true, false, name4, value4);
            fail("truncation occurs silently");
        }
        catch (IllegalArgumentException e)
        {
            if (!"notationName exceeds maximum length.".equals(e.getMessage()))
            {
                fail("wrong message");
            }
        }

        try
        {
            sGen.setNotationData(true, false, name3, value4);
            fail("truncation occurs silently");
        }
        catch (IllegalArgumentException e)
        {
            if (!"notationValue exceeds maximum length.".equals(e.getMessage()))
            {
                fail("wrong message");
            }
        }
    }

    private String genString(int length)
    {
        char[] chars = new char[length];

        for (int i = 0; i != length; i++)
        {
            chars[i] = (char)('a' + (i % 26));
        }

        return new String(chars);
    }

    private void testKeyFlagsValues()
    {
        checkValue(KeyFlags.CERTIFY_OTHER, 0x01);
        checkValue(KeyFlags.SIGN_DATA, 0x02);
        checkValue(KeyFlags.ENCRYPT_COMMS, 0x04);
        checkValue(KeyFlags.ENCRYPT_STORAGE, 0x08);
        checkValue(KeyFlags.SPLIT, 0x10);
        checkValue(KeyFlags.AUTHENTICATION, 0x20);
        checkValue(KeyFlags.SHARED, 0x80);

        // yes this actually happens
        checkValue(new byte[] { 4, 0, 0, 0 }, 0x04);
        checkValue(new byte[] { 4, 0, 0 }, 0x04);
        checkValue(new byte[] { 4, 0 }, 0x04);
        checkValue(new byte[] { 4 }, 0x04);
    }

    private void checkValue(int flag, int value)
    {
        KeyFlags f = new KeyFlags(true, flag);

        if (f.getFlags() != value)
        {
            fail("flag value mismatch");
        }
    }

    private void checkValue(byte[] flag, int value)
    {
        KeyFlags f = new KeyFlags(true, flag);

        if (f.getFlags() != value)
        {
            fail("flag value mismatch");
        }
    }

    private void testMissingSubpackets(byte[] signature) 
        throws IOException
    {
        PGPObjectFactory f = new PGPObjectFactory(signature);
        Object           obj = f.nextObject();
        
        while (!(obj instanceof PGPSignatureList))
        {
            obj = f.nextObject();
            if (obj instanceof PGPLiteralData)
            {
                InputStream in = ((PGPLiteralData)obj).getDataStream();
                Streams.drain(in);
            }
        }
        
        PGPSignature     sig = ((PGPSignatureList)obj).get(0);
        
        if (sig.getVersion() > 3)
        {
            PGPSignatureSubpacketVector v = sig.getHashedSubPackets();
            
            if (v.getKeyExpirationTime() != 0)
            {
                fail("key expiration time not zero for missing subpackets");
            }

            if (!sig.hasSubpackets())
            {
                fail("hasSubpackets() returns false with packets");
            }
        }
        else
        {
            if (sig.getHashedSubPackets() != null)
            {
                fail("hashed sub packets found when none expected");
            }
            if (sig.getUnhashedSubPackets() != null)
            {
                fail("unhashed sub packets found when none expected");
            }

            if (sig.hasSubpackets())
            {
                fail("hasSubpackets() returns true with no packets");
            }
        }
    }

    private void preferredAlgorithmCheck(
        String type,
        int[] expected,  
        int[] prefAlgs)
    {
        if (expected == null)
        {
            if (prefAlgs != null)
            {
                fail("preferences for " + type + " found when none expected");
            }
        }
        else
        {   
            if (prefAlgs.length != expected.length)
            {
                fail("wrong number of preferred " + type + " algorithms found");
            }
            
            for (int i = 0; i != expected.length; i++)
            {
                if (expected[i] != prefAlgs[i])
                {
                    fail("wrong algorithm found for " + type + ": expected " + expected[i] + " got " + prefAlgs[i]);
                }
            }
        }
    }

    private void testSig(
        int           encAlgorithm,
        int           hashAlgorithm,
        PGPPublicKey  pubKey,
        PGPPrivateKey privKey)
        throws Exception
    {            
        ByteArrayOutputStream bOut = new ByteArrayOutputStream();
        ByteArrayInputStream  testIn = new ByteArrayInputStream(TEST_DATA);
        PGPSignatureGenerator sGen = new PGPSignatureGenerator(new JcaPGPContentSignerBuilder(encAlgorithm, hashAlgorithm).setProvider("SC"));
        
        sGen.init(PGPSignature.BINARY_DOCUMENT, privKey);
        sGen.generateOnePassVersion(false).encode(bOut);
    
        PGPLiteralDataGenerator    lGen = new PGPLiteralDataGenerator();
        OutputStream               lOut = lGen.open(
            new UncloseableOutputStream(bOut),
            PGPLiteralData.BINARY,
            "_CONSOLE",
            TEST_DATA.length * 2,
            new Date());

        int ch;
        while ((ch = testIn.read()) >= 0)
        {
            lOut.write(ch);
            sGen.update((byte)ch);
        }
    
        lOut.write(TEST_DATA);
        sGen.update(TEST_DATA);
        
        lGen.close();
    
        sGen.generate().encode(bOut);
    
        verifySignature(bOut.toByteArray(), hashAlgorithm, pubKey, TEST_DATA);
    }
    
    private void testTextSig(
        int            encAlgorithm,
        int            hashAlgorithm,
        PGPPublicKey   pubKey,
        PGPPrivateKey  privKey,
        byte[]         data,
        byte[]         canonicalData)
        throws Exception
    {            
        PGPSignatureGenerator sGen = new PGPSignatureGenerator(new JcaPGPContentSignerBuilder(encAlgorithm, HashAlgorithmTags.SHA1).setProvider("SC"));
        ByteArrayOutputStream bOut = new ByteArrayOutputStream();
        ByteArrayInputStream  testIn = new ByteArrayInputStream(data);
        Date                  creationTime = new Date();
        
        sGen.init(PGPSignature.CANONICAL_TEXT_DOCUMENT, privKey);
        sGen.generateOnePassVersion(false).encode(bOut);

        PGPLiteralDataGenerator    lGen = new PGPLiteralDataGenerator();
        OutputStream               lOut = lGen.open(
            new UncloseableOutputStream(bOut),
            PGPLiteralData.TEXT,
            "_CONSOLE",
            data.length * 2,
            creationTime);

        int ch;
        while ((ch = testIn.read()) >= 0)
        {
            lOut.write(ch);
            sGen.update((byte)ch);
        }
    
        lOut.write(data);
        sGen.update(data);
        
        lGen.close();
    
        PGPSignature sig = sGen.generate();

        if (sig.getCreationTime().getTime() == 0)
        {
            fail("creation time not set in v4 signature");
        }

        sig.encode(bOut);
    
        verifySignature(bOut.toByteArray(), hashAlgorithm, pubKey, canonicalData);
    }
    
    private void testSigV3(
        int           encAlgorithm,
        int           hashAlgorithm,
        PGPPublicKey  pubKey,
        PGPPrivateKey privKey)
        throws Exception
    {            
        byte[] bytes = generateV3BinarySig(privKey, encAlgorithm, hashAlgorithm);
    
        verifySignature(bytes, hashAlgorithm, pubKey, TEST_DATA);
    }

    private byte[] generateV3BinarySig(PGPPrivateKey privKey, int encAlgorithm, int hashAlgorithm) 
        throws Exception
    {
        ByteArrayOutputStream   bOut = new ByteArrayOutputStream();
        ByteArrayInputStream    testIn = new ByteArrayInputStream(TEST_DATA);
        PGPV3SignatureGenerator sGen = new PGPV3SignatureGenerator(new JcaPGPContentSignerBuilder(encAlgorithm, hashAlgorithm).setProvider("SC"));
        
        sGen.init(PGPSignature.BINARY_DOCUMENT, privKey);
        sGen.generateOnePassVersion(false).encode(bOut);
    
        PGPLiteralDataGenerator lGen = new PGPLiteralDataGenerator();
        OutputStream            lOut = lGen.open(
            new UncloseableOutputStream(bOut),
            PGPLiteralData.BINARY,
            "_CONSOLE",
            TEST_DATA.length * 2,
            new Date());

        int ch;
        while ((ch = testIn.read()) >= 0)
        {
            lOut.write(ch);
            sGen.update((byte)ch);
        }
    
        lOut.write(TEST_DATA);
        sGen.update(TEST_DATA);
        
        lGen.close();
    
        sGen.generate().encode(bOut);
        
        return bOut.toByteArray();
    }
    
    private void testTextSigV3(
        int            encAlgorithm,
        int            hashAlgorithm,
        PGPPublicKey   pubKey,
        PGPPrivateKey  privKey,
        byte[]         data,
        byte[]         canonicalData)
        throws Exception
    {            
        PGPV3SignatureGenerator sGen = new PGPV3SignatureGenerator(new JcaPGPContentSignerBuilder(encAlgorithm, HashAlgorithmTags.SHA1).setProvider("SC"));
        ByteArrayOutputStream   bOut = new ByteArrayOutputStream();
        ByteArrayInputStream    testIn = new ByteArrayInputStream(data);
        
        sGen.init(PGPSignature.CANONICAL_TEXT_DOCUMENT, privKey);
        sGen.generateOnePassVersion(false).encode(bOut);

        PGPLiteralDataGenerator lGen = new PGPLiteralDataGenerator();
        OutputStream            lOut = lGen.open(
            new UncloseableOutputStream(bOut),
            PGPLiteralData.TEXT,
            "_CONSOLE",
            data.length * 2,
            new Date());

        int ch;
        while ((ch = testIn.read()) >= 0)
        {
            lOut.write(ch);
            sGen.update((byte)ch);
        }
    
        lOut.write(data);
        sGen.update(data);
        
        lGen.close();
    
        PGPSignature sig = sGen.generate();

        if (sig.getCreationTime().getTime() == 0)
        {
            fail("creation time not set in v3 signature");
        }

        sig.encode(bOut);

        verifySignature(bOut.toByteArray(), hashAlgorithm, pubKey, canonicalData);
    }
    
    private void verifySignature(
        byte[] encodedSig, 
        int hashAlgorithm, 
        PGPPublicKey pubKey,  
        byte[] original) 
        throws IOException, PGPException, NoSuchProviderException, SignatureException
    {
        PGPObjectFactory        pgpFact = new PGPObjectFactory(encodedSig);
        PGPOnePassSignatureList p1 = (PGPOnePassSignatureList)pgpFact.nextObject();
        PGPOnePassSignature     ops = p1.get(0);
        PGPLiteralData          p2 = (PGPLiteralData)pgpFact.nextObject();
        InputStream             dIn = p2.getInputStream();
    
        ops.init(new JcaPGPContentVerifierBuilderProvider().setProvider("SC"), pubKey);
        
        int ch;

        while ((ch = dIn.read()) >= 0)
        {
            ops.update((byte)ch);
        }
    
        PGPSignatureList p3 = (PGPSignatureList)pgpFact.nextObject();
        PGPSignature sig = p3.get(0);

        Date creationTime = sig.getCreationTime();
        Date now = new Date();

        // Check creationTime is recent
        if (creationTime.after(now)
            || creationTime.before(new Date(now.getTime() - 10 * 60 * 1000)))
        {
            fail("bad creation time in signature: " + creationTime);
        }

        if (sig.getKeyID() != pubKey.getKeyID())
        {
            fail("key id mismatch in signature");
        }
        
        if (!ops.verify(sig))
        {
            fail("Failed generated signature check - " + hashAlgorithm);
        }
        
        sig.init(new JcaPGPContentVerifierBuilderProvider().setProvider("SC"), pubKey);
        
        for (int i = 0; i != original.length; i++)
        {
            sig.update(original[i]);
        }
        
        sig.update(original);
        
        if (!sig.verify())
        {
            fail("Failed generated signature check against original data");
        }
    }
    
    public String getName()
    {
        return "PGPSignatureTest";
    }

    public static void main(
        String[]    args)
    {
        Security.addProvider(new BouncyCastleProvider());

        runTest(new PGPSignatureTest());
    }
}