RC2WrapEngine.cs 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374
  1. #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
  2. #pragma warning disable
  3. using System;
  4. using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Digests;
  5. using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Modes;
  6. using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
  7. using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
  8. using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
  9. namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Engines
  10. {
  11. /**
  12. * Wrap keys according to RFC 3217 - RC2 mechanism
  13. */
  14. public class RC2WrapEngine
  15. : IWrapper
  16. {
  17. /** Field engine */
  18. private CbcBlockCipher engine;
  19. /** Field param */
  20. private ICipherParameters parameters;
  21. /** Field paramPlusIV */
  22. private ParametersWithIV paramPlusIV;
  23. /** Field iv */
  24. private byte[] iv;
  25. /** Field forWrapping */
  26. private bool forWrapping;
  27. private SecureRandom sr;
  28. /** Field IV2 */
  29. private static readonly byte[] IV2 =
  30. {
  31. (byte) 0x4a, (byte) 0xdd, (byte) 0xa2,
  32. (byte) 0x2c, (byte) 0x79, (byte) 0xe8,
  33. (byte) 0x21, (byte) 0x05
  34. };
  35. //
  36. // checksum digest
  37. //
  38. IDigest sha1 = new Sha1Digest();
  39. byte[] digest = new byte[20];
  40. /**
  41. * Method init
  42. *
  43. * @param forWrapping
  44. * @param param
  45. */
  46. public virtual void Init(
  47. bool forWrapping,
  48. ICipherParameters parameters)
  49. {
  50. this.forWrapping = forWrapping;
  51. this.engine = new CbcBlockCipher(new RC2Engine());
  52. if (parameters is ParametersWithRandom)
  53. {
  54. ParametersWithRandom pWithR = (ParametersWithRandom)parameters;
  55. sr = pWithR.Random;
  56. parameters = pWithR.Parameters;
  57. }
  58. else
  59. {
  60. sr = new SecureRandom();
  61. }
  62. if (parameters is ParametersWithIV)
  63. {
  64. if (!forWrapping)
  65. throw new ArgumentException("You should not supply an IV for unwrapping");
  66. this.paramPlusIV = (ParametersWithIV)parameters;
  67. this.iv = this.paramPlusIV.GetIV();
  68. this.parameters = this.paramPlusIV.Parameters;
  69. if (this.iv.Length != 8)
  70. throw new ArgumentException("IV is not 8 octets");
  71. }
  72. else
  73. {
  74. this.parameters = parameters;
  75. if (this.forWrapping)
  76. {
  77. // Hm, we have no IV but we want to wrap ?!?
  78. // well, then we have to create our own IV.
  79. this.iv = new byte[8];
  80. sr.NextBytes(iv);
  81. this.paramPlusIV = new ParametersWithIV(this.parameters, this.iv);
  82. }
  83. }
  84. }
  85. /**
  86. * Method GetAlgorithmName
  87. *
  88. * @return
  89. */
  90. public virtual string AlgorithmName
  91. {
  92. get { return "RC2"; }
  93. }
  94. /**
  95. * Method wrap
  96. *
  97. * @param in
  98. * @param inOff
  99. * @param inLen
  100. * @return
  101. */
  102. public virtual byte[] Wrap(
  103. byte[] input,
  104. int inOff,
  105. int length)
  106. {
  107. if (!forWrapping)
  108. {
  109. throw new InvalidOperationException("Not initialized for wrapping");
  110. }
  111. int len = length + 1;
  112. if ((len % 8) != 0)
  113. {
  114. len += 8 - (len % 8);
  115. }
  116. byte [] keyToBeWrapped = new byte[len];
  117. keyToBeWrapped[0] = (byte)length;
  118. Array.Copy(input, inOff, keyToBeWrapped, 1, length);
  119. byte[] pad = new byte[keyToBeWrapped.Length - length - 1];
  120. if (pad.Length > 0)
  121. {
  122. sr.NextBytes(pad);
  123. Array.Copy(pad, 0, keyToBeWrapped, length + 1, pad.Length);
  124. }
  125. // Compute the CMS Key Checksum, (section 5.6.1), call this CKS.
  126. byte[] CKS = CalculateCmsKeyChecksum(keyToBeWrapped);
  127. // Let WKCKS = WK || CKS where || is concatenation.
  128. byte[] WKCKS = new byte[keyToBeWrapped.Length + CKS.Length];
  129. Array.Copy(keyToBeWrapped, 0, WKCKS, 0, keyToBeWrapped.Length);
  130. Array.Copy(CKS, 0, WKCKS, keyToBeWrapped.Length, CKS.Length);
  131. // Encrypt WKCKS in CBC mode using KEK as the key and IV as the
  132. // initialization vector. Call the results TEMP1.
  133. byte [] TEMP1 = new byte[WKCKS.Length];
  134. Array.Copy(WKCKS, 0, TEMP1, 0, WKCKS.Length);
  135. int noOfBlocks = WKCKS.Length / engine.GetBlockSize();
  136. int extraBytes = WKCKS.Length % engine.GetBlockSize();
  137. if (extraBytes != 0)
  138. {
  139. throw new InvalidOperationException("Not multiple of block length");
  140. }
  141. engine.Init(true, paramPlusIV);
  142. for (int i = 0; i < noOfBlocks; i++)
  143. {
  144. int currentBytePos = i * engine.GetBlockSize();
  145. engine.ProcessBlock(TEMP1, currentBytePos, TEMP1, currentBytePos);
  146. }
  147. // Left TEMP2 = IV || TEMP1.
  148. byte[] TEMP2 = new byte[this.iv.Length + TEMP1.Length];
  149. Array.Copy(this.iv, 0, TEMP2, 0, this.iv.Length);
  150. Array.Copy(TEMP1, 0, TEMP2, this.iv.Length, TEMP1.Length);
  151. // Reverse the order of the octets in TEMP2 and call the result TEMP3.
  152. byte[] TEMP3 = new byte[TEMP2.Length];
  153. for (int i = 0; i < TEMP2.Length; i++)
  154. {
  155. TEMP3[i] = TEMP2[TEMP2.Length - (i + 1)];
  156. }
  157. // Encrypt TEMP3 in CBC mode using the KEK and an initialization vector
  158. // of 0x 4a dd a2 2c 79 e8 21 05. The resulting cipher text is the desired
  159. // result. It is 40 octets long if a 168 bit key is being wrapped.
  160. ParametersWithIV param2 = new ParametersWithIV(this.parameters, IV2);
  161. this.engine.Init(true, param2);
  162. for (int i = 0; i < noOfBlocks + 1; i++)
  163. {
  164. int currentBytePos = i * engine.GetBlockSize();
  165. engine.ProcessBlock(TEMP3, currentBytePos, TEMP3, currentBytePos);
  166. }
  167. return TEMP3;
  168. }
  169. /**
  170. * Method unwrap
  171. *
  172. * @param in
  173. * @param inOff
  174. * @param inLen
  175. * @return
  176. * @throws InvalidCipherTextException
  177. */
  178. public virtual byte[] Unwrap(
  179. byte[] input,
  180. int inOff,
  181. int length)
  182. {
  183. if (forWrapping)
  184. {
  185. throw new InvalidOperationException("Not set for unwrapping");
  186. }
  187. if (input == null)
  188. {
  189. throw new InvalidCipherTextException("Null pointer as ciphertext");
  190. }
  191. if (length % engine.GetBlockSize() != 0)
  192. {
  193. throw new InvalidCipherTextException("Ciphertext not multiple of "
  194. + engine.GetBlockSize());
  195. }
  196. /*
  197. // Check if the length of the cipher text is reasonable given the key
  198. // type. It must be 40 bytes for a 168 bit key and either 32, 40, or
  199. // 48 bytes for a 128, 192, or 256 bit key. If the length is not supported
  200. // or inconsistent with the algorithm for which the key is intended,
  201. // return error.
  202. //
  203. // we do not accept 168 bit keys. it has to be 192 bit.
  204. int lengthA = (estimatedKeyLengthInBit / 8) + 16;
  205. int lengthB = estimatedKeyLengthInBit % 8;
  206. if ((lengthA != keyToBeUnwrapped.Length) || (lengthB != 0)) {
  207. throw new XMLSecurityException("empty");
  208. }
  209. */
  210. // Decrypt the cipher text with TRIPLedeS in CBC mode using the KEK
  211. // and an initialization vector (IV) of 0x4adda22c79e82105. Call the output TEMP3.
  212. ParametersWithIV param2 = new ParametersWithIV(this.parameters, IV2);
  213. this.engine.Init(false, param2);
  214. byte [] TEMP3 = new byte[length];
  215. Array.Copy(input, inOff, TEMP3, 0, length);
  216. for (int i = 0; i < (TEMP3.Length / engine.GetBlockSize()); i++)
  217. {
  218. int currentBytePos = i * engine.GetBlockSize();
  219. engine.ProcessBlock(TEMP3, currentBytePos, TEMP3, currentBytePos);
  220. }
  221. // Reverse the order of the octets in TEMP3 and call the result TEMP2.
  222. byte[] TEMP2 = new byte[TEMP3.Length];
  223. for (int i = 0; i < TEMP3.Length; i++)
  224. {
  225. TEMP2[i] = TEMP3[TEMP3.Length - (i + 1)];
  226. }
  227. // Decompose TEMP2 into IV, the first 8 octets, and TEMP1, the remaining octets.
  228. this.iv = new byte[8];
  229. byte[] TEMP1 = new byte[TEMP2.Length - 8];
  230. Array.Copy(TEMP2, 0, this.iv, 0, 8);
  231. Array.Copy(TEMP2, 8, TEMP1, 0, TEMP2.Length - 8);
  232. // Decrypt TEMP1 using TRIPLedeS in CBC mode using the KEK and the IV
  233. // found in the previous step. Call the result WKCKS.
  234. this.paramPlusIV = new ParametersWithIV(this.parameters, this.iv);
  235. this.engine.Init(false, this.paramPlusIV);
  236. byte[] LCEKPADICV = new byte[TEMP1.Length];
  237. Array.Copy(TEMP1, 0, LCEKPADICV, 0, TEMP1.Length);
  238. for (int i = 0; i < (LCEKPADICV.Length / engine.GetBlockSize()); i++)
  239. {
  240. int currentBytePos = i * engine.GetBlockSize();
  241. engine.ProcessBlock(LCEKPADICV, currentBytePos, LCEKPADICV, currentBytePos);
  242. }
  243. // Decompose LCEKPADICV. CKS is the last 8 octets and WK, the wrapped key, are
  244. // those octets before the CKS.
  245. byte[] result = new byte[LCEKPADICV.Length - 8];
  246. byte[] CKStoBeVerified = new byte[8];
  247. Array.Copy(LCEKPADICV, 0, result, 0, LCEKPADICV.Length - 8);
  248. Array.Copy(LCEKPADICV, LCEKPADICV.Length - 8, CKStoBeVerified, 0, 8);
  249. // Calculate a CMS Key Checksum, (section 5.6.1), over the WK and compare
  250. // with the CKS extracted in the above step. If they are not equal, return error.
  251. if (!CheckCmsKeyChecksum(result, CKStoBeVerified))
  252. {
  253. throw new InvalidCipherTextException(
  254. "Checksum inside ciphertext is corrupted");
  255. }
  256. if ((result.Length - ((result[0] & 0xff) + 1)) > 7)
  257. {
  258. throw new InvalidCipherTextException(
  259. "too many pad bytes (" + (result.Length - ((result[0] & 0xff) + 1)) + ")");
  260. }
  261. // CEK is the wrapped key, now extracted for use in data decryption.
  262. byte[] CEK = new byte[result[0]];
  263. Array.Copy(result, 1, CEK, 0, CEK.Length);
  264. return CEK;
  265. }
  266. /**
  267. * Some key wrap algorithms make use of the Key Checksum defined
  268. * in CMS [CMS-Algorithms]. This is used to provide an integrity
  269. * check value for the key being wrapped. The algorithm is
  270. *
  271. * - Compute the 20 octet SHA-1 hash on the key being wrapped.
  272. * - Use the first 8 octets of this hash as the checksum value.
  273. *
  274. * @param key
  275. * @return
  276. * @throws Exception
  277. * @see http://www.w3.org/TR/xmlenc-core/#sec-CMSKeyChecksum
  278. */
  279. private byte[] CalculateCmsKeyChecksum(
  280. byte[] key)
  281. {
  282. sha1.BlockUpdate(key, 0, key.Length);
  283. sha1.DoFinal(digest, 0);
  284. byte[] result = new byte[8];
  285. Array.Copy(digest, 0, result, 0, 8);
  286. return result;
  287. }
  288. /**
  289. * @param key
  290. * @param checksum
  291. * @return
  292. * @see http://www.w3.org/TR/xmlenc-core/#sec-CMSKeyChecksum
  293. */
  294. private bool CheckCmsKeyChecksum(
  295. byte[] key,
  296. byte[] checksum)
  297. {
  298. return Arrays.ConstantTimeAreEqual(CalculateCmsKeyChecksum(key), checksum);
  299. }
  300. }
  301. }
  302. #pragma warning restore
  303. #endif