Ssl3Mac.cs 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  1. #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
  2. using System;
  3. using Org.BouncyCastle.Crypto;
  4. using Org.BouncyCastle.Crypto.Parameters;
  5. using Org.BouncyCastle.Utilities;
  6. namespace Org.BouncyCastle.Crypto.Tls
  7. {
  8. /**
  9. * HMAC implementation based on original internet draft for HMAC (RFC 2104)
  10. *
  11. * The difference is that padding is concatentated versus XORed with the key
  12. *
  13. * H(K + opad, H(K + ipad, text))
  14. */
  15. public class Ssl3Mac
  16. : IMac
  17. {
  18. private const byte IPAD_BYTE = 0x36;
  19. private const byte OPAD_BYTE = 0x5C;
  20. internal static readonly byte[] IPAD = GenPad(IPAD_BYTE, 48);
  21. internal static readonly byte[] OPAD = GenPad(OPAD_BYTE, 48);
  22. private readonly IDigest digest;
  23. private readonly int padLength;
  24. private byte[] secret;
  25. /**
  26. * Base constructor for one of the standard digest algorithms that the byteLength of
  27. * the algorithm is know for. Behaviour is undefined for digests other than MD5 or SHA1.
  28. *
  29. * @param digest the digest.
  30. */
  31. public Ssl3Mac(IDigest digest)
  32. {
  33. this.digest = digest;
  34. if (digest.GetDigestSize() == 20)
  35. {
  36. this.padLength = 40;
  37. }
  38. else
  39. {
  40. this.padLength = 48;
  41. }
  42. }
  43. public virtual string AlgorithmName
  44. {
  45. get { return digest.AlgorithmName + "/SSL3MAC"; }
  46. }
  47. public virtual void Init(ICipherParameters parameters)
  48. {
  49. secret = Arrays.Clone(((KeyParameter)parameters).GetKey());
  50. Reset();
  51. }
  52. public virtual int GetMacSize()
  53. {
  54. return digest.GetDigestSize();
  55. }
  56. public virtual void Update(byte input)
  57. {
  58. digest.Update(input);
  59. }
  60. public virtual void BlockUpdate(byte[] input, int inOff, int len)
  61. {
  62. digest.BlockUpdate(input, inOff, len);
  63. }
  64. public virtual int DoFinal(byte[] output, int outOff)
  65. {
  66. byte[] tmp = new byte[digest.GetDigestSize()];
  67. digest.DoFinal(tmp, 0);
  68. digest.BlockUpdate(secret, 0, secret.Length);
  69. digest.BlockUpdate(OPAD, 0, padLength);
  70. digest.BlockUpdate(tmp, 0, tmp.Length);
  71. int len = digest.DoFinal(output, outOff);
  72. Reset();
  73. return len;
  74. }
  75. /**
  76. * Reset the mac generator.
  77. */
  78. public virtual void Reset()
  79. {
  80. digest.Reset();
  81. digest.BlockUpdate(secret, 0, secret.Length);
  82. digest.BlockUpdate(IPAD, 0, padLength);
  83. }
  84. private static byte[] GenPad(byte b, int count)
  85. {
  86. byte[] padding = new byte[count];
  87. Arrays.Fill(padding, b);
  88. return padding;
  89. }
  90. }
  91. }
  92. #endif