forked from pocoproject/poco
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDigestEngine.cpp
More file actions
85 lines (70 loc) · 1.68 KB
/
DigestEngine.cpp
File metadata and controls
85 lines (70 loc) · 1.68 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
//
// DigestEngine.cpp
//
// $Id: //poco/1.4/Foundation/src/DigestEngine.cpp#1 $
//
// Library: Foundation
// Package: Crypt
// Module: DigestEngine
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#include "Poco/DigestEngine.h"
#include "Poco/Exception.h"
namespace Poco
{
DigestEngine::DigestEngine()
{
}
DigestEngine::~DigestEngine()
{
}
std::string DigestEngine::digestToHex(const Digest& bytes)
{
static const char digits[] = "0123456789abcdef";
std::string result;
result.reserve(bytes.size() * 2);
for (Digest::const_iterator it = bytes.begin(); it != bytes.end(); ++it)
{
unsigned char c = *it;
result += digits[(c >> 4) & 0xF];
result += digits[c & 0xF];
}
return result;
}
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