SHA1.h 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. //==- SHA1.h - SHA1 implementation for LLVM --*- C++ -*-==//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. // This code is taken from public domain
  9. // (http://oauth.googlecode.com/svn/code/c/liboauth/src/sha1.c)
  10. // and modified by wrapping it in a C++ interface for LLVM,
  11. // and removing unnecessary code.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #ifndef LLVM_SUPPORT_SHA1_H
  15. #define LLVM_SUPPORT_SHA1_H
  16. #include <array>
  17. #include <cstdint>
  18. namespace llvm {
  19. template <typename T> class ArrayRef;
  20. class StringRef;
  21. /// A class that wrap the SHA1 algorithm.
  22. class SHA1 {
  23. public:
  24. SHA1() { init(); }
  25. /// Reinitialize the internal state
  26. void init();
  27. /// Digest more data.
  28. void update(ArrayRef<uint8_t> Data);
  29. /// Digest more data.
  30. void update(StringRef Str);
  31. /// Return a reference to the current raw 160-bits SHA1 for the digested data
  32. /// since the last call to init(). This call will add data to the internal
  33. /// state and as such is not suited for getting an intermediate result
  34. /// (see result()).
  35. StringRef final();
  36. /// Return a reference to the current raw 160-bits SHA1 for the digested data
  37. /// since the last call to init(). This is suitable for getting the SHA1 at
  38. /// any time without invalidating the internal state so that more calls can be
  39. /// made into update.
  40. StringRef result();
  41. /// Returns a raw 160-bit SHA1 hash for the given data.
  42. static std::array<uint8_t, 20> hash(ArrayRef<uint8_t> Data);
  43. private:
  44. /// Define some constants.
  45. /// "static constexpr" would be cleaner but MSVC does not support it yet.
  46. enum { BLOCK_LENGTH = 64 };
  47. enum { HASH_LENGTH = 20 };
  48. // Internal State
  49. struct {
  50. union {
  51. uint8_t C[BLOCK_LENGTH];
  52. uint32_t L[BLOCK_LENGTH / 4];
  53. } Buffer;
  54. uint32_t State[HASH_LENGTH / 4];
  55. uint32_t ByteCount;
  56. uint8_t BufferOffset;
  57. } InternalState;
  58. // Internal copy of the hash, populated and accessed on calls to result()
  59. uint32_t HashResult[HASH_LENGTH / 4];
  60. // Helper
  61. void writebyte(uint8_t data);
  62. void hashBlock();
  63. void addUncounted(uint8_t data);
  64. void pad();
  65. };
  66. } // end llvm namespace
  67. #endif