IncrementalMD5.cs 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. /* Copyright 2016 MongoDB Inc.
  2. *
  3. * Licensed under the Apache License, Version 2.0 (the "License");
  4. * you may not use this file except in compliance with the License.
  5. * You may obtain a copy of the License at
  6. *
  7. * http://www.apache.org/licenses/LICENSE-2.0
  8. *
  9. * Unless required by applicable law or agreed to in writing, software
  10. * distributed under the License is distributed on an "AS IS" BASIS,
  11. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. * See the License for the specific language governing permissions and
  13. * limitations under the License.
  14. */
  15. using System;
  16. using System.Security.Cryptography;
  17. namespace MongoDB.Shared
  18. {
  19. internal abstract class IncrementalMD5 : IDisposable
  20. {
  21. public static IncrementalMD5 Create()
  22. {
  23. #if NET45
  24. return new IncrementalMD5Net45();
  25. #else
  26. return new IncrementalMD5NetStandard16();
  27. #endif
  28. }
  29. public abstract void AppendData(byte[] data, int offset, int count);
  30. public abstract void Dispose();
  31. public abstract byte[] GetHashAndReset();
  32. }
  33. #if NET45
  34. internal class IncrementalMD5Net45 : IncrementalMD5
  35. {
  36. private static readonly byte[] __emptyByteArray = new byte[0];
  37. private MD5 _md5;
  38. public override void AppendData(byte[] data, int offset, int count)
  39. {
  40. if (_md5 == null)
  41. {
  42. _md5 = MD5.Create();
  43. }
  44. _md5.TransformBlock(data, offset, count, null, 0);
  45. }
  46. public override void Dispose()
  47. {
  48. if (_md5 != null)
  49. {
  50. _md5.Dispose();
  51. }
  52. }
  53. public override byte[] GetHashAndReset()
  54. {
  55. if (_md5 == null)
  56. {
  57. _md5 = MD5.Create();
  58. }
  59. _md5.TransformFinalBlock(__emptyByteArray, 0, 0);
  60. var hash = _md5.Hash;
  61. _md5.Dispose();
  62. _md5 = null;
  63. return hash;
  64. }
  65. }
  66. #else
  67. internal class IncrementalMD5NetStandard16 : IncrementalMD5
  68. {
  69. private readonly IncrementalHash _incrementalHash;
  70. public IncrementalMD5NetStandard16()
  71. {
  72. _incrementalHash = IncrementalHash.CreateHash(HashAlgorithmName.MD5);
  73. }
  74. public override void AppendData(byte[] data, int offset, int count)
  75. {
  76. _incrementalHash.AppendData(data, offset, count);
  77. }
  78. public override void Dispose()
  79. {
  80. _incrementalHash.Dispose();
  81. }
  82. public override byte[] GetHashAndReset()
  83. {
  84. return _incrementalHash.GetHashAndReset();
  85. }
  86. }
  87. #endif
  88. }