RC2WrapEngine.cs 9.8 KB

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