SHA3Digest.cs 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
  2. #pragma warning disable
  3. using System;
  4. using System.Diagnostics;
  5. using Best.HTTP.SecureProtocol.Org.BouncyCastle.Utilities;
  6. namespace Best.HTTP.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. #if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || UNITY_2021_2_OR_NEWER
  52. public override int DoFinal(Span<byte> output)
  53. {
  54. AbsorbBits(0x02, 2);
  55. return base.DoFinal(output);
  56. }
  57. #endif
  58. /*
  59. * TODO Possible API change to support partial-byte suffixes.
  60. */
  61. protected override int DoFinal(byte[] output, int outOff, byte partialByte, int partialBits)
  62. {
  63. if (partialBits < 0 || partialBits > 7)
  64. throw new ArgumentException("must be in the range [0,7]", "partialBits");
  65. int finalInput = (partialByte & ((1 << partialBits) - 1)) | (0x02 << partialBits);
  66. Debug.Assert(finalInput >= 0);
  67. int finalBits = partialBits + 2;
  68. if (finalBits >= 8)
  69. {
  70. Absorb((byte)finalInput);
  71. finalBits -= 8;
  72. finalInput >>= 8;
  73. }
  74. return base.DoFinal(output, outOff, (byte)finalInput, finalBits);
  75. }
  76. public override IMemoable Copy()
  77. {
  78. return new Sha3Digest(this);
  79. }
  80. }
  81. }
  82. #pragma warning restore
  83. #endif