]> cygwin.com Git - cygwin-apps/setup.git/blob - csu_util/MD5Sum.cc
2004-11-22 Max Bowsher <maxb@ukf.net>
[cygwin-apps/setup.git] / csu_util / MD5Sum.cc
1 /*
2 * Copyright (c) 2004 Max Bowsher
3 *
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
8 *
9 * A copy of the GNU General Public License can be found at
10 * http://www.gnu.org/
11 *
12 * Written by Max Bowsher
13 */
14
15 #include "MD5Sum.h"
16 #include <stdexcept>
17
18 namespace libmd5_rfc {
19 #include "../libmd5-rfc/md5.h"
20 }
21
22 MD5Sum::MD5Sum(const MD5Sum& source)
23 {
24 *this = source;
25 }
26
27 MD5Sum&
28 MD5Sum::operator= (const MD5Sum& source)
29 {
30 state = source.state;
31 memcpy(digest, source.digest, sizeof(digest));
32 internalData = 0;
33 if (source.internalData)
34 {
35 internalData = new libmd5_rfc::md5_state_s;
36 *internalData = *(source.internalData);
37 }
38 return *this;
39 }
40
41 MD5Sum::~MD5Sum()
42 {
43 if (internalData) delete internalData;
44 }
45
46 void
47 MD5Sum::set(const unsigned char digest[16])
48 {
49 memcpy(this->digest, digest, sizeof(this->digest));
50 state = Set;
51 if (internalData) delete internalData;
52 }
53
54 void
55 MD5Sum::begin()
56 {
57 if (internalData) delete internalData;
58 internalData = new libmd5_rfc::md5_state_s;
59 state = Accumulating;
60 libmd5_rfc::md5_init(internalData);
61 }
62
63 void
64 MD5Sum::append(const unsigned char* data, int nbytes)
65 {
66 if (!internalData)
67 throw new std::logic_error("MD5Sum::append() called on an object not "
68 "in the 'Accumulating' state");
69 libmd5_rfc::md5_append(internalData, data, nbytes);
70 }
71
72 void
73 MD5Sum::finish()
74 {
75 if (!internalData)
76 throw new std::logic_error("MD5Sum::finish() called on an object not "
77 "in the 'Accumulating' state");
78 libmd5_rfc::md5_finish(internalData, digest);
79 state = Set;
80 delete internalData; internalData = 0;
81 }
82
83 MD5Sum::operator std::string() const
84 {
85 char hexdigest[33];
86 hexdigest[32] = '\0';
87
88 for (int i = 0; i < 16; ++i)
89 {
90 int hexdigit = 2 * i;
91 char tmp;
92
93 tmp = digest[i] >> 4;
94 hexdigest[hexdigit] = (tmp < 10) ? (tmp + '0') : (tmp + 'a' - 10);
95
96 tmp = digest[i] & 0x0f;
97 hexdigest[hexdigit + 1] = (tmp < 10) ? (tmp + '0') : (tmp + 'a' - 10);
98 }
99
100 return std::string(hexdigest);
101 }
102
103 bool
104 MD5Sum::operator == (const MD5Sum& other) const
105 {
106 if (state != Set || other.state != Set)
107 throw new std::logic_error("MD5Sum comparison attempted on operands not "
108 "in the 'Set' state");
109 return (memcmp(digest, other.digest, sizeof(digest)) == 0);
110 }
This page took 0.038636 seconds and 5 git commands to generate.