mirrored from https://www.bouncycastle.org/repositories/bc-java
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
PEMParser.java
574 lines (524 loc) · 18.7 KB
/
PEMParser.java
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
package org.bouncycastle.openssl;
import java.io.IOException;
import java.io.Reader;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.StringTokenizer;
import org.bouncycastle.asn1.ASN1BitString;
import org.bouncycastle.asn1.ASN1Integer;
import org.bouncycastle.asn1.ASN1ObjectIdentifier;
import org.bouncycastle.asn1.ASN1Primitive;
import org.bouncycastle.asn1.ASN1Sequence;
import org.bouncycastle.asn1.DERNull;
import org.bouncycastle.asn1.cms.ContentInfo;
import org.bouncycastle.asn1.pkcs.EncryptedPrivateKeyInfo;
import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers;
import org.bouncycastle.asn1.pkcs.PrivateKeyInfo;
import org.bouncycastle.asn1.pkcs.RSAPublicKey;
import org.bouncycastle.asn1.x509.AlgorithmIdentifier;
import org.bouncycastle.asn1.x509.DSAParameter;
import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo;
import org.bouncycastle.asn1.x9.X9ECParameters;
import org.bouncycastle.asn1.x9.X9ObjectIdentifiers;
import org.bouncycastle.cert.X509AttributeCertificateHolder;
import org.bouncycastle.cert.X509CRLHolder;
import org.bouncycastle.cert.X509CertificateHolder;
import org.bouncycastle.pkcs.PKCS10CertificationRequest;
import org.bouncycastle.pkcs.PKCS8EncryptedPrivateKeyInfo;
import org.bouncycastle.util.encoders.Hex;
import org.bouncycastle.util.io.pem.PemHeader;
import org.bouncycastle.util.io.pem.PemObject;
import org.bouncycastle.util.io.pem.PemObjectParser;
import org.bouncycastle.util.io.pem.PemReader;
/**
* Class for parsing OpenSSL PEM encoded streams containing
* X509 certificates, PKCS8 encoded keys and PKCS7 objects.
* <p>
* In the case of PKCS7 objects the reader will return a CMS ContentInfo object. Public keys will be returned as
* well formed SubjectPublicKeyInfo objects, private keys will be returned as well formed PrivateKeyInfo objects. In the
* case of a private key a PEMKeyPair will normally be returned if the encoding contains both the private and public
* key definition. CRLs, Certificates, PKCS#10 requests, and Attribute Certificates will generate the appropriate BC holder class.
* </p>
*/
public class PEMParser
extends PemReader
{
public static final String TYPE_CERTIFICATE_REQUEST = "CERTIFICATE REQUEST";
public static final String TYPE_NEW_CERTIFICATE_REQUEST = "NEW CERTIFICATE REQUEST";
public static final String TYPE_CERTIFICATE = "CERTIFICATE";
public static final String TYPE_TRUSTED_CERTIFICATE = "TRUSTED CERTIFICATE";
public static final String TYPE_X509_CERTIFICATE = "X509 CERTIFICATE";
public static final String TYPE_X509_CRL = "X509 CRL";
public static final String TYPE_PKCS7 = "PKCS7";
public static final String TYPE_CMS = "CMS";
public static final String TYPE_ATTRIBUTE_CERTIFICATE = "ATTRIBUTE CERTIFICATE";
public static final String TYPE_EC_PARAMETERS = "EC PARAMETERS";
public static final String TYPE_PUBLIC_KEY = "PUBLIC KEY";
public static final String TYPE_RSA_PUBLIC_KEY = "RSA PUBLIC KEY";
public static final String TYPE_RSA_PRIVATE_KEY = "RSA PRIVATE KEY";
public static final String TYPE_DSA_PRIVATE_KEY = "DSA PRIVATE KEY";
public static final String TYPE_EC_PRIVATE_KEY = "EC PRIVATE KEY";
public static final String TYPE_ENCRYPTED_PRIVATE_KEY = "ENCRYPTED PRIVATE KEY";
public static final String TYPE_PRIVATE_KEY = "PRIVATE KEY";
protected final Map parsers = new HashMap();
/**
* Create a new PEMReader
*
* @param reader the Reader
*/
public PEMParser(
Reader reader)
{
super(reader);
parsers.put(TYPE_CERTIFICATE_REQUEST, new PKCS10CertificationRequestParser());
parsers.put(TYPE_NEW_CERTIFICATE_REQUEST, new PKCS10CertificationRequestParser());
parsers.put(TYPE_CERTIFICATE, new X509CertificateParser());
parsers.put(TYPE_TRUSTED_CERTIFICATE, new X509TrustedCertificateParser());
parsers.put(TYPE_X509_CERTIFICATE, new X509CertificateParser());
parsers.put(TYPE_X509_CRL, new X509CRLParser());
parsers.put(TYPE_PKCS7, new PKCS7Parser());
parsers.put(TYPE_CMS, new PKCS7Parser());
parsers.put(TYPE_ATTRIBUTE_CERTIFICATE, new X509AttributeCertificateParser());
parsers.put(TYPE_EC_PARAMETERS, new ECCurveParamsParser());
parsers.put(TYPE_PUBLIC_KEY, new PublicKeyParser());
parsers.put(TYPE_RSA_PUBLIC_KEY, new RSAPublicKeyParser());
parsers.put(TYPE_RSA_PRIVATE_KEY, new KeyPairParser(new RSAKeyPairParser()));
parsers.put(TYPE_DSA_PRIVATE_KEY, new KeyPairParser(new DSAKeyPairParser()));
parsers.put(TYPE_EC_PRIVATE_KEY, new KeyPairParser(new ECDSAKeyPairParser()));
parsers.put(TYPE_ENCRYPTED_PRIVATE_KEY, new EncryptedPrivateKeyParser());
parsers.put(TYPE_PRIVATE_KEY, new PrivateKeyParser());
}
/**
* Read the next PEM object attempting to interpret the header and
* create a higher level object from the content.
*
* @return the next object in the stream, null if no objects left.
* @throws IOException in case of a parse error.
*/
public Object readObject()
throws IOException
{
PemObject obj = readPemObject();
if (obj == null)
{
return null;
}
String type = obj.getType();
Object pemObjectParser = parsers.get(type);
if (pemObjectParser == null)
{
throw new IOException("unrecognised object: " + type);
}
return ((PemObjectParser)pemObjectParser).parseObject(obj);
}
/**
* @return set of pem object types that can be parsed
* @see PemObject#getType()
*/
public Set<String> getSupportedTypes()
{
return Collections.unmodifiableSet(parsers.keySet());
}
private static class KeyPairParser
implements PemObjectParser
{
private final PEMKeyPairParser pemKeyPairParser;
public KeyPairParser(PEMKeyPairParser pemKeyPairParser)
{
this.pemKeyPairParser = pemKeyPairParser;
}
/**
* Read a Key Pair
*/
public Object parseObject(
PemObject obj)
throws IOException
{
boolean isEncrypted = false;
String dekInfo = null;
List headers = obj.getHeaders();
for (Iterator it = headers.iterator(); it.hasNext();)
{
PemHeader hdr = (PemHeader)it.next();
if (hdr.getName().equals("Proc-Type") && hdr.getValue().equals("4,ENCRYPTED"))
{
isEncrypted = true;
}
else if (hdr.getName().equals("DEK-Info"))
{
dekInfo = hdr.getValue();
}
}
//
// extract the key
//
byte[] keyBytes = obj.getContent();
try
{
if (isEncrypted)
{
StringTokenizer tknz = new StringTokenizer(dekInfo, ",");
String dekAlgName = tknz.nextToken();
byte[] iv = Hex.decode(tknz.nextToken());
return new PEMEncryptedKeyPair(dekAlgName, iv, keyBytes, pemKeyPairParser);
}
return pemKeyPairParser.parse(keyBytes);
}
catch (IOException e)
{
if (isEncrypted)
{
throw new PEMException("exception decoding - please check password and data.", e);
}
else
{
throw new PEMException(e.getMessage(), e);
}
}
catch (IllegalArgumentException e)
{
if (isEncrypted)
{
throw new PEMException("exception decoding - please check password and data.", e);
}
else
{
throw new PEMException(e.getMessage(), e);
}
}
}
}
private static class DSAKeyPairParser
implements PEMKeyPairParser
{
public PEMKeyPair parse(byte[] encoding)
throws IOException
{
try
{
ASN1Sequence seq = ASN1Sequence.getInstance(encoding);
if (seq.size() != 6)
{
throw new PEMException("malformed sequence in DSA private key");
}
// ASN1Integer v = (ASN1Integer)seq.getObjectAt(0);
ASN1Integer p = ASN1Integer.getInstance(seq.getObjectAt(1));
ASN1Integer q = ASN1Integer.getInstance(seq.getObjectAt(2));
ASN1Integer g = ASN1Integer.getInstance(seq.getObjectAt(3));
ASN1Integer y = ASN1Integer.getInstance(seq.getObjectAt(4));
ASN1Integer x = ASN1Integer.getInstance(seq.getObjectAt(5));
return new PEMKeyPair(
new SubjectPublicKeyInfo(new AlgorithmIdentifier(X9ObjectIdentifiers.id_dsa, new DSAParameter(p.getValue(), q.getValue(), g.getValue())), y),
new PrivateKeyInfo(new AlgorithmIdentifier(X9ObjectIdentifiers.id_dsa, new DSAParameter(p.getValue(), q.getValue(), g.getValue())), x));
}
catch (IOException e)
{
throw e;
}
catch (Exception e)
{
throw new PEMException(
"problem creating DSA private key: " + e.toString(), e);
}
}
}
private static class ECDSAKeyPairParser
implements PEMKeyPairParser
{
public PEMKeyPair parse(byte[] encoding)
throws IOException
{
try
{
ASN1Sequence seq = ASN1Sequence.getInstance(encoding);
org.bouncycastle.asn1.sec.ECPrivateKey pKey = org.bouncycastle.asn1.sec.ECPrivateKey.getInstance(seq);
AlgorithmIdentifier algId = new AlgorithmIdentifier(X9ObjectIdentifiers.id_ecPublicKey,
pKey.getParametersObject());
PrivateKeyInfo privInfo = new PrivateKeyInfo(algId, pKey);
ASN1BitString publicKey = pKey.getPublicKey();
SubjectPublicKeyInfo pubInfo = null;
if (publicKey != null)
{
pubInfo = new SubjectPublicKeyInfo(algId, publicKey.getBytes());
}
return new PEMKeyPair(pubInfo, privInfo);
}
catch (IOException e)
{
throw e;
}
catch (Exception e)
{
throw new PEMException(
"problem creating EC private key: " + e.toString(), e);
}
}
}
private static class RSAKeyPairParser
implements PEMKeyPairParser
{
public PEMKeyPair parse(byte[] encoding)
throws IOException
{
try
{
ASN1Sequence seq = ASN1Sequence.getInstance(encoding);
if (seq.size() != 9)
{
throw new PEMException("malformed sequence in RSA private key");
}
org.bouncycastle.asn1.pkcs.RSAPrivateKey keyStruct = org.bouncycastle.asn1.pkcs.RSAPrivateKey.getInstance(seq);
RSAPublicKey pubSpec = new RSAPublicKey(
keyStruct.getModulus(), keyStruct.getPublicExponent());
AlgorithmIdentifier algId = new AlgorithmIdentifier(PKCSObjectIdentifiers.rsaEncryption, DERNull.INSTANCE);
return new PEMKeyPair(new SubjectPublicKeyInfo(algId, pubSpec), new PrivateKeyInfo(algId, keyStruct));
}
catch (IOException e)
{
throw e;
}
catch (Exception e)
{
throw new PEMException(
"problem creating RSA private key: " + e.toString(), e);
}
}
}
private static class PublicKeyParser
implements PemObjectParser
{
public PublicKeyParser()
{
}
public Object parseObject(PemObject obj)
throws IOException
{
return SubjectPublicKeyInfo.getInstance(obj.getContent());
}
}
private static class RSAPublicKeyParser
implements PemObjectParser
{
public RSAPublicKeyParser()
{
}
public Object parseObject(PemObject obj)
throws IOException
{
try
{
AlgorithmIdentifier algId = new AlgorithmIdentifier(PKCSObjectIdentifiers.rsaEncryption, DERNull.INSTANCE);
RSAPublicKey rsaPubStructure = RSAPublicKey.getInstance(obj.getContent());
return new SubjectPublicKeyInfo(algId, rsaPubStructure);
}
catch (IOException e)
{
throw e;
}
catch (Exception e)
{
throw new PEMException("problem extracting key: " + e.toString(), e);
}
}
}
private static class X509CertificateParser
implements PemObjectParser
{
/**
* Reads in a X509Certificate.
*
* @return the X509Certificate
* @throws java.io.IOException if an I/O error occured
*/
public Object parseObject(PemObject obj)
throws IOException
{
try
{
return new X509CertificateHolder(obj.getContent());
}
catch (Exception e)
{
throw new PEMException("problem parsing cert: " + e.toString(), e);
}
}
}
private static class X509TrustedCertificateParser
implements PemObjectParser
{
/**
* Reads in a X509Certificate.
*
* @return the X509Certificate
* @throws java.io.IOException if an I/O error occured
*/
public Object parseObject(PemObject obj)
throws IOException
{
try
{
return new X509TrustedCertificateBlock(obj.getContent());
}
catch (Exception e)
{
throw new PEMException("problem parsing cert: " + e.toString(), e);
}
}
}
private static class X509CRLParser
implements PemObjectParser
{
/**
* Reads in a X509CRL.
*
* @return the X509Certificate
* @throws java.io.IOException if an I/O error occured
*/
public Object parseObject(PemObject obj)
throws IOException
{
try
{
return new X509CRLHolder(obj.getContent());
}
catch (Exception e)
{
throw new PEMException("problem parsing cert: " + e.toString(), e);
}
}
}
private static class PKCS10CertificationRequestParser
implements PemObjectParser
{
/**
* Reads in a PKCS10 certification request.
*
* @return the certificate request.
* @throws java.io.IOException if an I/O error occured
*/
public Object parseObject(PemObject obj)
throws IOException
{
try
{
return new PKCS10CertificationRequest(obj.getContent());
}
catch (Exception e)
{
throw new PEMException("problem parsing certrequest: " + e.toString(), e);
}
}
}
private static class PKCS7Parser
implements PemObjectParser
{
/**
* Reads in a PKCS7 object. This returns a ContentInfo object suitable for use with the CMS
* API.
*
* @return the X509Certificate
* @throws java.io.IOException if an I/O error occured
*/
public Object parseObject(PemObject obj)
throws IOException
{
try
{
return ContentInfo.getInstance(obj.getContent());
}
catch (Exception e)
{
throw new PEMException("problem parsing PKCS7 object: " + e.toString(), e);
}
}
}
private static class X509AttributeCertificateParser
implements PemObjectParser
{
public Object parseObject(PemObject obj)
throws IOException
{
return new X509AttributeCertificateHolder(obj.getContent());
}
}
private static class ECCurveParamsParser
implements PemObjectParser
{
public Object parseObject(PemObject obj)
throws IOException
{
try
{
Object param = ASN1Primitive.fromByteArray(obj.getContent());
if (param instanceof ASN1ObjectIdentifier)
{
return param;
}
else if (param instanceof ASN1Sequence)
{
return X9ECParameters.getInstance(param);
}
else
{
return null; // implicitly CA
}
}
catch (IOException e)
{
throw e;
}
catch (Exception e)
{
throw new PEMException("exception extracting EC named curve: " + e.toString());
}
}
}
private static class EncryptedPrivateKeyParser
implements PemObjectParser
{
public EncryptedPrivateKeyParser()
{
}
/**
* Reads in an EncryptedPrivateKeyInfo
*
* @return the X509Certificate
* @throws java.io.IOException if an I/O error occured
*/
public Object parseObject(PemObject obj)
throws IOException
{
try
{
return new PKCS8EncryptedPrivateKeyInfo(EncryptedPrivateKeyInfo.getInstance(obj.getContent()));
}
catch (Exception e)
{
throw new PEMException("problem parsing ENCRYPTED PRIVATE KEY: " + e.toString(), e);
}
}
}
private static class PrivateKeyParser
implements PemObjectParser
{
public PrivateKeyParser()
{
}
public Object parseObject(PemObject obj)
throws IOException
{
try
{
return PrivateKeyInfo.getInstance(obj.getContent());
}
catch (Exception e)
{
throw new PEMException("problem parsing PRIVATE KEY: " + e.toString(), e);
}
}
}
}