-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsha1hash.h
58 lines (45 loc) · 1.16 KB
/
sha1hash.h
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
#pragma once
#include <stdint.h>
#include "memblock.h"
#include <openssl/sha.h>
class Sha1CheckSum
{
public:
static const uint32_t HASH_LENGTH = SHA_DIGEST_LENGTH ;
bool operator<(const Sha1CheckSum& s) const
{
for(int i=0;i<HASH_LENGTH;++i)
if(bytes[i] < s.bytes[i])
return true ;
else if(bytes[i] > s.bytes[i])
return false ;
return false ;
}
explicit Sha1CheckSum(const unsigned char *data,size_t size)
{
SHA_CTX sha_ctx ;
if(HASH_LENGTH != 20)
throw std::runtime_error("Warning: can't compute Sha1Sum with sum size != 20") ;
SHA1_Init(&sha_ctx);
while(size > 512)
{
SHA1_Update(&sha_ctx, data, 512);
data = &data[512] ;
size -= 512 ;
}
SHA1_Update(&sha_ctx, data, size);
SHA1_Final(&bytes[0], &sha_ctx);
}
std::string toStdString() const
{
static const char outl[16] = { '0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F' } ;
std::string res(HASH_LENGTH*2,' ') ;
for(uint32_t j = 0; j < HASH_LENGTH; j++)
{
res[2*j ] = outl[ (bytes[j]>>4) ] ;
res[2*j+1] = outl[ bytes[j] & 0xf ] ;
}
return res ;
}
unsigned char bytes[HASH_LENGTH] ;
};