using Digest = std::vector<unsigned char>;
std::string digestToHex(const Digest& bytes, std::size_t length)
{
static const char digits[] = "0123456789abcdef";
const std::size_t fullLen = bytes.size()*2;
std::size_t len = length ? length*2 : fullLen;
if (len > fullLen)
throw Poco::InvalidArgumentException(
Poco::format("DigestEngine::digestToHex(): invalid length : %z,"
"max alllowed is %z", length, fullLen));
std::string result;
result.reserve(len);
for (auto b: bytes)
{
result += digits[(b >> 4) & 0xF];
result += digits[b & 0xF];
if (result.size() >= len) break;
}
return result;
}
Digest 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;
}
标签:std,十六进制,字节,length,result,&&,字符串,digest,size
From: https://www.cnblogs.com/sunwenqi/p/18201554