SHA3Digest.cs 2.4 KB

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