Statistics
| Branch: | Revision:

root / src / sim / chasher.cc @ e26d3d25

History | View | Annotate | Download (2.38 KB)

1 01873262 Georg Kunz
//==========================================================================
2
//   CHASHER.CC  - part of
3
//                     OMNeT++/OMNEST
4
//            Discrete System Simulation in C++
5
//
6
//  Author: Andras Varga
7
//
8
//==========================================================================
9
10
/*--------------------------------------------------------------*
11
  Copyright (C) 1992-2008 Andras Varga
12
  Copyright (C) 2006-2008 OpenSim Ltd.
13

14
  This file is distributed WITHOUT ANY WARRANTY. See the file
15
  `license' for details on this and other legal matters.
16
*--------------------------------------------------------------*/
17
18
#include "chasher.h"
19
20
USING_NAMESPACE
21
22
23
void cHasher::add(const char *p, size_t length)
24
{
25
    // add the bulk in 4-byte chunks
26
    size_t lengthmod4 = length&~3U;
27
    size_t i;
28
    for (i=0; i<lengthmod4; i+=4)
29
        merge((uint32)(p[i] | (p[i+1]<<8) | (p[i+2]<<16) | (p[i+3]<<24)));
30
31
    // add the 1, 2 or 3 bytes left
32
    switch (length-i)
33
    {
34
        case 0: break;
35
        case 1: merge((uint32)(p[i])); break;
36
        case 2: merge((uint32)(p[i] | (p[i+1]<<8))); break;
37
        case 3: merge((uint32)(p[i] | (p[i+1]<<8) | (p[i+2]<<16))); break;
38
        default: ASSERT(false);
39
    }
40
}
41
42
uint32 cHasher::parse(const char *fingerprint) const
43
{
44
    // remove spaces, hyphens and colons before parsing
45
    std::string s;
46
    for (const char *p = fingerprint; *p; p++)
47
        if (*p!=' ' && *p!='-' && *p!=':')
48
            s += *p;
49
50
    // parse
51
    char *e;
52
    unsigned long d = strtoul(s.c_str(), &e, 16);
53
    uint32 hash = (uint32)d;
54
    if (*e || hash!=d)
55
        throw cRuntimeError("Error verifying fingerprint: invalid fingerprint text \"%s\"", fingerprint);
56
    return hash;
57
}
58
59
bool cHasher::equals(const char *fingerprint) const
60
{
61
    uint32 hash = parse(fingerprint);
62
    return getHash()==hash;
63
}
64
65
std::string cHasher::str() const
66
{
67
    char buf[32];
68
    sprintf(buf, "%08x", getHash());
69
    std::string str = buf;
70
    str.insert(str.length()-4, "-");
71
    return str;
72
}
73
74
75
/* XXX to test case
76

77
int main(int argc, char **argv)
78
{
79
#define PRINT printf("%x\n", h.getHash())
80
    cHasher h;
81
    h.add(1); PRINT;
82
    h.add(4); PRINT;
83
    h.add(1); PRINT;
84
    h.add(0xffffffff); PRINT;
85
    h.add(0); h.add(0); h.add(0); h.add(0); PRINT;
86

87
    h.reset();
88
    h.add("alma"); PRINT;
89

90
    h.reset();
91
    h.add("almaalma"); PRINT;
92

93
    h.reset();
94
    h.add("almaalmaalma"); PRINT;
95
    return 0;
96
}
97
*/