Welcome to mirror list, hosted at ThFree Co, Russian Federation.

PGPDSAElGamalTest.java « test « openpgp « spongycastle « org « java « test « src « pg - gitlab.com/quite/humla-spongycastle.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 32a2806bdbc0061d3c3e292e63c2f9cfc8738944 (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
package org.spongycastle.openpgp.test;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigInteger;
import java.security.AlgorithmParameterGenerator;
import java.security.AlgorithmParameters;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.Security;
import java.util.Date;
import java.util.Iterator;

import javax.crypto.Cipher;
import javax.crypto.spec.DHParameterSpec;

import org.spongycastle.bcpg.BCPGOutputStream;
import org.spongycastle.bcpg.PublicKeyAlgorithmTags;
import org.spongycastle.bcpg.SymmetricKeyAlgorithmTags;
import org.spongycastle.jce.provider.BouncyCastleProvider;
import org.spongycastle.jce.spec.ElGamalParameterSpec;
import org.spongycastle.openpgp.PGPCompressedData;
import org.spongycastle.openpgp.PGPCompressedDataGenerator;
import org.spongycastle.openpgp.PGPEncryptedDataGenerator;
import org.spongycastle.openpgp.PGPEncryptedDataList;
import org.spongycastle.openpgp.PGPException;
import org.spongycastle.openpgp.PGPKeyPair;
import org.spongycastle.openpgp.PGPLiteralData;
import org.spongycastle.openpgp.PGPLiteralDataGenerator;
import org.spongycastle.openpgp.PGPOnePassSignature;
import org.spongycastle.openpgp.PGPOnePassSignatureList;
import org.spongycastle.openpgp.PGPPrivateKey;
import org.spongycastle.openpgp.PGPPublicKey;
import org.spongycastle.openpgp.PGPPublicKeyEncryptedData;
import org.spongycastle.openpgp.PGPPublicKeyRing;
import org.spongycastle.openpgp.PGPSecretKeyRing;
import org.spongycastle.openpgp.PGPSignature;
import org.spongycastle.openpgp.PGPSignatureGenerator;
import org.spongycastle.openpgp.PGPSignatureList;
import org.spongycastle.openpgp.PGPUtil;
import org.spongycastle.openpgp.jcajce.JcaPGPObjectFactory;
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.JcaPGPDigestCalculatorProviderBuilder;
import org.spongycastle.openpgp.operator.jcajce.JcaPGPKeyConverter;
import org.spongycastle.openpgp.operator.jcajce.JcaPGPKeyPair;
import org.spongycastle.openpgp.operator.jcajce.JcePBESecretKeyDecryptorBuilder;
import org.spongycastle.openpgp.operator.jcajce.JcePGPDataEncryptorBuilder;
import org.spongycastle.openpgp.operator.jcajce.JcePublicKeyDataDecryptorFactoryBuilder;
import org.spongycastle.openpgp.operator.jcajce.JcePublicKeyKeyEncryptionMethodGenerator;
import org.spongycastle.util.encoders.Base64;
import org.spongycastle.util.test.SimpleTest;
import org.spongycastle.util.test.UncloseableOutputStream;

public class PGPDSAElGamalTest
    extends SimpleTest
{

    byte[] testPubKeyRing =
        Base64.decode(
            "mQGiBEAR8jYRBADNifuSopd20JOQ5x30ljIaY0M6927+vo09NeNxS3KqItba"
         + "nz9o5e2aqdT0W1xgdHYZmdElOHTTsugZxdXTEhghyxoo3KhVcNnTABQyrrvX"
         + "qouvmP2fEDEw0Vpyk+90BpyY9YlgeX/dEA8OfooRLCJde/iDTl7r9FT+mts8"
         + "g3azjwCgx+pOLD9LPBF5E4FhUOdXISJ0f4EEAKXSOi9nZzajpdhe8W2ZL9gc"
         + "BpzZi6AcrRZBHOEMqd69gtUxA4eD8xycUQ42yH89imEcwLz8XdJ98uHUxGJi"
         + "qp6hq4oakmw8GQfiL7yQIFgaM0dOAI9Afe3m84cEYZsoAFYpB4/s9pVMpPRH"
         + "NsVspU0qd3NHnSZ0QXs8L8DXGO1uBACjDUj+8GsfDCIP2QF3JC+nPUNa0Y5t"
         + "wKPKl+T8hX/0FBD7fnNeC6c9j5Ir/Fp/QtdaDAOoBKiyNLh1JaB1NY6US5zc"
         + "qFks2seZPjXEiE6OIDXYra494mjNKGUobA4hqT2peKWXt/uBcuL1mjKOy8Qf"
         + "JxgEd0MOcGJO+1PFFZWGzLQ3RXJpYyBILiBFY2hpZG5hICh0ZXN0IGtleSBv"
         + "bmx5KSA8ZXJpY0Bib3VuY3ljYXN0bGUub3JnPohZBBMRAgAZBQJAEfI2BAsH"
         + "AwIDFQIDAxYCAQIeAQIXgAAKCRAOtk6iUOgnkDdnAKC/CfLWikSBdbngY6OK"
         + "5UN3+o7q1ACcDRqjT3yjBU3WmRUNlxBg3tSuljmwAgAAuQENBEAR8jgQBAC2"
         + "kr57iuOaV7Ga1xcU14MNbKcA0PVembRCjcVjei/3yVfT/fuCVtGHOmYLEBqH"
         + "bn5aaJ0P/6vMbLCHKuN61NZlts+LEctfwoya43RtcubqMc7eKw4k0JnnoYgB"
         + "ocLXOtloCb7jfubOsnfORvrUkK0+Ne6anRhFBYfaBmGU75cQgwADBQP/XxR2"
         + "qGHiwn+0YiMioRDRiIAxp6UiC/JQIri2AKSqAi0zeAMdrRsBN7kyzYVVpWwN"
         + "5u13gPdQ2HnJ7d4wLWAuizUdKIQxBG8VoCxkbipnwh2RR4xCXFDhJrJFQUm+"
         + "4nKx9JvAmZTBIlI5Wsi5qxst/9p5MgP3flXsNi1tRbTmRhqIRgQYEQIABgUC"
         + "QBHyOAAKCRAOtk6iUOgnkBStAJoCZBVM61B1LG2xip294MZecMtCwQCbBbsk"
         + "JVCXP0/Szm05GB+WN+MOCT2wAgAA");
           
    byte[] testPrivKeyRing =
        Base64.decode(
            "lQHhBEAR8jYRBADNifuSopd20JOQ5x30ljIaY0M6927+vo09NeNxS3KqItba"
         + "nz9o5e2aqdT0W1xgdHYZmdElOHTTsugZxdXTEhghyxoo3KhVcNnTABQyrrvX"
         + "qouvmP2fEDEw0Vpyk+90BpyY9YlgeX/dEA8OfooRLCJde/iDTl7r9FT+mts8"
         + "g3azjwCgx+pOLD9LPBF5E4FhUOdXISJ0f4EEAKXSOi9nZzajpdhe8W2ZL9gc"
         + "BpzZi6AcrRZBHOEMqd69gtUxA4eD8xycUQ42yH89imEcwLz8XdJ98uHUxGJi"
         + "qp6hq4oakmw8GQfiL7yQIFgaM0dOAI9Afe3m84cEYZsoAFYpB4/s9pVMpPRH"
         + "NsVspU0qd3NHnSZ0QXs8L8DXGO1uBACjDUj+8GsfDCIP2QF3JC+nPUNa0Y5t"
         + "wKPKl+T8hX/0FBD7fnNeC6c9j5Ir/Fp/QtdaDAOoBKiyNLh1JaB1NY6US5zc"
         + "qFks2seZPjXEiE6OIDXYra494mjNKGUobA4hqT2peKWXt/uBcuL1mjKOy8Qf"
         + "JxgEd0MOcGJO+1PFFZWGzP4DAwLeUcsVxIC2s2Bb9ab2XD860TQ2BI2rMD/r"
         + "7/psx9WQ+Vz/aFAT3rXkEJ97nFeqEACgKmUCAEk9939EwLQ3RXJpYyBILiBF"
         + "Y2hpZG5hICh0ZXN0IGtleSBvbmx5KSA8ZXJpY0Bib3VuY3ljYXN0bGUub3Jn"
         + "PohZBBMRAgAZBQJAEfI2BAsHAwIDFQIDAxYCAQIeAQIXgAAKCRAOtk6iUOgn"
         + "kDdnAJ9Ala3OcwEV1DbK906CheYWo4zIQwCfUqUOLMp/zj6QAk02bbJAhV1r"
         + "sAewAgAAnQFYBEAR8jgQBAC2kr57iuOaV7Ga1xcU14MNbKcA0PVembRCjcVj"
         + "ei/3yVfT/fuCVtGHOmYLEBqHbn5aaJ0P/6vMbLCHKuN61NZlts+LEctfwoya"
         + "43RtcubqMc7eKw4k0JnnoYgBocLXOtloCb7jfubOsnfORvrUkK0+Ne6anRhF"
         + "BYfaBmGU75cQgwADBQP/XxR2qGHiwn+0YiMioRDRiIAxp6UiC/JQIri2AKSq"
         + "Ai0zeAMdrRsBN7kyzYVVpWwN5u13gPdQ2HnJ7d4wLWAuizUdKIQxBG8VoCxk"
         + "bipnwh2RR4xCXFDhJrJFQUm+4nKx9JvAmZTBIlI5Wsi5qxst/9p5MgP3flXs"
         + "Ni1tRbTmRhr+AwMC3lHLFcSAtrNg/EiWFLAnKNXH27zjwuhje8u2r+9iMTYs"
         + "GjbRxaxRY0GKRhttCwqe2BC0lHhzifdlEcc9yjIjuKfepG2fnnSIRgQYEQIA"
         + "BgUCQBHyOAAKCRAOtk6iUOgnkBStAJ9HFejVtVJ/A9LM/mDPe0ExhEXt/QCg"
         + "m/KM7hJ/JrfnLQl7IaZsdg1F6vCwAgAA");

    byte[] encMessage =
        Base64.decode(
            "hQEOAynbo4lhNjcHEAP/dgCkMtPB6mIgjFvNiotjaoh4sAXf4vFNkSeehQ2c"
         + "r+IMt9CgIYodJI3FoJXxOuTcwesqTp5hRzgUBJS0adLDJwcNubFMy0M2tp5o"
         + "KTWpXulIiqyO6f5jI/oEDHPzFoYgBmR4x72l/YpMy8UoYGtNxNvR7LVOfqJv"
         + "uDY/71KMtPQEAIadOWpf1P5Td+61Zqn2VH2UV7H8eI6hGa6Lsy4sb9iZNE7f"
         + "c+spGJlgkiOt8TrQoq3iOK9UN9nHZLiCSIEGCzsEn3uNuorD++Qs065ij+Oy"
         + "36TKeuJ+38CfT7u47dEshHCPqWhBKEYrxZWHUJU/izw2Q1Yxd2XRxN+nafTL"
         + "X1fQ0lABQUASa18s0BkkEERIdcKQXVLEswWcGqWNv1ZghC7xO2VDBX4HrPjp"
         + "drjL63p2UHzJ7/4gPWGGtnqq1Xita/1mrImn7pzLThDWiT55vjw6Hw==");

    byte[] signedAndEncMessage =
        Base64.decode(
            "hQEOAynbo4lhNjcHEAP+K20MVhzdX57hf/cU8TH0prP0VePr9mmeBedzqqMn"
         + "fp2p8Zb68zmcMlI/WiL5XMNLYRmCgEcXyWbKdP/XV9m9LDBe1CMAGrkCeGBy"
         + "je69IQQ5LS9vDPyEMF4iAAv/EqACjqHkizdY/a/FRx/t2ioXYdEC2jA6kS9C"
         + "McpsNz16DE8EAIk3uKn4bGo/+15TXkyFYzW5Cf71SfRoHNmU2zAI93zhjN+T"
         + "B7mGJwWXzsMkIO6FkMU5TCSrwZS3DBWCIaJ6SYoaawE/C/2j9D7bX1Jv8kum"
         + "4cq+eZM7z6JYs6xend+WAwittpUxbEiyC2AJb3fBSXPAbLqWd6J6xbZZ7GDK"
         + "r2Ca0pwBxwGhbMDyi2zpHLzw95H7Ah2wMcGU6kMLB+hzBSZ6mSTGFehqFQE3"
         + "2BnAj7MtnbghiefogacJ891jj8Y2ggJeKDuRz8j2iICaTOy+Y2rXnnJwfYzm"
         + "BMWcd2h1C5+UeBJ9CrrLniCCI8s5u8z36Rno3sfhBnXdRmWSxExXtocbg1Ht"
         + "dyiThf6TK3W29Yy/T6x45Ws5zOasaJdsFKM=");    
    char[] pass = { 'h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd' };
    
    public void performTest()
        throws Exception
    {
        try
        {
            PGPPublicKey pubKey = null;
            
            PGPUtil.setDefaultProvider("SC");

            //
            // Read the public key
            //
            JcaPGPObjectFactory    pgpFact = new JcaPGPObjectFactory(testPubKeyRing);
            
            PGPPublicKeyRing        pgpPub = (PGPPublicKeyRing)pgpFact.nextObject();

               pubKey = pgpPub.getPublicKey();

            if (pubKey.getBitStrength() != 1024)
            {
                fail("failed - key strength reported incorrectly.");
            }

            //
            // Read the private key
            //
            PGPSecretKeyRing    sKey = new PGPSecretKeyRing(testPrivKeyRing, new JcaKeyFingerprintCalculator());
            PGPPrivateKey        pgpPrivKey = sKey.getSecretKey().extractPrivateKey(new JcePBESecretKeyDecryptorBuilder(new JcaPGPDigestCalculatorProviderBuilder().setProvider("SC").build()).setProvider("SC").build(pass));
            
            //
            // signature generation
            //
            String                                data = "hello world!";
            ByteArrayOutputStream    bOut = new ByteArrayOutputStream();
            ByteArrayInputStream        testIn = new ByteArrayInputStream(data.getBytes());
            PGPSignatureGenerator    sGen = new PGPSignatureGenerator(new JcaPGPContentSignerBuilder(PGPPublicKey.DSA, PGPUtil.SHA1).setProvider("SC"));
        
            sGen.init(PGPSignature.BINARY_DOCUMENT, pgpPrivKey);

            PGPCompressedDataGenerator cGen = new PGPCompressedDataGenerator(
                PGPCompressedData.ZIP);

            BCPGOutputStream bcOut = new BCPGOutputStream(
                cGen.open(new UncloseableOutputStream(bOut)));

            sGen.generateOnePassVersion(false).encode(bcOut);

            PGPLiteralDataGenerator lGen = new PGPLiteralDataGenerator();
            
            Date testDate = new Date((System.currentTimeMillis() / 1000) * 1000);
            OutputStream lOut = lGen.open(
                new UncloseableOutputStream(bcOut),
                PGPLiteralData.BINARY,
                "_CONSOLE",
                data.getBytes().length,
                testDate);

            int ch;
            while ((ch = testIn.read()) >= 0)
            {
                lOut.write(ch);
                sGen.update((byte)ch);
            }

            lGen.close();

            sGen.generate().encode(bcOut);

            cGen.close();

            //
            // verify generated signature
            //
            pgpFact = new JcaPGPObjectFactory(bOut.toByteArray());

            PGPCompressedData c1 = (PGPCompressedData)pgpFact.nextObject();

            pgpFact = new JcaPGPObjectFactory(c1.getDataStream());
            
            PGPOnePassSignatureList p1 = (PGPOnePassSignatureList)pgpFact.nextObject();
            
            PGPOnePassSignature ops = p1.get(0);
            
            PGPLiteralData p2 = (PGPLiteralData)pgpFact.nextObject();
            if (!p2.getModificationTime().equals(testDate))
            {
                fail("Modification time not preserved");
            }

            InputStream    dIn = p2.getInputStream();

            ops.init(new JcaPGPContentVerifierBuilderProvider().setProvider("SC"), pubKey);
            
            while ((ch = dIn.read()) >= 0)
            {
                ops.update((byte)ch);
            }

            PGPSignatureList p3 = (PGPSignatureList)pgpFact.nextObject();

            if (!ops.verify(p3.get(0)))
            {
                fail("Failed generated signature check");
            }
            
            //
            // test encryption
            //
            
            //
            // find a key suitable for encryption
            //
            long            pgpKeyID = 0;
            PublicKey    pKey = null;
            
            Iterator    it = pgpPub.getPublicKeys();
            while (it.hasNext())
            {
                PGPPublicKey    pgpKey = (PGPPublicKey)it.next();

                if (pgpKey.getAlgorithm() == PGPPublicKey.ELGAMAL_ENCRYPT
                    || pgpKey.getAlgorithm() == PGPPublicKey.ELGAMAL_GENERAL)
                {
                    pKey = new JcaPGPKeyConverter().setProvider("SC").getPublicKey(pgpKey);
                    pgpKeyID = pgpKey.getKeyID();
                    if (pgpKey.getBitStrength() != 1024)
                    {
                        fail("failed - key strength reported incorrectly.");
                    }
                    
                    //
                    // verify the key
                    //
                    
                }
            }
             
            Cipher c = Cipher.getInstance("ElGamal/None/PKCS1Padding", "SC");

            c.init(Cipher.ENCRYPT_MODE, pKey);
            
            byte[]  in = "hello world".getBytes();

            byte[]  out = c.doFinal(in);
            
            pgpPrivKey = sKey.getSecretKey(pgpKeyID).extractPrivateKey(new JcePBESecretKeyDecryptorBuilder(new JcaPGPDigestCalculatorProviderBuilder().setProvider("SC").build()).setProvider("SC").build(pass));
            
            c.init(Cipher.DECRYPT_MODE, new JcaPGPKeyConverter().setProvider("SC").getPrivateKey(pgpPrivKey));
            
            out = c.doFinal(out);
            
            if (!areEqual(in, out))
            {
                fail("decryption failed.");
            }

            //
            // encrypted message
            //
            byte[]    text = { (byte)'h', (byte)'e', (byte)'l', (byte)'l', (byte)'o', (byte)' ', (byte)'w', (byte)'o', (byte)'r', (byte)'l', (byte)'d', (byte)'!', (byte)'\n' };
            
            JcaPGPObjectFactory pgpF = new JcaPGPObjectFactory(encMessage);

            PGPEncryptedDataList            encList = (PGPEncryptedDataList)pgpF.nextObject();
        
            PGPPublicKeyEncryptedData    encP = (PGPPublicKeyEncryptedData)encList.get(0);

            InputStream clear = encP.getDataStream(new JcePublicKeyDataDecryptorFactoryBuilder().setProvider("SC").build(pgpPrivKey));
                     
            pgpFact = new JcaPGPObjectFactory(clear);

            c1 = (PGPCompressedData)pgpFact.nextObject();

            pgpFact = new JcaPGPObjectFactory(c1.getDataStream());
            
            PGPLiteralData    ld = (PGPLiteralData)pgpFact.nextObject();
        
            bOut = new ByteArrayOutputStream();
            
            if (!ld.getFileName().equals("test.txt"))
            {
                throw new RuntimeException("wrong filename in packet");
            }

            InputStream    inLd = ld.getDataStream();
            
            while ((ch = inLd.read()) >= 0)
            {
                bOut.write(ch);
            }

            if (!areEqual(bOut.toByteArray(), text))
            {
                fail("wrong plain text in decrypted packet");
            }
            
            //
            // signed and encrypted message
            //
            pgpF = new JcaPGPObjectFactory(signedAndEncMessage);

            encList = (PGPEncryptedDataList)pgpF.nextObject();
        
            encP = (PGPPublicKeyEncryptedData)encList.get(0);

            clear = encP.getDataStream(new JcePublicKeyDataDecryptorFactoryBuilder().setProvider("SC").build(pgpPrivKey));
                     
            pgpFact = new JcaPGPObjectFactory(clear);

            c1 = (PGPCompressedData)pgpFact.nextObject();

            pgpFact = new JcaPGPObjectFactory(c1.getDataStream());
            
            p1 = (PGPOnePassSignatureList)pgpFact.nextObject();
            
            ops = p1.get(0);
            
            ld = (PGPLiteralData)pgpFact.nextObject();
        
            bOut = new ByteArrayOutputStream();
            
            if (!ld.getFileName().equals("test.txt"))
            {
                throw new RuntimeException("wrong filename in packet");
            }

            inLd = ld.getDataStream();
            
            //
            // note: we use the DSA public key here.
            //
            ops.init(new JcaPGPContentVerifierBuilderProvider().setProvider("SC"), pgpPub.getPublicKey());
            
            while ((ch = inLd.read()) >= 0)
            {
                ops.update((byte)ch);
                bOut.write(ch);
            }

            p3 = (PGPSignatureList)pgpFact.nextObject();

            if (!ops.verify(p3.get(0)))
            {
                fail("Failed signature check");
            }
            
            if (!areEqual(bOut.toByteArray(), text))
            {
                fail("wrong plain text in decrypted packet");
            }
            
            //
            // encrypt
            //
            ByteArrayOutputStream        cbOut = new ByteArrayOutputStream();
            PGPEncryptedDataGenerator    cPk = new PGPEncryptedDataGenerator(new JcePGPDataEncryptorBuilder(SymmetricKeyAlgorithmTags.TRIPLE_DES).setSecureRandom(new SecureRandom()).setProvider("SC"));
            PGPPublicKey                        puK = sKey.getSecretKey(pgpKeyID).getPublicKey();
            
            cPk.addMethod(new JcePublicKeyKeyEncryptionMethodGenerator(puK).setProvider("SC"));
            
            OutputStream    cOut = cPk.open(new UncloseableOutputStream(cbOut), bOut.toByteArray().length);

            cOut.write(text);

            cOut.close();

            pgpF = new JcaPGPObjectFactory(cbOut.toByteArray());

            encList = (PGPEncryptedDataList)pgpF.nextObject();
        
            encP = (PGPPublicKeyEncryptedData)encList.get(0);
            
            pgpPrivKey = sKey.getSecretKey(pgpKeyID).extractPrivateKey(new JcePBESecretKeyDecryptorBuilder(new JcaPGPDigestCalculatorProviderBuilder().setProvider("SC").build()).setProvider("SC").build(pass));

            clear = encP.getDataStream(new JcePublicKeyDataDecryptorFactoryBuilder().setProvider("SC").build(pgpPrivKey));
            
            bOut.reset();
            
            while ((ch = clear.read()) >= 0)
            {
                bOut.write(ch);
            }

            out = bOut.toByteArray();

            if (!areEqual(out, text))
            {
                fail("wrong plain text in generated packet");
            }
            
            //
            // use of PGPKeyPair
            //
            BigInteger g = new BigInteger("153d5d6172adb43045b68ae8e1de1070b6137005686d29d3d73a7749199681ee5b212c9b96bfdcfa5b20cd5e3fd2044895d609cf9b410b7a0f12ca1cb9a428cc", 16);
            BigInteger p = new BigInteger("9494fec095f3b85ee286542b3836fc81a5dd0a0349b4c239dd38744d488cf8e31db8bcb7d33b41abb9e5a33cca9144b1cef332c94bf0573bf047a3aca98cdf3b", 16);

            KeyPairGenerator       kpg = KeyPairGenerator.getInstance("ElGamal", "SC");
            
            ElGamalParameterSpec   elParams = new ElGamalParameterSpec(p, g);
            
            kpg.initialize(elParams);
            
            KeyPair kp = kpg.generateKeyPair();
            
            PGPKeyPair    pgpKp = new JcaPGPKeyPair(PGPPublicKey.ELGAMAL_GENERAL, kp, new Date());
            
            PGPPublicKey k1 = pgpKp.getPublicKey();
            
            PGPPrivateKey k2 = pgpKp.getPrivateKey();



            // Test bug with ElGamal P size != 0 mod 8 (don't use these sizes at home!)
            SecureRandom random = new SecureRandom();
            for (int pSize = 257; pSize < 264; ++pSize)
            {
                // Generate some parameters of the given size
                AlgorithmParameterGenerator a = AlgorithmParameterGenerator.getInstance("ElGamal", "SC");
                a.init(pSize, new SecureRandom());
                AlgorithmParameters params = a.generateParameters();

                DHParameterSpec elP = (DHParameterSpec)params.getParameterSpec(DHParameterSpec.class);
                KeyPairGenerator keyGen = KeyPairGenerator.getInstance("ElGamal", "SC");

                keyGen.initialize(elP);


                // Run a short encrypt/decrypt test with random key for the given parameters
                kp = keyGen.generateKeyPair();

                PGPKeyPair elGamalKeyPair = new JcaPGPKeyPair(
                    PublicKeyAlgorithmTags.ELGAMAL_GENERAL, kp, new Date());

                cPk = new PGPEncryptedDataGenerator(new JcePGPDataEncryptorBuilder(SymmetricKeyAlgorithmTags.CAST5).setSecureRandom(new SecureRandom()).setProvider("SC"));

                puK = elGamalKeyPair.getPublicKey();

                cPk.addMethod(new JcePublicKeyKeyEncryptionMethodGenerator(puK).setProvider("SC"));

                cbOut = new ByteArrayOutputStream();

                cOut = cPk.open(cbOut, text.length);

                cOut.write(text);

                cOut.close();

                pgpF = new JcaPGPObjectFactory(cbOut.toByteArray());

                encList = (PGPEncryptedDataList)pgpF.nextObject();

                encP = (PGPPublicKeyEncryptedData)encList.get(0);

                pgpPrivKey = elGamalKeyPair.getPrivateKey();

                // Note: This is where an exception would be expected if the P size causes problems
                clear = encP.getDataStream(new JcePublicKeyDataDecryptorFactoryBuilder().setProvider("SC").build(pgpPrivKey));

                ByteArrayOutputStream dec = new ByteArrayOutputStream();

                int b;
                while ((b = clear.read()) >= 0)
                {
                    dec.write(b);
                }

                byte[] decText = dec.toByteArray();

                if (!areEqual(text, decText))
                {
                    fail("decrypted message incorrect");
                }
            }

            // check sub key encoding

            it = pgpPub.getPublicKeys();
            while (it.hasNext())
            {
                PGPPublicKey    pgpKey = (PGPPublicKey)it.next();

                if (!pgpKey.isMasterKey())
                {
                    byte[] kEnc = pgpKey.getEncoded();

                    JcaPGPObjectFactory objF = new JcaPGPObjectFactory(kEnc);

                    PGPPublicKey k = (PGPPublicKey)objF.nextObject();

                    pKey = new JcaPGPKeyConverter().setProvider("SC").getPublicKey(k);
                    pgpKeyID = k.getKeyID();
                    if (k.getBitStrength() != 1024)
                    {
                        fail("failed - key strength reported incorrectly.");
                    }
       
                    if (objF.nextObject() != null)
                    {
                        fail("failed - stream not fully parsed.");
                    }
                }
            }
           
        }
        catch (PGPException e)
        {
            fail("exception: " + e.getMessage(), e.getUnderlyingException());
        }
    }

    public String getName()
    {
        return "PGPDSAElGamalTest";
    }

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

        runTest(new PGPDSAElGamalTest());
    }
}