PKCS1.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491
  1. //
  2. // PKCS1.cs - Implements PKCS#1 primitives.
  3. //
  4. // Author:
  5. // Sebastien Pouliot <sebastien@xamarin.com>
  6. //
  7. // (C) 2002, 2003 Motus Technologies Inc. (http://www.motus.com)
  8. // Copyright (C) 2004 Novell, Inc (http://www.novell.com)
  9. // Copyright 2013 Xamarin Inc. (http://www.xamarin.com)
  10. //
  11. // Permission is hereby granted, free of charge, to any person obtaining
  12. // a copy of this software and associated documentation files (the
  13. // "Software"), to deal in the Software without restriction, including
  14. // without limitation the rights to use, copy, modify, merge, publish,
  15. // distribute, sublicense, and/or sell copies of the Software, and to
  16. // permit persons to whom the Software is furnished to do so, subject to
  17. // the following conditions:
  18. //
  19. // The above copyright notice and this permission notice shall be
  20. // included in all copies or substantial portions of the Software.
  21. //
  22. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  23. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  24. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  25. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  26. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  27. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  28. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  29. //
  30. using System;
  31. using System.Security.Cryptography;
  32. namespace Emby.Server.Core.Cryptography
  33. {
  34. // References:
  35. // a. PKCS#1: RSA Cryptography Standard
  36. // http://www.rsasecurity.com/rsalabs/pkcs/pkcs-1/index.html
  37. public sealed class PKCS1 {
  38. private PKCS1 ()
  39. {
  40. }
  41. private static bool Compare (byte[] array1, byte[] array2)
  42. {
  43. bool result = (array1.Length == array2.Length);
  44. if (result) {
  45. for (int i=0; i < array1.Length; i++)
  46. if (array1[i] != array2[i])
  47. return false;
  48. }
  49. return result;
  50. }
  51. private static byte[] xor (byte[] array1, byte[] array2)
  52. {
  53. byte[] result = new byte [array1.Length];
  54. for (int i=0; i < result.Length; i++)
  55. result[i] = (byte) (array1[i] ^ array2[i]);
  56. return result;
  57. }
  58. private static byte[] emptySHA1 = { 0xda, 0x39, 0xa3, 0xee, 0x5e, 0x6b, 0x4b, 0x0d, 0x32, 0x55, 0xbf, 0xef, 0x95, 0x60, 0x18, 0x90, 0xaf, 0xd8, 0x07, 0x09 };
  59. private static byte[] emptySHA256 = { 0xe3, 0xb0, 0xc4, 0x42, 0x98, 0xfc, 0x1c, 0x14, 0x9a, 0xfb, 0xf4, 0xc8, 0x99, 0x6f, 0xb9, 0x24, 0x27, 0xae, 0x41, 0xe4, 0x64, 0x9b, 0x93, 0x4c, 0xa4, 0x95, 0x99, 0x1b, 0x78, 0x52, 0xb8, 0x55 };
  60. private static byte[] emptySHA384 = { 0x38, 0xb0, 0x60, 0xa7, 0x51, 0xac, 0x96, 0x38, 0x4c, 0xd9, 0x32, 0x7e, 0xb1, 0xb1, 0xe3, 0x6a, 0x21, 0xfd, 0xb7, 0x11, 0x14, 0xbe, 0x07, 0x43, 0x4c, 0x0c, 0xc7, 0xbf, 0x63, 0xf6, 0xe1, 0xda, 0x27, 0x4e, 0xde, 0xbf, 0xe7, 0x6f, 0x65, 0xfb, 0xd5, 0x1a, 0xd2, 0xf1, 0x48, 0x98, 0xb9, 0x5b };
  61. private static byte[] emptySHA512 = { 0xcf, 0x83, 0xe1, 0x35, 0x7e, 0xef, 0xb8, 0xbd, 0xf1, 0x54, 0x28, 0x50, 0xd6, 0x6d, 0x80, 0x07, 0xd6, 0x20, 0xe4, 0x05, 0x0b, 0x57, 0x15, 0xdc, 0x83, 0xf4, 0xa9, 0x21, 0xd3, 0x6c, 0xe9, 0xce, 0x47, 0xd0, 0xd1, 0x3c, 0x5d, 0x85, 0xf2, 0xb0, 0xff, 0x83, 0x18, 0xd2, 0x87, 0x7e, 0xec, 0x2f, 0x63, 0xb9, 0x31, 0xbd, 0x47, 0x41, 0x7a, 0x81, 0xa5, 0x38, 0x32, 0x7a, 0xf9, 0x27, 0xda, 0x3e };
  62. private static byte[] GetEmptyHash (HashAlgorithm hash)
  63. {
  64. if (hash is SHA1)
  65. return emptySHA1;
  66. else if (hash is SHA256)
  67. return emptySHA256;
  68. else if (hash is SHA384)
  69. return emptySHA384;
  70. else if (hash is SHA512)
  71. return emptySHA512;
  72. else
  73. return hash.ComputeHash ((byte[])null);
  74. }
  75. // PKCS #1 v.2.1, Section 4.1
  76. // I2OSP converts a non-negative integer to an octet string of a specified length.
  77. public static byte[] I2OSP (int x, int size)
  78. {
  79. byte[] array = BitConverterLE.GetBytes (x);
  80. Array.Reverse (array, 0, array.Length);
  81. return I2OSP (array, size);
  82. }
  83. public static byte[] I2OSP (byte[] x, int size)
  84. {
  85. byte[] result = new byte [size];
  86. Buffer.BlockCopy (x, 0, result, (result.Length - x.Length), x.Length);
  87. return result;
  88. }
  89. // PKCS #1 v.2.1, Section 4.2
  90. // OS2IP converts an octet string to a nonnegative integer.
  91. public static byte[] OS2IP (byte[] x)
  92. {
  93. int i = 0;
  94. while ((x [i++] == 0x00) && (i < x.Length)) {
  95. // confuse compiler into reporting a warning with {}
  96. }
  97. i--;
  98. if (i > 0) {
  99. byte[] result = new byte [x.Length - i];
  100. Buffer.BlockCopy (x, i, result, 0, result.Length);
  101. return result;
  102. }
  103. else
  104. return x;
  105. }
  106. // PKCS #1 v.2.1, Section 5.1.1
  107. public static byte[] RSAEP (RSA rsa, byte[] m)
  108. {
  109. // c = m^e mod n
  110. return rsa.EncryptValue (m);
  111. }
  112. // PKCS #1 v.2.1, Section 5.1.2
  113. public static byte[] RSADP (RSA rsa, byte[] c)
  114. {
  115. // m = c^d mod n
  116. // Decrypt value may apply CRT optimizations
  117. return rsa.DecryptValue (c);
  118. }
  119. // PKCS #1 v.2.1, Section 5.2.1
  120. public static byte[] RSASP1 (RSA rsa, byte[] m)
  121. {
  122. // first form: s = m^d mod n
  123. // Decrypt value may apply CRT optimizations
  124. return rsa.DecryptValue (m);
  125. }
  126. // PKCS #1 v.2.1, Section 5.2.2
  127. public static byte[] RSAVP1 (RSA rsa, byte[] s)
  128. {
  129. // m = s^e mod n
  130. return rsa.EncryptValue (s);
  131. }
  132. // PKCS #1 v.2.1, Section 7.1.1
  133. // RSAES-OAEP-ENCRYPT ((n, e), M, L)
  134. public static byte[] Encrypt_OAEP (RSA rsa, HashAlgorithm hash, RandomNumberGenerator rng, byte[] M)
  135. {
  136. int size = rsa.KeySize / 8;
  137. int hLen = hash.HashSize / 8;
  138. if (M.Length > size - 2 * hLen - 2)
  139. throw new CryptographicException ("message too long");
  140. // empty label L SHA1 hash
  141. byte[] lHash = GetEmptyHash (hash);
  142. int PSLength = (size - M.Length - 2 * hLen - 2);
  143. // DB = lHash || PS || 0x01 || M
  144. byte[] DB = new byte [lHash.Length + PSLength + 1 + M.Length];
  145. Buffer.BlockCopy (lHash, 0, DB, 0, lHash.Length);
  146. DB [(lHash.Length + PSLength)] = 0x01;
  147. Buffer.BlockCopy (M, 0, DB, (DB.Length - M.Length), M.Length);
  148. byte[] seed = new byte [hLen];
  149. rng.GetBytes (seed);
  150. byte[] dbMask = MGF1 (hash, seed, size - hLen - 1);
  151. byte[] maskedDB = xor (DB, dbMask);
  152. byte[] seedMask = MGF1 (hash, maskedDB, hLen);
  153. byte[] maskedSeed = xor (seed, seedMask);
  154. // EM = 0x00 || maskedSeed || maskedDB
  155. byte[] EM = new byte [maskedSeed.Length + maskedDB.Length + 1];
  156. Buffer.BlockCopy (maskedSeed, 0, EM, 1, maskedSeed.Length);
  157. Buffer.BlockCopy (maskedDB, 0, EM, maskedSeed.Length + 1, maskedDB.Length);
  158. byte[] m = OS2IP (EM);
  159. byte[] c = RSAEP (rsa, m);
  160. return I2OSP (c, size);
  161. }
  162. // PKCS #1 v.2.1, Section 7.1.2
  163. // RSAES-OAEP-DECRYPT (K, C, L)
  164. public static byte[] Decrypt_OAEP (RSA rsa, HashAlgorithm hash, byte[] C)
  165. {
  166. int size = rsa.KeySize / 8;
  167. int hLen = hash.HashSize / 8;
  168. if ((size < (2 * hLen + 2)) || (C.Length != size))
  169. throw new CryptographicException ("decryption error");
  170. byte[] c = OS2IP (C);
  171. byte[] m = RSADP (rsa, c);
  172. byte[] EM = I2OSP (m, size);
  173. // split EM = Y || maskedSeed || maskedDB
  174. byte[] maskedSeed = new byte [hLen];
  175. Buffer.BlockCopy (EM, 1, maskedSeed, 0, maskedSeed.Length);
  176. byte[] maskedDB = new byte [size - hLen - 1];
  177. Buffer.BlockCopy (EM, (EM.Length - maskedDB.Length), maskedDB, 0, maskedDB.Length);
  178. byte[] seedMask = MGF1 (hash, maskedDB, hLen);
  179. byte[] seed = xor (maskedSeed, seedMask);
  180. byte[] dbMask = MGF1 (hash, seed, size - hLen - 1);
  181. byte[] DB = xor (maskedDB, dbMask);
  182. byte[] lHash = GetEmptyHash (hash);
  183. // split DB = lHash' || PS || 0x01 || M
  184. byte[] dbHash = new byte [lHash.Length];
  185. Buffer.BlockCopy (DB, 0, dbHash, 0, dbHash.Length);
  186. bool h = Compare (lHash, dbHash);
  187. // find separator 0x01
  188. int nPos = lHash.Length;
  189. while (DB[nPos] == 0)
  190. nPos++;
  191. int Msize = DB.Length - nPos - 1;
  192. byte[] M = new byte [Msize];
  193. Buffer.BlockCopy (DB, (nPos + 1), M, 0, Msize);
  194. // we could have returned EM[0] sooner but would be helping a timing attack
  195. if ((EM[0] != 0) || (!h) || (DB[nPos] != 0x01))
  196. return null;
  197. return M;
  198. }
  199. // PKCS #1 v.2.1, Section 7.2.1
  200. // RSAES-PKCS1-V1_5-ENCRYPT ((n, e), M)
  201. public static byte[] Encrypt_v15 (RSA rsa, RandomNumberGenerator rng, byte[] M)
  202. {
  203. int size = rsa.KeySize / 8;
  204. if (M.Length > size - 11)
  205. throw new CryptographicException ("message too long");
  206. int PSLength = System.Math.Max (8, (size - M.Length - 3));
  207. byte[] PS = new byte [PSLength];
  208. rng.GetNonZeroBytes (PS);
  209. byte[] EM = new byte [size];
  210. EM [1] = 0x02;
  211. Buffer.BlockCopy (PS, 0, EM, 2, PSLength);
  212. Buffer.BlockCopy (M, 0, EM, (size - M.Length), M.Length);
  213. byte[] m = OS2IP (EM);
  214. byte[] c = RSAEP (rsa, m);
  215. byte[] C = I2OSP (c, size);
  216. return C;
  217. }
  218. // PKCS #1 v.2.1, Section 7.2.2
  219. // RSAES-PKCS1-V1_5-DECRYPT (K, C)
  220. public static byte[] Decrypt_v15 (RSA rsa, byte[] C)
  221. {
  222. int size = rsa.KeySize >> 3; // div by 8
  223. if ((size < 11) || (C.Length > size))
  224. throw new CryptographicException ("decryption error");
  225. byte[] c = OS2IP (C);
  226. byte[] m = RSADP (rsa, c);
  227. byte[] EM = I2OSP (m, size);
  228. if ((EM [0] != 0x00) || (EM [1] != 0x02))
  229. return null;
  230. int mPos = 10;
  231. // PS is a minimum of 8 bytes + 2 bytes for header
  232. while ((EM [mPos] != 0x00) && (mPos < EM.Length))
  233. mPos++;
  234. if (EM [mPos] != 0x00)
  235. return null;
  236. mPos++;
  237. byte[] M = new byte [EM.Length - mPos];
  238. Buffer.BlockCopy (EM, mPos, M, 0, M.Length);
  239. return M;
  240. }
  241. // PKCS #1 v.2.1, Section 8.2.1
  242. // RSASSA-PKCS1-V1_5-SIGN (K, M)
  243. public static byte[] Sign_v15 (RSA rsa, HashAlgorithm hash, byte[] hashValue)
  244. {
  245. int size = (rsa.KeySize >> 3); // div 8
  246. byte[] EM = Encode_v15 (hash, hashValue, size);
  247. byte[] m = OS2IP (EM);
  248. byte[] s = RSASP1 (rsa, m);
  249. byte[] S = I2OSP (s, size);
  250. return S;
  251. }
  252. internal static byte[] Sign_v15 (RSA rsa, string hashName, byte[] hashValue)
  253. {
  254. using (var hash = CreateFromName (hashName))
  255. return Sign_v15 (rsa, hash, hashValue);
  256. }
  257. // PKCS #1 v.2.1, Section 8.2.2
  258. // RSASSA-PKCS1-V1_5-VERIFY ((n, e), M, S)
  259. public static bool Verify_v15 (RSA rsa, HashAlgorithm hash, byte[] hashValue, byte[] signature)
  260. {
  261. return Verify_v15 (rsa, hash, hashValue, signature, false);
  262. }
  263. internal static bool Verify_v15 (RSA rsa, string hashName, byte[] hashValue, byte[] signature)
  264. {
  265. using (var hash = CreateFromName (hashName))
  266. return Verify_v15 (rsa, hash, hashValue, signature, false);
  267. }
  268. // DO NOT USE WITHOUT A VERY GOOD REASON
  269. public static bool Verify_v15 (RSA rsa, HashAlgorithm hash, byte [] hashValue, byte [] signature, bool tryNonStandardEncoding)
  270. {
  271. int size = (rsa.KeySize >> 3); // div 8
  272. byte[] s = OS2IP (signature);
  273. byte[] m = RSAVP1 (rsa, s);
  274. byte[] EM2 = I2OSP (m, size);
  275. byte[] EM = Encode_v15 (hash, hashValue, size);
  276. bool result = Compare (EM, EM2);
  277. if (result || !tryNonStandardEncoding)
  278. return result;
  279. // NOTE: some signatures don't include the hash OID (pretty lame but real)
  280. // and compatible with MS implementation. E.g. Verisign Authenticode Timestamps
  281. // we're making this "as safe as possible"
  282. if ((EM2 [0] != 0x00) || (EM2 [1] != 0x01))
  283. return false;
  284. int i;
  285. for (i = 2; i < EM2.Length - hashValue.Length - 1; i++) {
  286. if (EM2 [i] != 0xFF)
  287. return false;
  288. }
  289. if (EM2 [i++] != 0x00)
  290. return false;
  291. byte [] decryptedHash = new byte [hashValue.Length];
  292. Buffer.BlockCopy (EM2, i, decryptedHash, 0, decryptedHash.Length);
  293. return Compare (decryptedHash, hashValue);
  294. }
  295. // PKCS #1 v.2.1, Section 9.2
  296. // EMSA-PKCS1-v1_5-Encode
  297. public static byte[] Encode_v15 (HashAlgorithm hash, byte[] hashValue, int emLength)
  298. {
  299. if (hashValue.Length != (hash.HashSize >> 3))
  300. throw new CryptographicException ("bad hash length for " + hash.ToString ());
  301. // DigestInfo ::= SEQUENCE {
  302. // digestAlgorithm AlgorithmIdentifier,
  303. // digest OCTET STRING
  304. // }
  305. byte[] t = null;
  306. string oid = CryptoConfig.MapNameToOID (hash.ToString ());
  307. if (oid != null)
  308. {
  309. ASN1 digestAlgorithm = new ASN1 (0x30);
  310. digestAlgorithm.Add (new ASN1 (CryptoConfig.EncodeOID (oid)));
  311. digestAlgorithm.Add (new ASN1 (0x05)); // NULL
  312. ASN1 digest = new ASN1 (0x04, hashValue);
  313. ASN1 digestInfo = new ASN1 (0x30);
  314. digestInfo.Add (digestAlgorithm);
  315. digestInfo.Add (digest);
  316. t = digestInfo.GetBytes ();
  317. }
  318. else
  319. {
  320. // There are no valid OID, in this case t = hashValue
  321. // This is the case of the MD5SHA hash algorithm
  322. t = hashValue;
  323. }
  324. Buffer.BlockCopy (hashValue, 0, t, t.Length - hashValue.Length, hashValue.Length);
  325. int PSLength = System.Math.Max (8, emLength - t.Length - 3);
  326. // PS = PSLength of 0xff
  327. // EM = 0x00 | 0x01 | PS | 0x00 | T
  328. byte[] EM = new byte [PSLength + t.Length + 3];
  329. EM [1] = 0x01;
  330. for (int i=2; i < PSLength + 2; i++)
  331. EM[i] = 0xff;
  332. Buffer.BlockCopy (t, 0, EM, PSLength + 3, t.Length);
  333. return EM;
  334. }
  335. // PKCS #1 v.2.1, Section B.2.1
  336. public static byte[] MGF1 (HashAlgorithm hash, byte[] mgfSeed, int maskLen)
  337. {
  338. // 1. If maskLen > 2^32 hLen, output "mask too long" and stop.
  339. // easy - this is impossible by using a int (31bits) as parameter ;-)
  340. // BUT with a signed int we do have to check for negative values!
  341. if (maskLen < 0)
  342. throw new OverflowException();
  343. int mgfSeedLength = mgfSeed.Length;
  344. int hLen = (hash.HashSize >> 3); // from bits to bytes
  345. int iterations = (maskLen / hLen);
  346. if (maskLen % hLen != 0)
  347. iterations++;
  348. // 2. Let T be the empty octet string.
  349. byte[] T = new byte [iterations * hLen];
  350. byte[] toBeHashed = new byte [mgfSeedLength + 4];
  351. int pos = 0;
  352. // 3. For counter from 0 to \ceil (maskLen / hLen) - 1, do the following:
  353. for (int counter = 0; counter < iterations; counter++) {
  354. // a. Convert counter to an octet string C of length 4 octets
  355. byte[] C = I2OSP (counter, 4);
  356. // b. Concatenate the hash of the seed mgfSeed and C to the octet string T:
  357. // T = T || Hash (mgfSeed || C)
  358. Buffer.BlockCopy (mgfSeed, 0, toBeHashed, 0, mgfSeedLength);
  359. Buffer.BlockCopy (C, 0, toBeHashed, mgfSeedLength, 4);
  360. byte[] output = hash.ComputeHash (toBeHashed);
  361. Buffer.BlockCopy (output, 0, T, pos, hLen);
  362. pos += hLen;
  363. }
  364. // 4. Output the leading maskLen octets of T as the octet string mask.
  365. byte[] mask = new byte [maskLen];
  366. Buffer.BlockCopy (T, 0, mask, 0, maskLen);
  367. return mask;
  368. }
  369. static internal string HashNameFromOid (string oid, bool throwOnError = true)
  370. {
  371. switch (oid) {
  372. case "1.2.840.113549.1.1.2": // MD2 with RSA encryption
  373. return "MD2";
  374. case "1.2.840.113549.1.1.3": // MD4 with RSA encryption
  375. return "MD4";
  376. case "1.2.840.113549.1.1.4": // MD5 with RSA encryption
  377. return "MD5";
  378. case "1.2.840.113549.1.1.5": // SHA-1 with RSA Encryption
  379. case "1.3.14.3.2.29": // SHA1 with RSA signature
  380. case "1.2.840.10040.4.3": // SHA1-1 with DSA
  381. return "SHA1";
  382. case "1.2.840.113549.1.1.11": // SHA-256 with RSA Encryption
  383. return "SHA256";
  384. case "1.2.840.113549.1.1.12": // SHA-384 with RSA Encryption
  385. return "SHA384";
  386. case "1.2.840.113549.1.1.13": // SHA-512 with RSA Encryption
  387. return "SHA512";
  388. case "1.3.36.3.3.1.2":
  389. return "RIPEMD160";
  390. default:
  391. if (throwOnError)
  392. throw new CryptographicException ("Unsupported hash algorithm: " + oid);
  393. return null;
  394. }
  395. }
  396. static internal HashAlgorithm CreateFromOid (string oid)
  397. {
  398. return CreateFromName (HashNameFromOid (oid));
  399. }
  400. static internal HashAlgorithm CreateFromName (string name)
  401. {
  402. #if FULL_AOT_RUNTIME
  403. switch (name) {
  404. case "MD2":
  405. return MD2.Create ();
  406. case "MD4":
  407. return MD4.Create ();
  408. case "MD5":
  409. return MD5.Create ();
  410. case "SHA1":
  411. return SHA1.Create ();
  412. case "SHA256":
  413. return SHA256.Create ();
  414. case "SHA384":
  415. return SHA384.Create ();
  416. case "SHA512":
  417. return SHA512.Create ();
  418. case "RIPEMD160":
  419. return RIPEMD160.Create ();
  420. default:
  421. try {
  422. return (HashAlgorithm) Activator.CreateInstance (Type.GetType (name));
  423. }
  424. catch {
  425. throw new CryptographicException ("Unsupported hash algorithm: " + name);
  426. }
  427. }
  428. #else
  429. return HashAlgorithm.Create (name);
  430. #endif
  431. }
  432. }
  433. }