Iso9796d2Signer.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554
  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.Parameters;
  5. using Best.HTTP.SecureProtocol.Org.BouncyCastle.Utilities;
  6. namespace Best.HTTP.SecureProtocol.Org.BouncyCastle.Crypto.Signers
  7. {
  8. /// <summary> ISO9796-2 - mechanism using a hash function with recovery (scheme 1)</summary>
  9. public class Iso9796d2Signer : ISignerWithRecovery
  10. {
  11. /// <summary>
  12. /// Return a reference to the recoveredMessage message.
  13. /// </summary>
  14. /// <returns>The full/partial recoveredMessage message.</returns>
  15. /// <seealso cref="ISignerWithRecovery.GetRecoveredMessage"/>
  16. public byte[] GetRecoveredMessage()
  17. {
  18. return recoveredMessage;
  19. }
  20. private IDigest digest;
  21. private IAsymmetricBlockCipher cipher;
  22. private int trailer;
  23. private int keyBits;
  24. private byte[] block;
  25. private byte[] mBuf;
  26. private int messageLength;
  27. private bool fullMessage;
  28. private byte[] recoveredMessage;
  29. private byte[] preSig;
  30. private byte[] preBlock;
  31. /// <summary>
  32. /// Generate a signer with either implicit or explicit trailers for ISO9796-2.
  33. /// </summary>
  34. /// <param name="cipher">base cipher to use for signature creation/verification</param>
  35. /// <param name="digest">digest to use.</param>
  36. /// <param name="isImplicit">whether or not the trailer is implicit or gives the hash.</param>
  37. public Iso9796d2Signer(
  38. IAsymmetricBlockCipher cipher,
  39. IDigest digest,
  40. bool isImplicit)
  41. {
  42. this.cipher = cipher;
  43. this.digest = digest;
  44. if (isImplicit)
  45. {
  46. trailer = IsoTrailers.TRAILER_IMPLICIT;
  47. }
  48. else if (IsoTrailers.NoTrailerAvailable(digest))
  49. {
  50. throw new ArgumentException("no valid trailer", "digest");
  51. }
  52. else
  53. {
  54. trailer = IsoTrailers.GetTrailer(digest);
  55. }
  56. }
  57. /// <summary> Constructor for a signer with an explicit digest trailer.
  58. ///
  59. /// </summary>
  60. /// <param name="cipher">cipher to use.
  61. /// </param>
  62. /// <param name="digest">digest to sign with.
  63. /// </param>
  64. public Iso9796d2Signer(IAsymmetricBlockCipher cipher, IDigest digest)
  65. : this(cipher, digest, false)
  66. {
  67. }
  68. public virtual string AlgorithmName
  69. {
  70. get { return digest.AlgorithmName + "with" + "ISO9796-2S1"; }
  71. }
  72. public virtual void Init(bool forSigning, ICipherParameters parameters)
  73. {
  74. RsaKeyParameters kParam = (RsaKeyParameters) parameters;
  75. cipher.Init(forSigning, kParam);
  76. keyBits = kParam.Modulus.BitLength;
  77. block = new byte[(keyBits + 7) / 8];
  78. if (trailer == IsoTrailers.TRAILER_IMPLICIT)
  79. {
  80. mBuf = new byte[block.Length - digest.GetDigestSize() - 2];
  81. }
  82. else
  83. {
  84. mBuf = new byte[block.Length - digest.GetDigestSize() - 3];
  85. }
  86. Reset();
  87. }
  88. /// <summary> compare two byte arrays - constant time.</summary>
  89. private bool IsSameAs(byte[] a, byte[] b)
  90. {
  91. int checkLen;
  92. if (messageLength > mBuf.Length)
  93. {
  94. if (mBuf.Length > b.Length)
  95. {
  96. return false;
  97. }
  98. checkLen = mBuf.Length;
  99. }
  100. else
  101. {
  102. if (messageLength != b.Length)
  103. {
  104. return false;
  105. }
  106. checkLen = b.Length;
  107. }
  108. bool isOkay = true;
  109. for (int i = 0; i != checkLen; i++)
  110. {
  111. if (a[i] != b[i])
  112. {
  113. isOkay = false;
  114. }
  115. }
  116. return isOkay;
  117. }
  118. /// <summary> clear possible sensitive data</summary>
  119. private void ClearBlock(
  120. byte[] block)
  121. {
  122. Array.Clear(block, 0, block.Length);
  123. }
  124. public virtual void UpdateWithRecoveredMessage(
  125. byte[] signature)
  126. {
  127. byte[] block = cipher.ProcessBlock(signature, 0, signature.Length);
  128. if (((block[0] & 0xC0) ^ 0x40) != 0)
  129. throw new InvalidCipherTextException("malformed signature");
  130. if (((block[block.Length - 1] & 0xF) ^ 0xC) != 0)
  131. throw new InvalidCipherTextException("malformed signature");
  132. int delta = 0;
  133. if (((block[block.Length - 1] & 0xFF) ^ 0xBC) == 0)
  134. {
  135. delta = 1;
  136. }
  137. else
  138. {
  139. int sigTrail = ((block[block.Length - 2] & 0xFF) << 8) | (block[block.Length - 1] & 0xFF);
  140. if (IsoTrailers.NoTrailerAvailable(digest))
  141. throw new ArgumentException("unrecognised hash in signature");
  142. if (sigTrail != IsoTrailers.GetTrailer(digest))
  143. throw new InvalidOperationException("signer initialised with wrong digest for trailer " + sigTrail);
  144. delta = 2;
  145. }
  146. //
  147. // find out how much padding we've got
  148. //
  149. int mStart = 0;
  150. for (mStart = 0; mStart != block.Length; mStart++)
  151. {
  152. if (((block[mStart] & 0x0f) ^ 0x0a) == 0)
  153. break;
  154. }
  155. mStart++;
  156. int off = block.Length - delta - digest.GetDigestSize();
  157. //
  158. // there must be at least one byte of message string
  159. //
  160. if ((off - mStart) <= 0)
  161. throw new InvalidCipherTextException("malformed block");
  162. //
  163. // if we contain the whole message as well, check the hash of that.
  164. //
  165. if ((block[0] & 0x20) == 0)
  166. {
  167. fullMessage = true;
  168. recoveredMessage = new byte[off - mStart];
  169. Array.Copy(block, mStart, recoveredMessage, 0, recoveredMessage.Length);
  170. }
  171. else
  172. {
  173. fullMessage = false;
  174. recoveredMessage = new byte[off - mStart];
  175. Array.Copy(block, mStart, recoveredMessage, 0, recoveredMessage.Length);
  176. }
  177. preSig = signature;
  178. preBlock = block;
  179. digest.BlockUpdate(recoveredMessage, 0, recoveredMessage.Length);
  180. messageLength = recoveredMessage.Length;
  181. recoveredMessage.CopyTo(mBuf, 0);
  182. }
  183. public virtual void Update(byte input)
  184. {
  185. digest.Update(input);
  186. if (messageLength < mBuf.Length)
  187. {
  188. mBuf[messageLength] = input;
  189. }
  190. messageLength++;
  191. }
  192. public virtual void BlockUpdate(byte[] input, int inOff, int inLen)
  193. {
  194. #if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || UNITY_2021_2_OR_NEWER
  195. BlockUpdate(input.AsSpan(inOff, inLen));
  196. #else
  197. while (inLen > 0 && messageLength < mBuf.Length)
  198. {
  199. this.Update(input[inOff]);
  200. inOff++;
  201. inLen--;
  202. }
  203. if (inLen > 0)
  204. {
  205. digest.BlockUpdate(input, inOff, inLen);
  206. messageLength += inLen;
  207. }
  208. #endif
  209. }
  210. #if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || UNITY_2021_2_OR_NEWER
  211. public virtual void BlockUpdate(ReadOnlySpan<byte> input)
  212. {
  213. while (!input.IsEmpty && messageLength < mBuf.Length)
  214. {
  215. this.Update(input[0]);
  216. input = input[1..];
  217. }
  218. if (!input.IsEmpty)
  219. {
  220. digest.BlockUpdate(input);
  221. messageLength += input.Length;
  222. }
  223. }
  224. #endif
  225. /// <summary> reset the internal state</summary>
  226. public virtual void Reset()
  227. {
  228. digest.Reset();
  229. messageLength = 0;
  230. ClearBlock(mBuf);
  231. if (recoveredMessage != null)
  232. {
  233. ClearBlock(recoveredMessage);
  234. }
  235. recoveredMessage = null;
  236. fullMessage = false;
  237. if (preSig != null)
  238. {
  239. preSig = null;
  240. ClearBlock(preBlock);
  241. preBlock = null;
  242. }
  243. }
  244. /// <summary> Generate a signature for the loaded message using the key we were
  245. /// initialised with.
  246. /// </summary>
  247. public virtual byte[] GenerateSignature()
  248. {
  249. int digSize = digest.GetDigestSize();
  250. int t = 0;
  251. int delta = 0;
  252. if (trailer == IsoTrailers.TRAILER_IMPLICIT)
  253. {
  254. t = 8;
  255. delta = block.Length - digSize - 1;
  256. digest.DoFinal(block, delta);
  257. block[block.Length - 1] = (byte)IsoTrailers.TRAILER_IMPLICIT;
  258. }
  259. else
  260. {
  261. t = 16;
  262. delta = block.Length - digSize - 2;
  263. digest.DoFinal(block, delta);
  264. block[block.Length - 2] = (byte) ((uint)trailer >> 8);
  265. block[block.Length - 1] = (byte) trailer;
  266. }
  267. byte header = 0;
  268. int x = (digSize + messageLength) * 8 + t + 4 - keyBits;
  269. if (x > 0)
  270. {
  271. int mR = messageLength - ((x + 7) / 8);
  272. header = (byte) (0x60);
  273. delta -= mR;
  274. Array.Copy(mBuf, 0, block, delta, mR);
  275. }
  276. else
  277. {
  278. header = (byte) (0x40);
  279. delta -= messageLength;
  280. Array.Copy(mBuf, 0, block, delta, messageLength);
  281. }
  282. if ((delta - 1) > 0)
  283. {
  284. for (int i = delta - 1; i != 0; i--)
  285. {
  286. block[i] = (byte) 0xbb;
  287. }
  288. block[delta - 1] ^= (byte) 0x01;
  289. block[0] = (byte) 0x0b;
  290. block[0] |= header;
  291. }
  292. else
  293. {
  294. block[0] = (byte) 0x0a;
  295. block[0] |= header;
  296. }
  297. byte[] b = cipher.ProcessBlock(block, 0, block.Length);
  298. messageLength = 0;
  299. ClearBlock(mBuf);
  300. ClearBlock(block);
  301. return b;
  302. }
  303. /// <summary> return true if the signature represents a ISO9796-2 signature
  304. /// for the passed in message.
  305. /// </summary>
  306. public virtual bool VerifySignature(byte[] signature)
  307. {
  308. byte[] block;
  309. if (preSig == null)
  310. {
  311. try
  312. {
  313. block = cipher.ProcessBlock(signature, 0, signature.Length);
  314. }
  315. catch (Exception)
  316. {
  317. return false;
  318. }
  319. }
  320. else
  321. {
  322. if (!Arrays.AreEqual(preSig, signature))
  323. throw new InvalidOperationException("updateWithRecoveredMessage called on different signature");
  324. block = preBlock;
  325. preSig = null;
  326. preBlock = null;
  327. }
  328. if (((block[0] & 0xC0) ^ 0x40) != 0)
  329. return ReturnFalse(block);
  330. if (((block[block.Length - 1] & 0xF) ^ 0xC) != 0)
  331. return ReturnFalse(block);
  332. int delta = 0;
  333. if (((block[block.Length - 1] & 0xFF) ^ 0xBC) == 0)
  334. {
  335. delta = 1;
  336. }
  337. else
  338. {
  339. int sigTrail = ((block[block.Length - 2] & 0xFF) << 8) | (block[block.Length - 1] & 0xFF);
  340. if (IsoTrailers.NoTrailerAvailable(digest))
  341. throw new ArgumentException("unrecognised hash in signature");
  342. if (sigTrail != IsoTrailers.GetTrailer(digest))
  343. throw new InvalidOperationException("signer initialised with wrong digest for trailer " + sigTrail);
  344. delta = 2;
  345. }
  346. //
  347. // find out how much padding we've got
  348. //
  349. int mStart = 0;
  350. for (; mStart != block.Length; mStart++)
  351. {
  352. if (((block[mStart] & 0x0f) ^ 0x0a) == 0)
  353. {
  354. break;
  355. }
  356. }
  357. mStart++;
  358. //
  359. // check the hashes
  360. //
  361. byte[] hash = new byte[digest.GetDigestSize()];
  362. int off = block.Length - delta - hash.Length;
  363. //
  364. // there must be at least one byte of message string
  365. //
  366. if ((off - mStart) <= 0)
  367. {
  368. return ReturnFalse(block);
  369. }
  370. //
  371. // if we contain the whole message as well, check the hash of that.
  372. //
  373. if ((block[0] & 0x20) == 0)
  374. {
  375. fullMessage = true;
  376. // check right number of bytes passed in.
  377. if (messageLength > off - mStart)
  378. {
  379. return ReturnFalse(block);
  380. }
  381. digest.Reset();
  382. digest.BlockUpdate(block, mStart, off - mStart);
  383. digest.DoFinal(hash, 0);
  384. bool isOkay = true;
  385. for (int i = 0; i != hash.Length; i++)
  386. {
  387. block[off + i] ^= hash[i];
  388. if (block[off + i] != 0)
  389. {
  390. isOkay = false;
  391. }
  392. }
  393. if (!isOkay)
  394. {
  395. return ReturnFalse(block);
  396. }
  397. recoveredMessage = new byte[off - mStart];
  398. Array.Copy(block, mStart, recoveredMessage, 0, recoveredMessage.Length);
  399. }
  400. else
  401. {
  402. fullMessage = false;
  403. digest.DoFinal(hash, 0);
  404. bool isOkay = true;
  405. for (int i = 0; i != hash.Length; i++)
  406. {
  407. block[off + i] ^= hash[i];
  408. if (block[off + i] != 0)
  409. {
  410. isOkay = false;
  411. }
  412. }
  413. if (!isOkay)
  414. {
  415. return ReturnFalse(block);
  416. }
  417. recoveredMessage = new byte[off - mStart];
  418. Array.Copy(block, mStart, recoveredMessage, 0, recoveredMessage.Length);
  419. }
  420. //
  421. // if they've input a message check what we've recovered against
  422. // what was input.
  423. //
  424. if (messageLength != 0)
  425. {
  426. if (!IsSameAs(mBuf, recoveredMessage))
  427. {
  428. return ReturnFalse(block);
  429. }
  430. }
  431. ClearBlock(mBuf);
  432. ClearBlock(block);
  433. messageLength = 0;
  434. return true;
  435. }
  436. private bool ReturnFalse(byte[] block)
  437. {
  438. messageLength = 0;
  439. ClearBlock(mBuf);
  440. ClearBlock(block);
  441. return false;
  442. }
  443. /// <summary>
  444. /// Return true if the full message was recoveredMessage.
  445. /// </summary>
  446. /// <returns> true on full message recovery, false otherwise.</returns>
  447. /// <seealso cref="ISignerWithRecovery.HasFullMessage"/>
  448. public virtual bool HasFullMessage()
  449. {
  450. return fullMessage;
  451. }
  452. }
  453. }
  454. #pragma warning restore
  455. #endif