PKCS8.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505
  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. using System;
  32. using System.Collections;
  33. using System.Security.Cryptography;
  34. using Mono.Security.X509;
  35. namespace Mono.Security.Cryptography {
  36. #if !INSIDE_CORLIB
  37. public
  38. #endif
  39. sealed class PKCS8 {
  40. public enum KeyInfo {
  41. PrivateKey,
  42. EncryptedPrivateKey,
  43. Unknown
  44. }
  45. private PKCS8 ()
  46. {
  47. }
  48. static public KeyInfo GetType (byte[] data)
  49. {
  50. if (data == null)
  51. throw new ArgumentNullException ("data");
  52. KeyInfo ki = KeyInfo.Unknown;
  53. try {
  54. ASN1 top = new ASN1 (data);
  55. if ((top.Tag == 0x30) && (top.Count > 0)) {
  56. ASN1 firstLevel = top [0];
  57. switch (firstLevel.Tag) {
  58. case 0x02:
  59. ki = KeyInfo.PrivateKey;
  60. break;
  61. case 0x30:
  62. ki = KeyInfo.EncryptedPrivateKey;
  63. break;
  64. }
  65. }
  66. }
  67. catch {
  68. throw new CryptographicException ("invalid ASN.1 data");
  69. }
  70. return ki;
  71. }
  72. /*
  73. * PrivateKeyInfo ::= SEQUENCE {
  74. * version Version,
  75. * privateKeyAlgorithm PrivateKeyAlgorithmIdentifier,
  76. * privateKey PrivateKey,
  77. * attributes [0] IMPLICIT Attributes OPTIONAL
  78. * }
  79. *
  80. * Version ::= INTEGER
  81. *
  82. * PrivateKeyAlgorithmIdentifier ::= AlgorithmIdentifier
  83. *
  84. * PrivateKey ::= OCTET STRING
  85. *
  86. * Attributes ::= SET OF Attribute
  87. */
  88. public class PrivateKeyInfo {
  89. private int _version;
  90. private string _algorithm;
  91. private byte[] _key;
  92. private ArrayList _list;
  93. public PrivateKeyInfo ()
  94. {
  95. _version = 0;
  96. _list = new ArrayList ();
  97. }
  98. public PrivateKeyInfo (byte[] data) : this ()
  99. {
  100. Decode (data);
  101. }
  102. // properties
  103. public string Algorithm {
  104. get { return _algorithm; }
  105. set { _algorithm = value; }
  106. }
  107. public ArrayList Attributes {
  108. get { return _list; }
  109. }
  110. public byte[] PrivateKey {
  111. get {
  112. if (_key == null)
  113. return null;
  114. return (byte[]) _key.Clone ();
  115. }
  116. set {
  117. if (value == null)
  118. throw new ArgumentNullException ("PrivateKey");
  119. _key = (byte[]) value.Clone ();
  120. }
  121. }
  122. public int Version {
  123. get { return _version; }
  124. set {
  125. if (value < 0)
  126. throw new ArgumentOutOfRangeException ("negative version");
  127. _version = value;
  128. }
  129. }
  130. // methods
  131. private void Decode (byte[] data)
  132. {
  133. ASN1 privateKeyInfo = new ASN1 (data);
  134. if (privateKeyInfo.Tag != 0x30)
  135. throw new CryptographicException ("invalid PrivateKeyInfo");
  136. ASN1 version = privateKeyInfo [0];
  137. if (version.Tag != 0x02)
  138. throw new CryptographicException ("invalid version");
  139. _version = version.Value [0];
  140. ASN1 privateKeyAlgorithm = privateKeyInfo [1];
  141. if (privateKeyAlgorithm.Tag != 0x30)
  142. throw new CryptographicException ("invalid algorithm");
  143. ASN1 algorithm = privateKeyAlgorithm [0];
  144. if (algorithm.Tag != 0x06)
  145. throw new CryptographicException ("missing algorithm OID");
  146. _algorithm = ASN1Convert.ToOid (algorithm);
  147. ASN1 privateKey = privateKeyInfo [2];
  148. _key = privateKey.Value;
  149. // attributes [0] IMPLICIT Attributes OPTIONAL
  150. if (privateKeyInfo.Count > 3) {
  151. ASN1 attributes = privateKeyInfo [3];
  152. for (int i=0; i < attributes.Count; i++) {
  153. _list.Add (attributes [i]);
  154. }
  155. }
  156. }
  157. public byte[] GetBytes ()
  158. {
  159. ASN1 privateKeyAlgorithm = new ASN1 (0x30);
  160. privateKeyAlgorithm.Add (ASN1Convert.FromOid (_algorithm));
  161. privateKeyAlgorithm.Add (new ASN1 (0x05)); // ASN.1 NULL
  162. ASN1 pki = new ASN1 (0x30);
  163. pki.Add (new ASN1 (0x02, new byte [1] { (byte) _version }));
  164. pki.Add (privateKeyAlgorithm);
  165. pki.Add (new ASN1 (0x04, _key));
  166. if (_list.Count > 0) {
  167. ASN1 attributes = new ASN1 (0xA0);
  168. foreach (ASN1 attribute in _list) {
  169. attributes.Add (attribute);
  170. }
  171. pki.Add (attributes);
  172. }
  173. return pki.GetBytes ();
  174. }
  175. // static methods
  176. static private byte[] RemoveLeadingZero (byte[] bigInt)
  177. {
  178. int start = 0;
  179. int length = bigInt.Length;
  180. if (bigInt [0] == 0x00) {
  181. start = 1;
  182. length--;
  183. }
  184. byte[] bi = new byte [length];
  185. Buffer.BlockCopy (bigInt, start, bi, 0, length);
  186. return bi;
  187. }
  188. static private byte[] Normalize (byte[] bigInt, int length)
  189. {
  190. if (bigInt.Length == length)
  191. return bigInt;
  192. else if (bigInt.Length > length)
  193. return RemoveLeadingZero (bigInt);
  194. else {
  195. // pad with 0
  196. byte[] bi = new byte [length];
  197. Buffer.BlockCopy (bigInt, 0, bi, (length - bigInt.Length), bigInt.Length);
  198. return bi;
  199. }
  200. }
  201. /*
  202. * RSAPrivateKey ::= SEQUENCE {
  203. * version Version,
  204. * modulus INTEGER, -- n
  205. * publicExponent INTEGER, -- e
  206. * privateExponent INTEGER, -- d
  207. * prime1 INTEGER, -- p
  208. * prime2 INTEGER, -- q
  209. * exponent1 INTEGER, -- d mod (p-1)
  210. * exponent2 INTEGER, -- d mod (q-1)
  211. * coefficient INTEGER, -- (inverse of q) mod p
  212. * otherPrimeInfos OtherPrimeInfos OPTIONAL
  213. * }
  214. */
  215. static public RSA DecodeRSA (byte[] keypair)
  216. {
  217. ASN1 privateKey = new ASN1 (keypair);
  218. if (privateKey.Tag != 0x30)
  219. throw new CryptographicException ("invalid private key format");
  220. ASN1 version = privateKey [0];
  221. if (version.Tag != 0x02)
  222. throw new CryptographicException ("missing version");
  223. if (privateKey.Count < 9)
  224. throw new CryptographicException ("not enough key parameters");
  225. RSAParameters param = new RSAParameters ();
  226. // note: MUST remove leading 0 - else MS wont import the key
  227. param.Modulus = RemoveLeadingZero (privateKey [1].Value);
  228. int keysize = param.Modulus.Length;
  229. int keysize2 = (keysize >> 1); // half-size
  230. // size must be normalized - else MS wont import the key
  231. param.D = Normalize (privateKey [3].Value, keysize);
  232. param.DP = Normalize (privateKey [6].Value, keysize2);
  233. param.DQ = Normalize (privateKey [7].Value, keysize2);
  234. param.Exponent = RemoveLeadingZero (privateKey [2].Value);
  235. param.InverseQ = Normalize (privateKey [8].Value, keysize2);
  236. param.P = Normalize (privateKey [4].Value, keysize2);
  237. param.Q = Normalize (privateKey [5].Value, keysize2);
  238. RSA rsa = null;
  239. try {
  240. rsa = RSA.Create ();
  241. rsa.ImportParameters (param);
  242. }
  243. catch (CryptographicException) {
  244. #if MONOTOUCH
  245. // there's no machine-wide store available for iOS so we can drop the dependency on
  246. // CspParameters (which drops other things, like XML key persistance, unless used elsewhere)
  247. throw;
  248. #else
  249. // this may cause problem when this code is run under
  250. // the SYSTEM identity on Windows (e.g. ASP.NET). See
  251. // http://bugzilla.ximian.com/show_bug.cgi?id=77559
  252. CspParameters csp = new CspParameters ();
  253. csp.Flags = CspProviderFlags.UseMachineKeyStore;
  254. rsa = new RSACryptoServiceProvider (csp);
  255. rsa.ImportParameters (param);
  256. #endif
  257. }
  258. return rsa;
  259. }
  260. /*
  261. * RSAPrivateKey ::= SEQUENCE {
  262. * version Version,
  263. * modulus INTEGER, -- n
  264. * publicExponent INTEGER, -- e
  265. * privateExponent INTEGER, -- d
  266. * prime1 INTEGER, -- p
  267. * prime2 INTEGER, -- q
  268. * exponent1 INTEGER, -- d mod (p-1)
  269. * exponent2 INTEGER, -- d mod (q-1)
  270. * coefficient INTEGER, -- (inverse of q) mod p
  271. * otherPrimeInfos OtherPrimeInfos OPTIONAL
  272. * }
  273. */
  274. static public byte[] Encode (RSA rsa)
  275. {
  276. RSAParameters param = rsa.ExportParameters (true);
  277. ASN1 rsaPrivateKey = new ASN1 (0x30);
  278. rsaPrivateKey.Add (new ASN1 (0x02, new byte [1] { 0x00 }));
  279. rsaPrivateKey.Add (ASN1Convert.FromUnsignedBigInteger (param.Modulus));
  280. rsaPrivateKey.Add (ASN1Convert.FromUnsignedBigInteger (param.Exponent));
  281. rsaPrivateKey.Add (ASN1Convert.FromUnsignedBigInteger (param.D));
  282. rsaPrivateKey.Add (ASN1Convert.FromUnsignedBigInteger (param.P));
  283. rsaPrivateKey.Add (ASN1Convert.FromUnsignedBigInteger (param.Q));
  284. rsaPrivateKey.Add (ASN1Convert.FromUnsignedBigInteger (param.DP));
  285. rsaPrivateKey.Add (ASN1Convert.FromUnsignedBigInteger (param.DQ));
  286. rsaPrivateKey.Add (ASN1Convert.FromUnsignedBigInteger (param.InverseQ));
  287. return rsaPrivateKey.GetBytes ();
  288. }
  289. // DSA only encode it's X private key inside an ASN.1 INTEGER (Hint: Tag == 0x02)
  290. // which isn't enough for rebuilding the keypair. The other parameters
  291. // can be found (98% of the time) in the X.509 certificate associated
  292. // with the private key or (2% of the time) the parameters are in it's
  293. // issuer X.509 certificate (not supported in the .NET framework).
  294. static public DSA DecodeDSA (byte[] privateKey, DSAParameters dsaParameters)
  295. {
  296. ASN1 pvk = new ASN1 (privateKey);
  297. if (pvk.Tag != 0x02)
  298. throw new CryptographicException ("invalid private key format");
  299. // X is ALWAYS 20 bytes (no matter if the key length is 512 or 1024 bits)
  300. dsaParameters.X = Normalize (pvk.Value, 20);
  301. DSA dsa = DSA.Create ();
  302. dsa.ImportParameters (dsaParameters);
  303. return dsa;
  304. }
  305. static public byte[] Encode (DSA dsa)
  306. {
  307. DSAParameters param = dsa.ExportParameters (true);
  308. return ASN1Convert.FromUnsignedBigInteger (param.X).GetBytes ();
  309. }
  310. static public byte[] Encode (AsymmetricAlgorithm aa)
  311. {
  312. if (aa is RSA)
  313. return Encode ((RSA)aa);
  314. else if (aa is DSA)
  315. return Encode ((DSA)aa);
  316. else
  317. throw new CryptographicException ("Unknown asymmetric algorithm {0}", aa.ToString ());
  318. }
  319. }
  320. /*
  321. * EncryptedPrivateKeyInfo ::= SEQUENCE {
  322. * encryptionAlgorithm EncryptionAlgorithmIdentifier,
  323. * encryptedData EncryptedData
  324. * }
  325. *
  326. * EncryptionAlgorithmIdentifier ::= AlgorithmIdentifier
  327. *
  328. * EncryptedData ::= OCTET STRING
  329. *
  330. * --
  331. * AlgorithmIdentifier ::= SEQUENCE {
  332. * algorithm OBJECT IDENTIFIER,
  333. * parameters ANY DEFINED BY algorithm OPTIONAL
  334. * }
  335. *
  336. * -- from PKCS#5
  337. * PBEParameter ::= SEQUENCE {
  338. * salt OCTET STRING SIZE(8),
  339. * iterationCount INTEGER
  340. * }
  341. */
  342. public class EncryptedPrivateKeyInfo {
  343. private string _algorithm;
  344. private byte[] _salt;
  345. private int _iterations;
  346. private byte[] _data;
  347. public EncryptedPrivateKeyInfo () {}
  348. public EncryptedPrivateKeyInfo (byte[] data) : this ()
  349. {
  350. Decode (data);
  351. }
  352. // properties
  353. public string Algorithm {
  354. get { return _algorithm; }
  355. set { _algorithm = value; }
  356. }
  357. public byte[] EncryptedData {
  358. get { return (_data == null) ? null : (byte[]) _data.Clone (); }
  359. set { _data = (value == null) ? null : (byte[]) value.Clone (); }
  360. }
  361. public byte[] Salt {
  362. get {
  363. if (_salt == null) {
  364. RandomNumberGenerator rng = RandomNumberGenerator.Create ();
  365. _salt = new byte [8];
  366. rng.GetBytes (_salt);
  367. }
  368. return (byte[]) _salt.Clone ();
  369. }
  370. set { _salt = (byte[]) value.Clone (); }
  371. }
  372. public int IterationCount {
  373. get { return _iterations; }
  374. set {
  375. if (value < 0)
  376. throw new ArgumentOutOfRangeException ("IterationCount", "Negative");
  377. _iterations = value;
  378. }
  379. }
  380. // methods
  381. private void Decode (byte[] data)
  382. {
  383. ASN1 encryptedPrivateKeyInfo = new ASN1 (data);
  384. if (encryptedPrivateKeyInfo.Tag != 0x30)
  385. throw new CryptographicException ("invalid EncryptedPrivateKeyInfo");
  386. ASN1 encryptionAlgorithm = encryptedPrivateKeyInfo [0];
  387. if (encryptionAlgorithm.Tag != 0x30)
  388. throw new CryptographicException ("invalid encryptionAlgorithm");
  389. ASN1 algorithm = encryptionAlgorithm [0];
  390. if (algorithm.Tag != 0x06)
  391. throw new CryptographicException ("invalid algorithm");
  392. _algorithm = ASN1Convert.ToOid (algorithm);
  393. // parameters ANY DEFINED BY algorithm OPTIONAL
  394. if (encryptionAlgorithm.Count > 1) {
  395. ASN1 parameters = encryptionAlgorithm [1];
  396. if (parameters.Tag != 0x30)
  397. throw new CryptographicException ("invalid parameters");
  398. ASN1 salt = parameters [0];
  399. if (salt.Tag != 0x04)
  400. throw new CryptographicException ("invalid salt");
  401. _salt = salt.Value;
  402. ASN1 iterationCount = parameters [1];
  403. if (iterationCount.Tag != 0x02)
  404. throw new CryptographicException ("invalid iterationCount");
  405. _iterations = ASN1Convert.ToInt32 (iterationCount);
  406. }
  407. ASN1 encryptedData = encryptedPrivateKeyInfo [1];
  408. if (encryptedData.Tag != 0x04)
  409. throw new CryptographicException ("invalid EncryptedData");
  410. _data = encryptedData.Value;
  411. }
  412. // Note: PKCS#8 doesn't define how to generate the key required for encryption
  413. // so you're on your own. Just don't try to copy the big guys too much ;)
  414. // Netscape: http://www.cs.auckland.ac.nz/~pgut001/pubs/netscape.txt
  415. // Microsoft: http://www.cs.auckland.ac.nz/~pgut001/pubs/breakms.txt
  416. public byte[] GetBytes ()
  417. {
  418. if (_algorithm == null)
  419. throw new CryptographicException ("No algorithm OID specified");
  420. ASN1 encryptionAlgorithm = new ASN1 (0x30);
  421. encryptionAlgorithm.Add (ASN1Convert.FromOid (_algorithm));
  422. // parameters ANY DEFINED BY algorithm OPTIONAL
  423. if ((_iterations > 0) || (_salt != null)) {
  424. ASN1 salt = new ASN1 (0x04, _salt);
  425. ASN1 iterations = ASN1Convert.FromInt32 (_iterations);
  426. ASN1 parameters = new ASN1 (0x30);
  427. parameters.Add (salt);
  428. parameters.Add (iterations);
  429. encryptionAlgorithm.Add (parameters);
  430. }
  431. // encapsulates EncryptedData into an OCTET STRING
  432. ASN1 encryptedData = new ASN1 (0x04, _data);
  433. ASN1 encryptedPrivateKeyInfo = new ASN1 (0x30);
  434. encryptedPrivateKeyInfo.Add (encryptionAlgorithm);
  435. encryptedPrivateKeyInfo.Add (encryptedData);
  436. return encryptedPrivateKeyInfo.GetBytes ();
  437. }
  438. }
  439. }
  440. }