Isis 3 Programmer Reference
md5wrapper.cpp
1 /*
2  * This is part of my wrapper-class to create
3  * a MD5 Hash from a string and a file.
4  *
5  * This code is completly free, you
6  * can copy it, modify it, or do
7  * what ever you want with it.
8  *
9  * Feb. 2005
10  * Benjamin Grüdelbach
11  */
12 
13 //----------------------------------------------------------------------
14 //basic includes
15 #include <fstream>
16 #include <iostream>
17 
18 //my includes
19 #include "md5wrapper.h"
20 #include "md5.h"
21 
22 //---------privates--------------------------
23 
24 /*
25  * internal hash function, calling
26  * the basic methods from md5.h
27  */
28 QString md5wrapper::hashit(QString text) {
29  MD5_CTX ctx;
30 
31  //init md5
32  md5->MD5Init(&ctx);
33  //update with our string
34  md5->MD5Update(&ctx,
35  (unsigned char *)text.toLatin1().data(),
36  text.length());
37 
38  //create the hash
39  unsigned char buff[16] = "";
40  md5->MD5Final((unsigned char *)buff, &ctx);
41 
42  //converte the hash to a string and return it
43  return convToString(buff);
44 }
45 
46 /*
47  * converts the numeric hash to
48  * a valid QString.
49  * (based on Jim Howard's code;
50  * http://www.codeproject.com/cpp/cmd5.asp)
51  */
52 QString md5wrapper::convToString(unsigned char *bytes) {
53  char asciihash[33];
54 
55  int p = 0;
56  for(int i = 0; i < 16; i++) {
57  ::sprintf(&asciihash[p], "%02x", bytes[i]);
58  p += 2;
59  }
60  asciihash[32] = '\0';
61  return QString(asciihash);
62 }
63 
64 //---------publics--------------------------
65 
66 //constructor
67 md5wrapper::md5wrapper() {
68  md5 = new MD5();
69 }
70 
71 
72 //destructor
73 md5wrapper::~md5wrapper() {
74  delete md5;
75 }
76 
77 /*
78  * creates a MD5 hash from
79  * "text" and returns it as
80  * string
81  */
82 QString md5wrapper::getHashFromString(QString text) {
83  return this->hashit(text);
84 }
85 
86 
87 /*
88  * creates a MD5 hash from
89  * a file specified in "filename" and
90  * returns it as string
91  * (based on Ronald L. Rivest's code
92  * from RFC1321 "The MD5 Message-Digest Algorithm")
93  */
94 QString md5wrapper::getHashFromFile(QString filename) {
95  FILE *file;
96  MD5_CTX context;
97 
98  int len;
99  unsigned char buffer[1024], digest[16];
100 
101  //open file
102  if((file = fopen(filename.toLatin1().data(), "rb")) == NULL) {
103  return "-1";
104  }
105 
106  //init md5
107  md5->MD5Init(&context);
108 
109  //read the filecontent
110  while((len = fread(buffer, 1, 1024, file))) {
111  md5->MD5Update(&context, buffer, len);
112  }
113 
114  /*
115  generate hash, close the file and return the
116  hash as QString
117  */
118  md5->MD5Final(digest, &context);
119  fclose(file);
120  return convToString(digest);
121 }
122 
123 /*
124  * EOF
125  */
MD5_CTX
Definition: md5.h:51
MD5
Definition: md5.h:60