SHA3Digest.cs 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
  2. #pragma warning disable
  3. using System;
  4. using System.Diagnostics;
  5. using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
  6. namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Digests
  7. {
  8. /// <summary>
  9. /// Implementation of SHA-3 based on following KeccakNISTInterface.c from http://keccak.noekeon.org/
  10. /// </summary>
  11. /// <remarks>
  12. /// Following the naming conventions used in the C source code to enable easy review of the implementation.
  13. /// </remarks>
  14. public class Sha3Digest
  15. : KeccakDigest
  16. {
  17. private static int CheckBitLength(int bitLength)
  18. {
  19. switch (bitLength)
  20. {
  21. case 224:
  22. case 256:
  23. case 384:
  24. case 512:
  25. return bitLength;
  26. default:
  27. throw new ArgumentException(bitLength + " not supported for SHA-3", "bitLength");
  28. }
  29. }
  30. public Sha3Digest()
  31. : this(256)
  32. {
  33. }
  34. public Sha3Digest(int bitLength)
  35. : base(CheckBitLength(bitLength))
  36. {
  37. }
  38. public Sha3Digest(Sha3Digest source)
  39. : base(source)
  40. {
  41. }
  42. public override string AlgorithmName
  43. {
  44. get { return "SHA3-" + fixedOutputLength; }
  45. }
  46. public override int DoFinal(byte[] output, int outOff)
  47. {
  48. AbsorbBits(0x02, 2);
  49. return base.DoFinal(output, outOff);
  50. }
  51. /*
  52. * TODO Possible API change to support partial-byte suffixes.
  53. */
  54. protected override int DoFinal(byte[] output, int outOff, byte partialByte, int partialBits)
  55. {
  56. if (partialBits < 0 || partialBits > 7)
  57. throw new ArgumentException("must be in the range [0,7]", "partialBits");
  58. int finalInput = (partialByte & ((1 << partialBits) - 1)) | (0x02 << partialBits);
  59. Debug.Assert(finalInput >= 0);
  60. int finalBits = partialBits + 2;
  61. if (finalBits >= 8)
  62. {
  63. Absorb((byte)finalInput);
  64. finalBits -= 8;
  65. finalInput >>= 8;
  66. }
  67. return base.DoFinal(output, outOff, (byte)finalInput, finalBits);
  68. }
  69. public override IMemoable Copy()
  70. {
  71. return new Sha3Digest(this);
  72. }
  73. }
  74. }
  75. #pragma warning restore
  76. #endif