Merge pull request #5714 from alexischr/update_bockbuild
[mono.git] / mcs / class / Mono.Security / Mono.Security.Cryptography / PKCS8.cs
1 //
2 // PKCS8.cs: PKCS #8 - Private-Key Information Syntax Standard
3 //      ftp://ftp.rsasecurity.com/pub/pkcs/doc/pkcs-8.doc
4 //
5 // Author:
6 //      Sebastien Pouliot <sebastien@xamarin.com>
7 //
8 // (C) 2003 Motus Technologies Inc. (http://www.motus.com)
9 // Copyright (C) 2004-2006 Novell Inc. (http://www.novell.com)
10 // Copyright 2013 Xamarin Inc. (http://www.xamarin.com)
11 //
12 // Permission is hereby granted, free of charge, to any person obtaining
13 // a copy of this software and associated documentation files (the
14 // "Software"), to deal in the Software without restriction, including
15 // without limitation the rights to use, copy, modify, merge, publish,
16 // distribute, sublicense, and/or sell copies of the Software, and to
17 // permit persons to whom the Software is furnished to do so, subject to
18 // the following conditions:
19 // 
20 // The above copyright notice and this permission notice shall be
21 // included in all copies or substantial portions of the Software.
22 // 
23 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
24 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
25 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
26 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
27 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
28 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
29 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
30 //
31
32 using System;
33 using System.Collections;
34 using System.Security.Cryptography;
35
36 using Mono.Security.X509;
37
38 namespace Mono.Security.Cryptography {
39
40 #if !INSIDE_CORLIB
41         public 
42 #endif
43         sealed class PKCS8 {
44
45                 public enum KeyInfo {
46                         PrivateKey,
47                         EncryptedPrivateKey,
48                         Unknown
49                 }
50
51                 private PKCS8 () 
52                 {
53                 }
54
55                 static public KeyInfo GetType (byte[] data) 
56                 {
57                         if (data == null)
58                                 throw new ArgumentNullException ("data");
59
60                         KeyInfo ki = KeyInfo.Unknown;
61                         try {
62                                 ASN1 top = new ASN1 (data);
63                                 if ((top.Tag == 0x30) && (top.Count > 0)) {
64                                         ASN1 firstLevel = top [0];
65                                         switch (firstLevel.Tag) {
66                                                 case 0x02:
67                                                         ki = KeyInfo.PrivateKey;
68                                                         break;
69                                                 case 0x30:
70                                                         ki = KeyInfo.EncryptedPrivateKey;
71                                                         break;
72                                         }
73                                 }
74                         }
75                         catch {
76                                 throw new CryptographicException ("invalid ASN.1 data");
77                         }
78                         return ki;
79                 }
80
81                 /*
82                  * PrivateKeyInfo ::= SEQUENCE {
83                  *      version Version,
84                  *      privateKeyAlgorithm PrivateKeyAlgorithmIdentifier,
85                  *      privateKey PrivateKey,
86                  *      attributes [0] IMPLICIT Attributes OPTIONAL 
87                  * }
88                  * 
89                  * Version ::= INTEGER
90                  * 
91                  * PrivateKeyAlgorithmIdentifier ::= AlgorithmIdentifier
92                  * 
93                  * PrivateKey ::= OCTET STRING
94                  * 
95                  * Attributes ::= SET OF Attribute
96                  */
97                 public class PrivateKeyInfo {
98
99                         private int _version;
100                         private string _algorithm;
101                         private byte[] _key;
102                         private ArrayList _list;
103
104                         public PrivateKeyInfo () 
105                         {
106                                 _version = 0;
107                                 _list = new ArrayList ();
108                         }
109
110                         public PrivateKeyInfo (byte[] data) : this () 
111                         {
112                                 Decode (data);
113                         }
114
115                         // properties
116
117                         public string Algorithm {
118                                 get { return _algorithm; }
119                                 set { _algorithm = value; }
120                         }
121
122                         public ArrayList Attributes {
123                                 get { return _list; }
124                         }
125
126                         public byte[] PrivateKey {
127                                 get {
128                                         if (_key == null)
129                                                 return null;
130                                         return (byte[]) _key.Clone (); 
131                                 }
132                                 set { 
133                                         if (value == null)
134                                                 throw new ArgumentNullException ("PrivateKey");
135                                         _key = (byte[]) value.Clone (); 
136                                 }
137                         }
138
139                         public int Version {
140                                 get { return _version; }
141                                 set { 
142                                         if (value < 0)
143                                                 throw new ArgumentOutOfRangeException ("negative version");
144                                         _version = value; 
145                                 }
146                         }
147
148                         // methods
149
150                         private void Decode (byte[] data) 
151                         {
152                                 ASN1 privateKeyInfo = new ASN1 (data);
153                                 if (privateKeyInfo.Tag != 0x30)
154                                         throw new CryptographicException ("invalid PrivateKeyInfo");
155
156                                 ASN1 version = privateKeyInfo [0];
157                                 if (version.Tag != 0x02)
158                                         throw new CryptographicException ("invalid version");
159                                 _version = version.Value [0];
160
161                                 ASN1 privateKeyAlgorithm = privateKeyInfo [1];
162                                 if (privateKeyAlgorithm.Tag != 0x30)
163                                         throw new CryptographicException ("invalid algorithm");
164                                 
165                                 ASN1 algorithm = privateKeyAlgorithm [0];
166                                 if (algorithm.Tag != 0x06)
167                                         throw new CryptographicException ("missing algorithm OID");
168                                 _algorithm = ASN1Convert.ToOid (algorithm);
169
170                                 ASN1 privateKey = privateKeyInfo [2];
171                                 _key = privateKey.Value;
172
173                                 // attributes [0] IMPLICIT Attributes OPTIONAL
174                                 if (privateKeyInfo.Count > 3) {
175                                         ASN1 attributes = privateKeyInfo [3];
176                                         for (int i=0; i < attributes.Count; i++) {
177                                                 _list.Add (attributes [i]);
178                                         }
179                                 }
180                         }
181
182                         public byte[] GetBytes () 
183                         {
184                                 ASN1 privateKeyAlgorithm = new ASN1 (0x30);
185                                 privateKeyAlgorithm.Add (ASN1Convert.FromOid (_algorithm));
186                                 privateKeyAlgorithm.Add (new ASN1 (0x05)); // ASN.1 NULL
187
188                                 ASN1 pki = new ASN1 (0x30);
189                                 pki.Add (new ASN1 (0x02, new byte [1] { (byte) _version }));
190                                 pki.Add (privateKeyAlgorithm);
191                                 pki.Add (new ASN1 (0x04, _key));
192
193                                 if (_list.Count > 0) {
194                                         ASN1 attributes = new ASN1 (0xA0);
195                                         foreach (ASN1 attribute in _list) {
196                                                 attributes.Add (attribute);
197                                         }
198                                         pki.Add (attributes);
199                                 }
200
201                                 return pki.GetBytes ();
202                         }
203
204                         // static methods
205
206                         static private byte[] RemoveLeadingZero (byte[] bigInt) 
207                         {
208                                 int start = 0;
209                                 int length = bigInt.Length;
210                                 if (bigInt [0] == 0x00) {
211                                         start = 1;
212                                         length--;
213                                 }
214                                 byte[] bi = new byte [length];
215                                 Buffer.BlockCopy (bigInt, start, bi, 0, length);
216                                 return bi;
217                         }
218
219                         static private byte[] Normalize (byte[] bigInt, int length) 
220                         {
221                                 if (bigInt.Length == length)
222                                         return bigInt;
223                                 else if (bigInt.Length > length)
224                                         return RemoveLeadingZero (bigInt);
225                                 else {
226                                         // pad with 0
227                                         byte[] bi = new byte [length];
228                                         Buffer.BlockCopy (bigInt, 0, bi, (length - bigInt.Length), bigInt.Length);
229                                         return bi;
230                                 }
231                         }
232                         
233                         /*
234                          * RSAPrivateKey ::= SEQUENCE {
235                          *      version           Version, 
236                          *      modulus           INTEGER,  -- n
237                          *      publicExponent    INTEGER,  -- e
238                          *      privateExponent   INTEGER,  -- d
239                          *      prime1            INTEGER,  -- p
240                          *      prime2            INTEGER,  -- q
241                          *      exponent1         INTEGER,  -- d mod (p-1)
242                          *      exponent2         INTEGER,  -- d mod (q-1) 
243                          *      coefficient       INTEGER,  -- (inverse of q) mod p
244                          *      otherPrimeInfos   OtherPrimeInfos OPTIONAL 
245                          * }
246                          */
247                         static public RSA DecodeRSA (byte[] keypair) 
248                         {
249                                 ASN1 privateKey = new ASN1 (keypair);
250                                 if (privateKey.Tag != 0x30)
251                                         throw new CryptographicException ("invalid private key format");
252
253                                 ASN1 version = privateKey [0];
254                                 if (version.Tag != 0x02)
255                                         throw new CryptographicException ("missing version");
256
257                                 if (privateKey.Count < 9)
258                                         throw new CryptographicException ("not enough key parameters");
259
260                                 RSAParameters param = new RSAParameters ();
261                                 // note: MUST remove leading 0 - else MS wont import the key
262                                 param.Modulus = RemoveLeadingZero (privateKey [1].Value);
263                                 int keysize = param.Modulus.Length;
264                                 int keysize2 = (keysize >> 1); // half-size
265                                 // size must be normalized - else MS wont import the key
266                                 param.D = Normalize (privateKey [3].Value, keysize);
267                                 param.DP = Normalize (privateKey [6].Value, keysize2);
268                                 param.DQ = Normalize (privateKey [7].Value, keysize2);
269                                 param.Exponent = RemoveLeadingZero (privateKey [2].Value);
270                                 param.InverseQ = Normalize (privateKey [8].Value, keysize2);
271                                 param.P = Normalize (privateKey [4].Value, keysize2);
272                                 param.Q = Normalize (privateKey [5].Value, keysize2);
273
274                                 RSA rsa = null;
275                                 try {
276                                         rsa = RSA.Create ();
277                                         rsa.ImportParameters (param);
278                                 }
279                                 catch (CryptographicException) {
280 #if MONOTOUCH
281                                         // there's no machine-wide store available for iOS so we can drop the dependency on
282                                         // CspParameters (which drops other things, like XML key persistance, unless used elsewhere)
283                                         throw;
284 #else
285                                         // this may cause problem when this code is run under
286                                         // the SYSTEM identity on Windows (e.g. ASP.NET). See
287                                         // http://bugzilla.ximian.com/show_bug.cgi?id=77559
288                                         CspParameters csp = new CspParameters ();
289                                         csp.Flags = CspProviderFlags.UseMachineKeyStore;
290                                         rsa = new RSACryptoServiceProvider (csp);
291                                         rsa.ImportParameters (param);
292 #endif
293                                 }
294                                 return rsa;
295                         }
296
297                         /*
298                          * RSAPrivateKey ::= SEQUENCE {
299                          *      version           Version, 
300                          *      modulus           INTEGER,  -- n
301                          *      publicExponent    INTEGER,  -- e
302                          *      privateExponent   INTEGER,  -- d
303                          *      prime1            INTEGER,  -- p
304                          *      prime2            INTEGER,  -- q
305                          *      exponent1         INTEGER,  -- d mod (p-1)
306                          *      exponent2         INTEGER,  -- d mod (q-1) 
307                          *      coefficient       INTEGER,  -- (inverse of q) mod p
308                          *      otherPrimeInfos   OtherPrimeInfos OPTIONAL 
309                          * }
310                          */
311                         static public byte[] Encode (RSA rsa) 
312                         {
313                                 RSAParameters param = rsa.ExportParameters (true);
314
315                                 ASN1 rsaPrivateKey = new ASN1 (0x30);
316                                 rsaPrivateKey.Add (new ASN1 (0x02, new byte [1] { 0x00 }));
317                                 rsaPrivateKey.Add (ASN1Convert.FromUnsignedBigInteger (param.Modulus));
318                                 rsaPrivateKey.Add (ASN1Convert.FromUnsignedBigInteger (param.Exponent));
319                                 rsaPrivateKey.Add (ASN1Convert.FromUnsignedBigInteger (param.D));
320                                 rsaPrivateKey.Add (ASN1Convert.FromUnsignedBigInteger (param.P));
321                                 rsaPrivateKey.Add (ASN1Convert.FromUnsignedBigInteger (param.Q));
322                                 rsaPrivateKey.Add (ASN1Convert.FromUnsignedBigInteger (param.DP));
323                                 rsaPrivateKey.Add (ASN1Convert.FromUnsignedBigInteger (param.DQ));
324                                 rsaPrivateKey.Add (ASN1Convert.FromUnsignedBigInteger (param.InverseQ));
325
326                                 return rsaPrivateKey.GetBytes ();
327                         }
328
329                         // DSA only encode it's X private key inside an ASN.1 INTEGER (Hint: Tag == 0x02)
330                         // which isn't enough for rebuilding the keypair. The other parameters
331                         // can be found (98% of the time) in the X.509 certificate associated
332                         // with the private key or (2% of the time) the parameters are in it's
333                         // issuer X.509 certificate (not supported in the .NET framework).
334                         static public DSA DecodeDSA (byte[] privateKey, DSAParameters dsaParameters) 
335                         {
336                                 ASN1 pvk = new ASN1 (privateKey);
337                                 if (pvk.Tag != 0x02)
338                                         throw new CryptographicException ("invalid private key format");
339
340                                 // X is ALWAYS 20 bytes (no matter if the key length is 512 or 1024 bits)
341                                 dsaParameters.X = Normalize (pvk.Value, 20);
342                                 DSA dsa = DSA.Create ();
343                                 dsa.ImportParameters (dsaParameters);
344                                 return dsa;
345                         }
346
347                         static public byte[] Encode (DSA dsa) 
348                         {
349                                 DSAParameters param = dsa.ExportParameters (true);
350                                 return ASN1Convert.FromUnsignedBigInteger (param.X).GetBytes ();
351                         }
352
353                         static public byte[] Encode (AsymmetricAlgorithm aa) 
354                         {
355                                 if (aa is RSA)
356                                         return Encode ((RSA)aa);
357                                 else if (aa is DSA)
358                                         return Encode ((DSA)aa);
359                                 else
360                                         throw new CryptographicException ("Unknown asymmetric algorithm {0}", aa.ToString ());
361                         }
362                 }
363
364                 /*
365                  * EncryptedPrivateKeyInfo ::= SEQUENCE {
366                  *      encryptionAlgorithm EncryptionAlgorithmIdentifier,
367                  *      encryptedData EncryptedData 
368                  * }
369                  * 
370                  * EncryptionAlgorithmIdentifier ::= AlgorithmIdentifier
371                  * 
372                  * EncryptedData ::= OCTET STRING
373                  * 
374                  * --
375                  *  AlgorithmIdentifier  ::= SEQUENCE {
376                  *      algorithm  OBJECT IDENTIFIER,
377                  *      parameters ANY DEFINED BY algorithm OPTIONAL
378                  * }
379                  * 
380                  * -- from PKCS#5
381                  * PBEParameter ::= SEQUENCE {
382                  *      salt OCTET STRING SIZE(8),
383                  *      iterationCount INTEGER 
384                  * }
385                  */
386                 public class EncryptedPrivateKeyInfo {
387
388                         private string _algorithm;
389                         private byte[] _salt;
390                         private int _iterations;
391                         private byte[] _data;
392
393                         public EncryptedPrivateKeyInfo () {}
394
395                         public EncryptedPrivateKeyInfo (byte[] data) : this () 
396                         {
397                                 Decode (data);
398                         }
399
400                         // properties
401
402                         public string Algorithm {
403                                 get { return _algorithm; }
404                                 set { _algorithm = value; }
405                         }
406
407                         public byte[] EncryptedData {
408                                 get { return (_data == null) ? null : (byte[]) _data.Clone (); }
409                                 set { _data = (value == null) ? null : (byte[]) value.Clone (); }
410                         }
411
412                         public byte[] Salt {
413                                 get { 
414                                         if (_salt == null) {
415                                                 RandomNumberGenerator rng = RandomNumberGenerator.Create ();
416                                                 _salt = new byte [8];
417                                                 rng.GetBytes (_salt);
418                                         }
419                                         return (byte[]) _salt.Clone (); 
420                                 }
421                                 set { _salt = (byte[]) value.Clone (); }
422                         }
423
424                         public int IterationCount {
425                                 get { return _iterations; }
426                                 set { 
427                                         if (value < 0)
428                                                 throw new ArgumentOutOfRangeException ("IterationCount", "Negative");
429                                         _iterations = value; 
430                                 }
431                         }
432
433                         // methods
434
435                         private void Decode (byte[] data) 
436                         {
437                                 ASN1 encryptedPrivateKeyInfo = new ASN1 (data);
438                                 if (encryptedPrivateKeyInfo.Tag != 0x30)
439                                         throw new CryptographicException ("invalid EncryptedPrivateKeyInfo");
440
441                                 ASN1 encryptionAlgorithm = encryptedPrivateKeyInfo [0];
442                                 if (encryptionAlgorithm.Tag != 0x30)
443                                         throw new CryptographicException ("invalid encryptionAlgorithm");
444                                 ASN1 algorithm = encryptionAlgorithm [0];
445                                 if (algorithm.Tag != 0x06)
446                                         throw new CryptographicException ("invalid algorithm");
447                                 _algorithm = ASN1Convert.ToOid (algorithm);
448                                 // parameters ANY DEFINED BY algorithm OPTIONAL
449                                 if (encryptionAlgorithm.Count > 1) {
450                                         ASN1 parameters = encryptionAlgorithm [1];
451                                         if (parameters.Tag != 0x30)
452                                                 throw new CryptographicException ("invalid parameters");
453
454                                         ASN1 salt = parameters [0];
455                                         if (salt.Tag != 0x04)
456                                                 throw new CryptographicException ("invalid salt");
457                                         _salt = salt.Value;
458
459                                         ASN1 iterationCount = parameters [1];
460                                         if (iterationCount.Tag != 0x02)
461                                                 throw new CryptographicException ("invalid iterationCount");
462                                         _iterations = ASN1Convert.ToInt32 (iterationCount);
463                                 }
464
465                                 ASN1 encryptedData = encryptedPrivateKeyInfo [1];
466                                 if (encryptedData.Tag != 0x04)
467                                         throw new CryptographicException ("invalid EncryptedData");
468                                 _data = encryptedData.Value;
469                         }
470
471                         // Note: PKCS#8 doesn't define how to generate the key required for encryption
472                         // so you're on your own. Just don't try to copy the big guys too much ;)
473                         // Netscape:    http://www.cs.auckland.ac.nz/~pgut001/pubs/netscape.txt
474                         // Microsoft:   http://www.cs.auckland.ac.nz/~pgut001/pubs/breakms.txt
475                         public byte[] GetBytes ()
476                         {
477                                 if (_algorithm == null)
478                                         throw new CryptographicException ("No algorithm OID specified");
479
480                                 ASN1 encryptionAlgorithm = new ASN1 (0x30);
481                                 encryptionAlgorithm.Add (ASN1Convert.FromOid (_algorithm));
482
483                                 // parameters ANY DEFINED BY algorithm OPTIONAL
484                                 if ((_iterations > 0) || (_salt != null)) {
485                                         ASN1 salt = new ASN1 (0x04, _salt);
486                                         ASN1 iterations = ASN1Convert.FromInt32 (_iterations);
487
488                                         ASN1 parameters = new ASN1 (0x30);
489                                         parameters.Add (salt);
490                                         parameters.Add (iterations);
491                                         encryptionAlgorithm.Add (parameters);
492                                 }
493
494                                 // encapsulates EncryptedData into an OCTET STRING
495                                 ASN1 encryptedData = new ASN1 (0x04, _data);
496
497                                 ASN1 encryptedPrivateKeyInfo = new ASN1 (0x30);
498                                 encryptedPrivateKeyInfo.Add (encryptionAlgorithm);
499                                 encryptedPrivateKeyInfo.Add (encryptedData);
500
501                                 return encryptedPrivateKeyInfo.GetBytes ();
502                         }
503                 }
504         }
505 }