PKCS8.cs 15 KB

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