cmCryptoHash.h 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. /* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
  2. file Copyright.txt or https://cmake.org/licensing for details. */
  3. #ifndef cmCryptoHash_h
  4. #define cmCryptoHash_h
  5. #include <cmConfigure.h>
  6. #include <cm_auto_ptr.hxx>
  7. #include <string>
  8. #include <vector>
  9. /**
  10. * @brief Abstract base class for cryptographic hash generators
  11. */
  12. class cmCryptoHash
  13. {
  14. public:
  15. enum Algo
  16. {
  17. AlgoMD5,
  18. AlgoSHA1,
  19. AlgoSHA224,
  20. AlgoSHA256,
  21. AlgoSHA384,
  22. AlgoSHA512,
  23. AlgoSHA3_224,
  24. AlgoSHA3_256,
  25. AlgoSHA3_384,
  26. AlgoSHA3_512
  27. };
  28. cmCryptoHash(Algo algo);
  29. ~cmCryptoHash();
  30. /// @brief Returns a new hash generator of the requested type
  31. /// @arg algo Hash type name. Supported hash types are
  32. /// MD5, SHA1, SHA224, SHA256, SHA384, SHA512,
  33. /// SHA3_224, SHA3_256, SHA3_384, SHA3_512
  34. /// @return A valid auto pointer if algo is supported or
  35. /// an invalid/NULL pointer otherwise
  36. static CM_AUTO_PTR<cmCryptoHash> New(const char* algo);
  37. /// @brief Converts a hex character to its binary value (4 bits)
  38. /// @arg input Hex character [0-9a-fA-F].
  39. /// @arg output Binary value of the input character (4 bits)
  40. /// @return True if input was a valid hex character
  41. static bool IntFromHexDigit(char input, char& output);
  42. /// @brief Converts a byte hash to a sequence of hex character pairs
  43. static std::string ByteHashToString(const std::vector<unsigned char>& hash);
  44. /// @brief Calculates a binary hash from string input data
  45. /// @return Binary hash vector
  46. std::vector<unsigned char> ByteHashString(const std::string& input);
  47. /// @brief Calculates a binary hash from file content
  48. /// @see ByteHashString()
  49. /// @return Non empty binary hash vector if the file was read successfully.
  50. /// An empty vector otherwise.
  51. std::vector<unsigned char> ByteHashFile(const std::string& file);
  52. /// @brief Calculates a hash string from string input data
  53. /// @return Sequence of hex characters pairs for each byte of the binary hash
  54. std::string HashString(const std::string& input);
  55. /// @brief Calculates a hash string from file content
  56. /// @see HashString()
  57. /// @return Non empty hash string if the file was read successfully.
  58. /// An empty string otherwise.
  59. std::string HashFile(const std::string& file);
  60. void Initialize();
  61. void Append(void const*, size_t);
  62. void Append(std::string const& str);
  63. std::vector<unsigned char> Finalize();
  64. std::string FinalizeHex();
  65. private:
  66. unsigned int Id;
  67. struct rhash_context* CTX;
  68. };
  69. #endif