PKCS8.cs 15 KB

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