summary refs log tree commit diff
path: root/crypto/src/openssl/PEMReader.cs
blob: a2c4fd1d6fc27623368cb49a2bfe6a948fa11969 (plain) (blame)
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
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;

using Org.BouncyCastle.Asn1;
using Org.BouncyCastle.Asn1.Pkcs;
using Org.BouncyCastle.Asn1.Sec;
using Org.BouncyCastle.Asn1.X509;
using Org.BouncyCastle.Asn1.X9;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Generators;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Pkcs;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.Utilities;
using Org.BouncyCastle.Utilities.Collections;
using Org.BouncyCastle.Utilities.Encoders;
using Org.BouncyCastle.Utilities.IO.Pem;
using Org.BouncyCastle.X509;

namespace Org.BouncyCastle.OpenSsl
{
    /**
    * Class for reading 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. Keys and
    * Certificates will be returned using the appropriate java.security type.</p>
    */
    public class PemReader
        : Utilities.IO.Pem.PemReader
    {
        //private static readonly Dictionary<string, PemObjectParser> Parsers = new Dictionary<string, PemObjectParser>();

        static PemReader()
        {
//			Parsers.Add("CERTIFICATE REQUEST", new PKCS10CertificationRequestParser());
//			Parsers.Add("NEW CERTIFICATE REQUEST", new PKCS10CertificationRequestParser());
//			Parsers.Add("CERTIFICATE", new X509CertificateParser(provider));
//			Parsers.Add("X509 CERTIFICATE", new X509CertificateParser(provider));
//			Parsers.Add("X509 CRL", new X509CRLParser(provider));
//			Parsers.Add("PKCS7", new PKCS7Parser());
//			Parsers.Add("ATTRIBUTE CERTIFICATE", new X509AttributeCertificateParser());
//			Parsers.Add("EC PARAMETERS", new ECNamedCurveSpecParser());
//			Parsers.Add("PUBLIC KEY", new PublicKeyParser(provider));
//			Parsers.Add("RSA PUBLIC KEY", new RSAPublicKeyParser(provider));
//			Parsers.Add("RSA PRIVATE KEY", new RSAKeyPairParser(provider));
//			Parsers.Add("DSA PRIVATE KEY", new DSAKeyPairParser(provider));
//			Parsers.Add("EC PRIVATE KEY", new ECDSAKeyPairParser(provider));
//			Parsers.Add("ENCRYPTED PRIVATE KEY", new EncryptedPrivateKeyParser(provider));
//			Parsers.Add("PRIVATE KEY", new PrivateKeyParser(provider));
        }

        private readonly IPasswordFinder pFinder;

        /**
        * Create a new PemReader
        *
        * @param reader the Reader
        */
        public PemReader(
            TextReader reader)
            : this(reader, null)
        {
        }

        /**
        * Create a new PemReader with a password finder
        *
        * @param reader the Reader
        * @param pFinder the password finder
        */
        public PemReader(
            TextReader		reader,
            IPasswordFinder	pFinder)
            : base(reader)
        {
            this.pFinder = pFinder;
        }

        public object ReadObject()
        {
            PemObject obj = ReadPemObject();

            if (obj == null)
                return null;

            // TODO Follow Java build and map to parser objects?
//			if (parsers.Contains(obj.Type))
//				return ((PemObjectParser)parsers[obj.Type]).ParseObject(obj);

            if (Platform.EndsWith(obj.Type, "PRIVATE KEY"))
                return ReadPrivateKey(obj);

            switch (obj.Type)
            {
                case "PUBLIC KEY":
                    return ReadPublicKey(obj);
                case "RSA PUBLIC KEY":
                    return ReadRsaPublicKey(obj);
                case "CERTIFICATE REQUEST":
                case "NEW CERTIFICATE REQUEST":
                    return ReadCertificateRequest(obj);
                case "CERTIFICATE":
                case "X509 CERTIFICATE":
                    return ReadCertificate(obj);
                case "PKCS7":
                case "CMS":
                    return ReadPkcs7(obj);
                case "X509 CRL":
                    return ReadCrl(obj);
                case "ATTRIBUTE CERTIFICATE":
                    return ReadAttributeCertificate(obj);
                // TODO Add back in when tests done, and return type issue resolved
                //case "EC PARAMETERS":
                //	return ReadECParameters(obj);
                default:
                    throw new IOException("unrecognised object: " + obj.Type);
            }
        }

        private AsymmetricKeyParameter ReadRsaPublicKey(PemObject pemObject)
        {
            RsaPublicKeyStructure rsaPubStructure = RsaPublicKeyStructure.GetInstance(
                Asn1Object.FromByteArray(pemObject.Content));

            return new RsaKeyParameters(
                false, // not private
                rsaPubStructure.Modulus, 
                rsaPubStructure.PublicExponent);
        }

        private AsymmetricKeyParameter ReadPublicKey(PemObject pemObject)
        {
            return PublicKeyFactory.CreateKey(pemObject.Content);
        }

        /**
        * Reads in a X509Certificate.
        *
        * @return the X509Certificate
        * @throws IOException if an I/O error occured
        */
        private X509Certificate ReadCertificate(PemObject pemObject)
        {
            try
            {
                return new X509CertificateParser().ReadCertificate(pemObject.Content);
            }
            catch (Exception e)
            {
                throw new PemException("problem parsing cert: " + e.ToString());
            }
        }

        /**
        * Reads in a X509CRL.
        *
        * @return the X509Certificate
        * @throws IOException if an I/O error occured
        */
        private X509Crl ReadCrl(PemObject pemObject)
        {
            try
            {
                return new X509CrlParser().ReadCrl(pemObject.Content);
            }
            catch (Exception e)
            {
                throw new PemException("problem parsing cert: " + e.ToString());
            }
        }

        /**
        * Reads in a PKCS10 certification request.
        *
        * @return the certificate request.
        * @throws IOException if an I/O error occured
        */
        private Pkcs10CertificationRequest ReadCertificateRequest(PemObject pemObject)
        {
            try
            {
                return new Pkcs10CertificationRequest(pemObject.Content);
            }
            catch (Exception e)
            {
                throw new PemException("problem parsing cert: " + e.ToString());
            }
        }

        /**
        * Reads in a X509 Attribute Certificate.
        *
        * @return the X509 Attribute Certificate
        * @throws IOException if an I/O error occured
        */
        private X509V2AttributeCertificate ReadAttributeCertificate(PemObject pemObject)
        {
            return new X509V2AttributeCertificate(pemObject.Content);
        }

        /**
        * Reads in a PKCS7 object. This returns a ContentInfo object suitable for use with the CMS
        * API.
        *
        * @return the X509Certificate
        * @throws IOException if an I/O error occured
        */
        // TODO Consider returning Asn1.Pkcs.ContentInfo
        private Asn1.Cms.ContentInfo ReadPkcs7(PemObject pemObject)
        {
            try
            {
                return Asn1.Cms.ContentInfo.GetInstance(
                    Asn1Object.FromByteArray(pemObject.Content));
            }
            catch (Exception e)
            {
                throw new PemException("problem parsing PKCS7 object: " + e.ToString());
            }
        }

        /**
        * Read a Key Pair
        */
        private object ReadPrivateKey(PemObject pemObject)
        {
            //
            // extract the key
            //
            Debug.Assert(Platform.EndsWith(pemObject.Type, "PRIVATE KEY"));

            string type = pemObject.Type.Substring(0, pemObject.Type.Length - "PRIVATE KEY".Length).Trim();
            byte[] keyBytes = pemObject.Content;

            var fields = new Dictionary<string, string>();
            foreach (PemHeader header in pemObject.Headers)
            {
                fields[header.Name] = header.Value;
            }

            string procType = CollectionUtilities.GetValueOrNull(fields, "Proc-Type");

            if (procType == "4,ENCRYPTED")
            {
                if (pFinder == null)
                    throw new PasswordException("No password finder specified, but a password is required");

                char[] password = pFinder.GetPassword();
                if (password == null)
                    throw new PasswordException("Password is null, but a password is required");

                if (!fields.TryGetValue("DEK-Info", out var dekInfo))
                    throw new PemException("missing DEK-info");

                string[] tknz = dekInfo.Split(',');

                string dekAlgName = tknz[0].Trim();
                byte[] iv = Hex.Decode(tknz[1].Trim());

                keyBytes = PemUtilities.Crypt(false, keyBytes, password, dekAlgName, iv);
            }

            try
            {
                AsymmetricKeyParameter pubSpec, privSpec;
                Asn1Sequence seq = Asn1Sequence.GetInstance(keyBytes);

                switch (type)
                {
                    case "RSA":
                    {
                        if (seq.Count != 9)
                            throw new PemException("malformed sequence in RSA private key");

                        RsaPrivateKeyStructure rsa = RsaPrivateKeyStructure.GetInstance(seq);

                        pubSpec = new RsaKeyParameters(false, rsa.Modulus, rsa.PublicExponent);
                        privSpec = new RsaPrivateCrtKeyParameters(
                            rsa.Modulus, rsa.PublicExponent, rsa.PrivateExponent,
                            rsa.Prime1, rsa.Prime2, rsa.Exponent1, rsa.Exponent2,
                            rsa.Coefficient);

                        break;
                    }

                    case "DSA":
                    {
                        if (seq.Count != 6)
                            throw new PemException("malformed sequence in DSA private key");

                        // TODO Create an ASN1 object somewhere for this?
                        //DerInteger v = (DerInteger)seq[0];
                        DerInteger p = (DerInteger)seq[1];
                        DerInteger q = (DerInteger)seq[2];
                        DerInteger g = (DerInteger)seq[3];
                        DerInteger y = (DerInteger)seq[4];
                        DerInteger x = (DerInteger)seq[5];

                        DsaParameters parameters = new DsaParameters(p.Value, q.Value, g.Value);

                        privSpec = new DsaPrivateKeyParameters(x.Value, parameters);
                        pubSpec = new DsaPublicKeyParameters(y.Value, parameters);

                        break;
                    }

                    case "EC":
                    {
                        ECPrivateKeyStructure pKey = ECPrivateKeyStructure.GetInstance(seq);
                        AlgorithmIdentifier algId = new AlgorithmIdentifier(
                            X9ObjectIdentifiers.IdECPublicKey, pKey.GetParameters());

                        PrivateKeyInfo privInfo = new PrivateKeyInfo(algId, pKey.ToAsn1Object());

                        // TODO Are the keys returned here ECDSA, as Java version forces?
                        privSpec = PrivateKeyFactory.CreateKey(privInfo);

                        DerBitString pubKey = pKey.GetPublicKey();
                        if (pubKey != null)
                        {
                            SubjectPublicKeyInfo pubInfo = new SubjectPublicKeyInfo(algId, pubKey.GetBytes());

                            // TODO Are the keys returned here ECDSA, as Java version forces?
                            pubSpec = PublicKeyFactory.CreateKey(pubInfo);
                        }
                        else
                        {
                            pubSpec = ECKeyPairGenerator.GetCorrespondingPublicKey(
                                (ECPrivateKeyParameters)privSpec);
                        }

                        break;
                    }

                    case "ENCRYPTED":
                    {
                        char[] password = pFinder.GetPassword();

                        if (password == null)
                            throw new PasswordException("Password is null, but a password is required");

                        return PrivateKeyFactory.DecryptKey(password, EncryptedPrivateKeyInfo.GetInstance(seq));
                    }

                    case "":
                    {
                        return PrivateKeyFactory.CreateKey(PrivateKeyInfo.GetInstance(seq));
                    }

                    default:
                        throw new ArgumentException("Unknown key type: " + type, "type");
                }

                return new AsymmetricCipherKeyPair(pubSpec, privSpec);
            }
            catch (IOException e)
            {
                throw e;
            }
            catch (Exception e)
            {
                throw new PemException(
                    "problem creating " + type + " private key: " + e.ToString());
            }
        }

        //private X9ECParameters ReadECParameters(PemObject pemObject)
        //{
        //    DerObjectIdentifier oid = (DerObjectIdentifier)Asn1Object.FromByteArray(pemObject.Content);

        //    //return ECNamedCurveTable.getParameterSpec(oid.Id);
        //    return GetCurveParameters(oid.Id);
        //}

        //private static X9ECParameters GetCurveParameters(string name)
        //{
        //    return ECKeyPairGenerator.FindECCurveByName(name) ?? throw new Exception("unknown curve name: " + name);
        //}
    }
}