PKCS1.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495
  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 Mono.Security.Cryptography {
  33. // References:
  34. // a. PKCS#1: RSA Cryptography Standard
  35. // http://www.rsasecurity.com/rsalabs/pkcs/pkcs-1/index.html
  36. #if INSIDE_CORLIB
  37. internal
  38. #else
  39. public
  40. #endif
  41. sealed class PKCS1 {
  42. private PKCS1 ()
  43. {
  44. }
  45. private static bool Compare (byte[] array1, byte[] array2)
  46. {
  47. bool result = (array1.Length == array2.Length);
  48. if (result) {
  49. for (int i=0; i < array1.Length; i++)
  50. if (array1[i] != array2[i])
  51. return false;
  52. }
  53. return result;
  54. }
  55. private static byte[] xor (byte[] array1, byte[] array2)
  56. {
  57. byte[] result = new byte [array1.Length];
  58. for (int i=0; i < result.Length; i++)
  59. result[i] = (byte) (array1[i] ^ array2[i]);
  60. return result;
  61. }
  62. private static byte[] emptySHA1 = { 0xda, 0x39, 0xa3, 0xee, 0x5e, 0x6b, 0x4b, 0x0d, 0x32, 0x55, 0xbf, 0xef, 0x95, 0x60, 0x18, 0x90, 0xaf, 0xd8, 0x07, 0x09 };
  63. 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 };
  64. 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 };
  65. 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 };
  66. private static byte[] GetEmptyHash (HashAlgorithm hash)
  67. {
  68. if (hash is SHA1)
  69. return emptySHA1;
  70. else if (hash is SHA256)
  71. return emptySHA256;
  72. else if (hash is SHA384)
  73. return emptySHA384;
  74. else if (hash is SHA512)
  75. return emptySHA512;
  76. else
  77. return hash.ComputeHash ((byte[])null);
  78. }
  79. // PKCS #1 v.2.1, Section 4.1
  80. // I2OSP converts a non-negative integer to an octet string of a specified length.
  81. public static byte[] I2OSP (int x, int size)
  82. {
  83. byte[] array = BitConverterLE.GetBytes (x);
  84. Array.Reverse (array, 0, array.Length);
  85. return I2OSP (array, size);
  86. }
  87. public static byte[] I2OSP (byte[] x, int size)
  88. {
  89. byte[] result = new byte [size];
  90. Buffer.BlockCopy (x, 0, result, (result.Length - x.Length), x.Length);
  91. return result;
  92. }
  93. // PKCS #1 v.2.1, Section 4.2
  94. // OS2IP converts an octet string to a nonnegative integer.
  95. public static byte[] OS2IP (byte[] x)
  96. {
  97. int i = 0;
  98. while ((x [i++] == 0x00) && (i < x.Length)) {
  99. // confuse compiler into reporting a warning with {}
  100. }
  101. i--;
  102. if (i > 0) {
  103. byte[] result = new byte [x.Length - i];
  104. Buffer.BlockCopy (x, i, result, 0, result.Length);
  105. return result;
  106. }
  107. else
  108. return x;
  109. }
  110. // PKCS #1 v.2.1, Section 5.1.1
  111. public static byte[] RSAEP (RSA rsa, byte[] m)
  112. {
  113. // c = m^e mod n
  114. return rsa.EncryptValue (m);
  115. }
  116. // PKCS #1 v.2.1, Section 5.1.2
  117. public static byte[] RSADP (RSA rsa, byte[] c)
  118. {
  119. // m = c^d mod n
  120. // Decrypt value may apply CRT optimizations
  121. return rsa.DecryptValue (c);
  122. }
  123. // PKCS #1 v.2.1, Section 5.2.1
  124. public static byte[] RSASP1 (RSA rsa, byte[] m)
  125. {
  126. // first form: s = m^d mod n
  127. // Decrypt value may apply CRT optimizations
  128. return rsa.DecryptValue (m);
  129. }
  130. // PKCS #1 v.2.1, Section 5.2.2
  131. public static byte[] RSAVP1 (RSA rsa, byte[] s)
  132. {
  133. // m = s^e mod n
  134. return rsa.EncryptValue (s);
  135. }
  136. // PKCS #1 v.2.1, Section 7.1.1
  137. // RSAES-OAEP-ENCRYPT ((n, e), M, L)
  138. public static byte[] Encrypt_OAEP (RSA rsa, HashAlgorithm hash, RandomNumberGenerator rng, byte[] M)
  139. {
  140. int size = rsa.KeySize / 8;
  141. int hLen = hash.HashSize / 8;
  142. if (M.Length > size - 2 * hLen - 2)
  143. throw new CryptographicException ("message too long");
  144. // empty label L SHA1 hash
  145. byte[] lHash = GetEmptyHash (hash);
  146. int PSLength = (size - M.Length - 2 * hLen - 2);
  147. // DB = lHash || PS || 0x01 || M
  148. byte[] DB = new byte [lHash.Length + PSLength + 1 + M.Length];
  149. Buffer.BlockCopy (lHash, 0, DB, 0, lHash.Length);
  150. DB [(lHash.Length + PSLength)] = 0x01;
  151. Buffer.BlockCopy (M, 0, DB, (DB.Length - M.Length), M.Length);
  152. byte[] seed = new byte [hLen];
  153. rng.GetBytes (seed);
  154. byte[] dbMask = MGF1 (hash, seed, size - hLen - 1);
  155. byte[] maskedDB = xor (DB, dbMask);
  156. byte[] seedMask = MGF1 (hash, maskedDB, hLen);
  157. byte[] maskedSeed = xor (seed, seedMask);
  158. // EM = 0x00 || maskedSeed || maskedDB
  159. byte[] EM = new byte [maskedSeed.Length + maskedDB.Length + 1];
  160. Buffer.BlockCopy (maskedSeed, 0, EM, 1, maskedSeed.Length);
  161. Buffer.BlockCopy (maskedDB, 0, EM, maskedSeed.Length + 1, maskedDB.Length);
  162. byte[] m = OS2IP (EM);
  163. byte[] c = RSAEP (rsa, m);
  164. return I2OSP (c, size);
  165. }
  166. // PKCS #1 v.2.1, Section 7.1.2
  167. // RSAES-OAEP-DECRYPT (K, C, L)
  168. public static byte[] Decrypt_OAEP (RSA rsa, HashAlgorithm hash, byte[] C)
  169. {
  170. int size = rsa.KeySize / 8;
  171. int hLen = hash.HashSize / 8;
  172. if ((size < (2 * hLen + 2)) || (C.Length != size))
  173. throw new CryptographicException ("decryption error");
  174. byte[] c = OS2IP (C);
  175. byte[] m = RSADP (rsa, c);
  176. byte[] EM = I2OSP (m, size);
  177. // split EM = Y || maskedSeed || maskedDB
  178. byte[] maskedSeed = new byte [hLen];
  179. Buffer.BlockCopy (EM, 1, maskedSeed, 0, maskedSeed.Length);
  180. byte[] maskedDB = new byte [size - hLen - 1];
  181. Buffer.BlockCopy (EM, (EM.Length - maskedDB.Length), maskedDB, 0, maskedDB.Length);
  182. byte[] seedMask = MGF1 (hash, maskedDB, hLen);
  183. byte[] seed = xor (maskedSeed, seedMask);
  184. byte[] dbMask = MGF1 (hash, seed, size - hLen - 1);
  185. byte[] DB = xor (maskedDB, dbMask);
  186. byte[] lHash = GetEmptyHash (hash);
  187. // split DB = lHash' || PS || 0x01 || M
  188. byte[] dbHash = new byte [lHash.Length];
  189. Buffer.BlockCopy (DB, 0, dbHash, 0, dbHash.Length);
  190. bool h = Compare (lHash, dbHash);
  191. // find separator 0x01
  192. int nPos = lHash.Length;
  193. while (DB[nPos] == 0)
  194. nPos++;
  195. int Msize = DB.Length - nPos - 1;
  196. byte[] M = new byte [Msize];
  197. Buffer.BlockCopy (DB, (nPos + 1), M, 0, Msize);
  198. // we could have returned EM[0] sooner but would be helping a timing attack
  199. if ((EM[0] != 0) || (!h) || (DB[nPos] != 0x01))
  200. return null;
  201. return M;
  202. }
  203. // PKCS #1 v.2.1, Section 7.2.1
  204. // RSAES-PKCS1-V1_5-ENCRYPT ((n, e), M)
  205. public static byte[] Encrypt_v15 (RSA rsa, RandomNumberGenerator rng, byte[] M)
  206. {
  207. int size = rsa.KeySize / 8;
  208. if (M.Length > size - 11)
  209. throw new CryptographicException ("message too long");
  210. int PSLength = System.Math.Max (8, (size - M.Length - 3));
  211. byte[] PS = new byte [PSLength];
  212. rng.GetNonZeroBytes (PS);
  213. byte[] EM = new byte [size];
  214. EM [1] = 0x02;
  215. Buffer.BlockCopy (PS, 0, EM, 2, PSLength);
  216. Buffer.BlockCopy (M, 0, EM, (size - M.Length), M.Length);
  217. byte[] m = OS2IP (EM);
  218. byte[] c = RSAEP (rsa, m);
  219. byte[] C = I2OSP (c, size);
  220. return C;
  221. }
  222. // PKCS #1 v.2.1, Section 7.2.2
  223. // RSAES-PKCS1-V1_5-DECRYPT (K, C)
  224. public static byte[] Decrypt_v15 (RSA rsa, byte[] C)
  225. {
  226. int size = rsa.KeySize >> 3; // div by 8
  227. if ((size < 11) || (C.Length > size))
  228. throw new CryptographicException ("decryption error");
  229. byte[] c = OS2IP (C);
  230. byte[] m = RSADP (rsa, c);
  231. byte[] EM = I2OSP (m, size);
  232. if ((EM [0] != 0x00) || (EM [1] != 0x02))
  233. return null;
  234. int mPos = 10;
  235. // PS is a minimum of 8 bytes + 2 bytes for header
  236. while ((EM [mPos] != 0x00) && (mPos < EM.Length))
  237. mPos++;
  238. if (EM [mPos] != 0x00)
  239. return null;
  240. mPos++;
  241. byte[] M = new byte [EM.Length - mPos];
  242. Buffer.BlockCopy (EM, mPos, M, 0, M.Length);
  243. return M;
  244. }
  245. // PKCS #1 v.2.1, Section 8.2.1
  246. // RSASSA-PKCS1-V1_5-SIGN (K, M)
  247. public static byte[] Sign_v15 (RSA rsa, HashAlgorithm hash, byte[] hashValue)
  248. {
  249. int size = (rsa.KeySize >> 3); // div 8
  250. byte[] EM = Encode_v15 (hash, hashValue, size);
  251. byte[] m = OS2IP (EM);
  252. byte[] s = RSASP1 (rsa, m);
  253. byte[] S = I2OSP (s, size);
  254. return S;
  255. }
  256. internal static byte[] Sign_v15 (RSA rsa, string hashName, byte[] hashValue)
  257. {
  258. using (var hash = CreateFromName (hashName))
  259. return Sign_v15 (rsa, hash, hashValue);
  260. }
  261. // PKCS #1 v.2.1, Section 8.2.2
  262. // RSASSA-PKCS1-V1_5-VERIFY ((n, e), M, S)
  263. public static bool Verify_v15 (RSA rsa, HashAlgorithm hash, byte[] hashValue, byte[] signature)
  264. {
  265. return Verify_v15 (rsa, hash, hashValue, signature, false);
  266. }
  267. internal static bool Verify_v15 (RSA rsa, string hashName, byte[] hashValue, byte[] signature)
  268. {
  269. using (var hash = CreateFromName (hashName))
  270. return Verify_v15 (rsa, hash, hashValue, signature, false);
  271. }
  272. // DO NOT USE WITHOUT A VERY GOOD REASON
  273. public static bool Verify_v15 (RSA rsa, HashAlgorithm hash, byte [] hashValue, byte [] signature, bool tryNonStandardEncoding)
  274. {
  275. int size = (rsa.KeySize >> 3); // div 8
  276. byte[] s = OS2IP (signature);
  277. byte[] m = RSAVP1 (rsa, s);
  278. byte[] EM2 = I2OSP (m, size);
  279. byte[] EM = Encode_v15 (hash, hashValue, size);
  280. bool result = Compare (EM, EM2);
  281. if (result || !tryNonStandardEncoding)
  282. return result;
  283. // NOTE: some signatures don't include the hash OID (pretty lame but real)
  284. // and compatible with MS implementation. E.g. Verisign Authenticode Timestamps
  285. // we're making this "as safe as possible"
  286. if ((EM2 [0] != 0x00) || (EM2 [1] != 0x01))
  287. return false;
  288. int i;
  289. for (i = 2; i < EM2.Length - hashValue.Length - 1; i++) {
  290. if (EM2 [i] != 0xFF)
  291. return false;
  292. }
  293. if (EM2 [i++] != 0x00)
  294. return false;
  295. byte [] decryptedHash = new byte [hashValue.Length];
  296. Buffer.BlockCopy (EM2, i, decryptedHash, 0, decryptedHash.Length);
  297. return Compare (decryptedHash, hashValue);
  298. }
  299. // PKCS #1 v.2.1, Section 9.2
  300. // EMSA-PKCS1-v1_5-Encode
  301. public static byte[] Encode_v15 (HashAlgorithm hash, byte[] hashValue, int emLength)
  302. {
  303. if (hashValue.Length != (hash.HashSize >> 3))
  304. throw new CryptographicException ("bad hash length for " + hash.ToString ());
  305. // DigestInfo ::= SEQUENCE {
  306. // digestAlgorithm AlgorithmIdentifier,
  307. // digest OCTET STRING
  308. // }
  309. byte[] t = null;
  310. string oid = CryptoConfig.MapNameToOID (hash.ToString ());
  311. if (oid != null)
  312. {
  313. ASN1 digestAlgorithm = new ASN1 (0x30);
  314. digestAlgorithm.Add (new ASN1 (CryptoConfig.EncodeOID (oid)));
  315. digestAlgorithm.Add (new ASN1 (0x05)); // NULL
  316. ASN1 digest = new ASN1 (0x04, hashValue);
  317. ASN1 digestInfo = new ASN1 (0x30);
  318. digestInfo.Add (digestAlgorithm);
  319. digestInfo.Add (digest);
  320. t = digestInfo.GetBytes ();
  321. }
  322. else
  323. {
  324. // There are no valid OID, in this case t = hashValue
  325. // This is the case of the MD5SHA hash algorithm
  326. t = hashValue;
  327. }
  328. Buffer.BlockCopy (hashValue, 0, t, t.Length - hashValue.Length, hashValue.Length);
  329. int PSLength = System.Math.Max (8, emLength - t.Length - 3);
  330. // PS = PSLength of 0xff
  331. // EM = 0x00 | 0x01 | PS | 0x00 | T
  332. byte[] EM = new byte [PSLength + t.Length + 3];
  333. EM [1] = 0x01;
  334. for (int i=2; i < PSLength + 2; i++)
  335. EM[i] = 0xff;
  336. Buffer.BlockCopy (t, 0, EM, PSLength + 3, t.Length);
  337. return EM;
  338. }
  339. // PKCS #1 v.2.1, Section B.2.1
  340. public static byte[] MGF1 (HashAlgorithm hash, byte[] mgfSeed, int maskLen)
  341. {
  342. // 1. If maskLen > 2^32 hLen, output "mask too long" and stop.
  343. // easy - this is impossible by using a int (31bits) as parameter ;-)
  344. // BUT with a signed int we do have to check for negative values!
  345. if (maskLen < 0)
  346. throw new OverflowException();
  347. int mgfSeedLength = mgfSeed.Length;
  348. int hLen = (hash.HashSize >> 3); // from bits to bytes
  349. int iterations = (maskLen / hLen);
  350. if (maskLen % hLen != 0)
  351. iterations++;
  352. // 2. Let T be the empty octet string.
  353. byte[] T = new byte [iterations * hLen];
  354. byte[] toBeHashed = new byte [mgfSeedLength + 4];
  355. int pos = 0;
  356. // 3. For counter from 0 to \ceil (maskLen / hLen) - 1, do the following:
  357. for (int counter = 0; counter < iterations; counter++) {
  358. // a. Convert counter to an octet string C of length 4 octets
  359. byte[] C = I2OSP (counter, 4);
  360. // b. Concatenate the hash of the seed mgfSeed and C to the octet string T:
  361. // T = T || Hash (mgfSeed || C)
  362. Buffer.BlockCopy (mgfSeed, 0, toBeHashed, 0, mgfSeedLength);
  363. Buffer.BlockCopy (C, 0, toBeHashed, mgfSeedLength, 4);
  364. byte[] output = hash.ComputeHash (toBeHashed);
  365. Buffer.BlockCopy (output, 0, T, pos, hLen);
  366. pos += hLen;
  367. }
  368. // 4. Output the leading maskLen octets of T as the octet string mask.
  369. byte[] mask = new byte [maskLen];
  370. Buffer.BlockCopy (T, 0, mask, 0, maskLen);
  371. return mask;
  372. }
  373. static internal string HashNameFromOid (string oid, bool throwOnError = true)
  374. {
  375. switch (oid) {
  376. case "1.2.840.113549.1.1.2": // MD2 with RSA encryption
  377. return "MD2";
  378. case "1.2.840.113549.1.1.3": // MD4 with RSA encryption
  379. return "MD4";
  380. case "1.2.840.113549.1.1.4": // MD5 with RSA encryption
  381. return "MD5";
  382. case "1.2.840.113549.1.1.5": // SHA-1 with RSA Encryption
  383. case "1.3.14.3.2.29": // SHA1 with RSA signature
  384. case "1.2.840.10040.4.3": // SHA1-1 with DSA
  385. return "SHA1";
  386. case "1.2.840.113549.1.1.11": // SHA-256 with RSA Encryption
  387. return "SHA256";
  388. case "1.2.840.113549.1.1.12": // SHA-384 with RSA Encryption
  389. return "SHA384";
  390. case "1.2.840.113549.1.1.13": // SHA-512 with RSA Encryption
  391. return "SHA512";
  392. case "1.3.36.3.3.1.2":
  393. return "RIPEMD160";
  394. default:
  395. if (throwOnError)
  396. throw new CryptographicException ("Unsupported hash algorithm: " + oid);
  397. return null;
  398. }
  399. }
  400. static internal HashAlgorithm CreateFromOid (string oid)
  401. {
  402. return CreateFromName (HashNameFromOid (oid));
  403. }
  404. static internal HashAlgorithm CreateFromName (string name)
  405. {
  406. #if FULL_AOT_RUNTIME
  407. switch (name) {
  408. case "MD2":
  409. return MD2.Create ();
  410. case "MD4":
  411. return MD4.Create ();
  412. case "MD5":
  413. return MD5.Create ();
  414. case "SHA1":
  415. return SHA1.Create ();
  416. case "SHA256":
  417. return SHA256.Create ();
  418. case "SHA384":
  419. return SHA384.Create ();
  420. case "SHA512":
  421. return SHA512.Create ();
  422. case "RIPEMD160":
  423. return RIPEMD160.Create ();
  424. default:
  425. try {
  426. return (HashAlgorithm) Activator.CreateInstance (Type.GetType (name));
  427. }
  428. catch {
  429. throw new CryptographicException ("Unsupported hash algorithm: " + name);
  430. }
  431. }
  432. #else
  433. return HashAlgorithm.Create (name);
  434. #endif
  435. }
  436. }
  437. }