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
85
86
87
88
89
90
91
92
93
94
95
96
97
|
/*
* Copyright (c) 2012 Kevin Smith
* Licensed under the GNU General Public License v3.
* See Documentation/Licenses/GPLv3.txt for more information.
*/
//http://msdn.microsoft.com/en-us/library/aa379908.aspx
#include <Swiften/StringCodecs/SHA1_Windows.h>
namespace Swift {
SHA1::SHA1() : hCryptProv(NULL), hHash(NULL) {
bool hasContext = CryptAcquireContext(&hCryptProv, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT);
if (!hasContext) {
// DWORD error = GetLastError();
// switch (error) {
// std::cerr << (long)error << std::endl;
// }
// assert(false);
hCryptProv = NULL;
}
if (!CryptCreateHash(hCryptProv, CALG_SHA1, 0, 0, &hHash)) {
hHash = NULL;
}
}
SHA1::~SHA1() {
if(hHash) {
CryptDestroyHash(hHash);
}
if(hCryptProv) {
CryptReleaseContext(hCryptProv,0);
}
}
SHA1& SHA1::update(const std::vector<unsigned char>& data) {
return update(vecptr(data), data.size());
}
SHA1& SHA1::update(const unsigned char* data, size_t dataSize) {
if (!hHash || !hCryptProv) {
return *this;
}
BYTE* byteData = (BYTE *)data;
DWORD dataLength = dataSize;
bool hasHashed = CryptHashData(hHash, byteData, dataLength, 0);
// if (!hasHashed) {
// DWORD error = GetLastError();
// switch (error) {
// std::cerr << (long)error << std::endl;
// }
// assert(false);
// }
return *this;
}
std::vector<unsigned char> SHA1::getHash() const {
if (!hHash || !hCryptProv) {
return std::vector<unsigned char>();
}
std::vector<unsigned char> result;
DWORD hashLength = sizeof(DWORD);
DWORD hashSize;
CryptGetHashParam(hHash, HP_HASHSIZE, (BYTE*)&hashSize, &hashLength, 0);
result.resize(static_cast<size_t>(hashSize));
bool hasHashed = CryptGetHashParam(hHash, HP_HASHVAL, (BYTE*)vecptr(result), &hashSize, 0);
if (!hasHashed) {
// DWORD error = GetLastError();
// switch (error) {
// std::cerr << (long)error << std::endl;
// }
// assert(false);
return std::vector<unsigned char>();
}
result.resize(static_cast<size_t>(hashSize));
return result;
}
ByteArray SHA1::getHash(const ByteArray& data) {
SHA1 hash;
hash.update(vecptr(data), data.size());
return hash.getHash();
}
ByteArray SHA1::getHash(const SafeByteArray& data) {
SHA1 hash;
hash.update(vecptr(data), data.size());
return hash.getHash();
}
}
|