DigestEngine.cpp 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. //
  2. // DigestEngine.cpp
  3. //
  4. // $Id: //poco/1.4/Foundation/src/DigestEngine.cpp#1 $
  5. //
  6. // Library: Foundation
  7. // Package: Crypt
  8. // Module: DigestEngine
  9. //
  10. // Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
  11. // and Contributors.
  12. //
  13. // SPDX-License-Identifier: BSL-1.0
  14. //
  15. #include "Poco/DigestEngine.h"
  16. #include "Poco/Exception.h"
  17. namespace Poco
  18. {
  19. DigestEngine::DigestEngine()
  20. {
  21. }
  22. DigestEngine::~DigestEngine()
  23. {
  24. }
  25. std::string DigestEngine::digestToHex(const Digest& bytes)
  26. {
  27. static const char digits[] = "0123456789abcdef";
  28. std::string result;
  29. result.reserve(bytes.size() * 2);
  30. for (Digest::const_iterator it = bytes.begin(); it != bytes.end(); ++it)
  31. {
  32. unsigned char c = *it;
  33. result += digits[(c >> 4) & 0xF];
  34. result += digits[c & 0xF];
  35. }
  36. return result;
  37. }
  38. DigestEngine::Digest DigestEngine::digestFromHex(const std::string& digest)
  39. {
  40. if (digest.size() % 2 != 0)
  41. throw DataFormatException();
  42. Digest result;
  43. result.reserve(digest.size() / 2);
  44. for (std::size_t i = 0; i < digest.size(); ++i)
  45. {
  46. int c = 0;
  47. // first upper 4 bits
  48. if (digest[i] >= '0' && digest[i] <= '9')
  49. c = digest[i] - '0';
  50. else if (digest[i] >= 'a' && digest[i] <= 'f')
  51. c = digest[i] - 'a' + 10;
  52. else if (digest[i] >= 'A' && digest[i] <= 'F')
  53. c = digest[i] - 'A' + 10;
  54. else
  55. throw DataFormatException();
  56. c <<= 4;
  57. ++i;
  58. if (digest[i] >= '0' && digest[i] <= '9')
  59. c += digest[i] - '0';
  60. else if (digest[i] >= 'a' && digest[i] <= 'f')
  61. c += digest[i] - 'a' + 10;
  62. else if (digest[i] >= 'A' && digest[i] <= 'F')
  63. c += digest[i] - 'A' + 10;
  64. else
  65. throw DataFormatException();
  66. result.push_back(static_cast<unsigned char>(c));
  67. }
  68. return result;
  69. }
  70. } // namespace Poco