added DigestEngine::digestFromHex

This commit is contained in:
Peter Schojer
2008-10-16 08:00:48 +00:00
parent 9a024d4516
commit 30e0ed3dd2
4 changed files with 54 additions and 4 deletions

View File

@@ -1,7 +1,7 @@
//
// DigestEngine.cpp
//
// $Id: //poco/svn/Foundation/src/DigestEngine.cpp#2 $
// $Id: //poco/Main/Foundation/src/DigestEngine.cpp#11 $
//
// Library: Foundation
// Package: Crypt
@@ -35,6 +35,7 @@
#include "Poco/DigestEngine.h"
#include "Poco/Exception.h"
namespace Poco {
@@ -65,4 +66,39 @@ std::string DigestEngine::digestToHex(const Digest& bytes)
}
DigestEngine::Digest DigestEngine::digestFromHex(const std::string& digest)
{
if (digest.size() % 2 != 0)
throw DataFormatException();
Digest result;
result.reserve(digest.size()/2);
for (std::size_t i = 0; i < digest.size(); ++i)
{
int c = 0;
// first upper 4 bits
if (digest[i] >= '0' && digest[i] <= '9')
c = digest[i] - '0';
else if (digest[i] >= 'a' && digest[i] <= 'f')
c = digest[i] - 'a'+10;
else if (digest[i] >= 'A' && digest[i] <= 'F')
c = digest[i] - 'A'+10;
else
throw DataFormatException();
c <<= 4;
++i;
if (digest[i] >= '0' && digest[i] <= '9')
c += digest[i] - '0';
else if (digest[i] >= 'a' && digest[i] <= 'f')
c += digest[i] - 'a'+10;
else if (digest[i] >= 'A' && digest[i] <= 'F')
c += digest[i] - 'A'+10;
else
throw DataFormatException();
result.push_back(static_cast<unsigned char>(c));
}
return result;
}
} // namespace Poco