From 74f0d4abcd8de84283858fe144772e688669e46a Mon Sep 17 00:00:00 2001 From: Sebastian Holtermann Date: Wed, 10 Aug 2016 10:35:19 +0200 Subject: [PATCH] cmCryptoHash: New byte hash to string function --- Source/cmCryptoHash.cxx | 31 +++++++++++++++++++++++++++++++ Source/cmCryptoHash.h | 7 +++++++ 2 files changed, 38 insertions(+) diff --git a/Source/cmCryptoHash.cxx b/Source/cmCryptoHash.cxx index 8d60c1f1a..59b9abdb9 100644 --- a/Source/cmCryptoHash.cxx +++ b/Source/cmCryptoHash.cxx @@ -34,6 +34,37 @@ CM_AUTO_PTR cmCryptoHash::New(const char* algo) } } +bool cmCryptoHash::IntFromHexDigit(char input, char& output) +{ + if (input >= '0' && input <= '9') { + output = char(input - '0'); + return true; + } else if (input >= 'a' && input <= 'f') { + output = char(input - 'a' + 0xA); + return true; + } else if (input >= 'A' && input <= 'F') { + output = char(input - 'A' + 0xA); + return true; + } + return false; +} + +std::string cmCryptoHash::ByteHashToString( + const std::vector& hash) +{ + // Map from 4-bit index to hexadecimal representation. + static char const hex[16] = { '0', '1', '2', '3', '4', '5', '6', '7', + '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; + + std::string res; + for (std::vector::const_iterator vit = hash.begin(); + vit != hash.end(); ++vit) { + res.push_back(hex[(*vit) >> 4]); + res.push_back(hex[(*vit) & 0xF]); + } + return res; +} + std::string cmCryptoHash::HashString(const std::string& input) { this->Initialize(); diff --git a/Source/cmCryptoHash.h b/Source/cmCryptoHash.h index 84dea9b08..80ab26925 100644 --- a/Source/cmCryptoHash.h +++ b/Source/cmCryptoHash.h @@ -29,6 +29,13 @@ public: /// @return A valid auto pointer if algo is supported or /// an invalid/NULL pointer otherwise static CM_AUTO_PTR New(const char* algo); + /// @brief Converts a hex character to its binary value (4 bits) + /// @arg input Hex character [0-9a-fA-F]. + /// @arg output Binary value of the input character (4 bits) + /// @return True if input was a valid hex character + static bool IntFromHexDigit(char input, char& output); + /// @brief Converts a byte hash to a sequence of hex character pairs + static std::string ByteHashToString(const std::vector& hash); /// @brief Calculates a hash string from string input data /// @return Sequence of hex characters pairs for each byte of the binary hash std::string HashString(const std::string& input);