33#include < md5.h>
44#include < iostream>
55#include < cstring>
6+ #include < fstream>
67
78// ---------------------------------------------------------------------
89// WsjcppHashes
@@ -27,6 +28,35 @@ std::string WsjcppHashes::getMd5ByString(const std::string &sStr) {
2728 return md5.hexdigest ();
2829}
2930
31+ std::string WsjcppHashes::getMd5ByFile (const std::string &sFilename ) {
32+ std::ifstream f (sFilename , std::ifstream::binary);
33+ if (!f) {
34+ return " Could not open file" ;
35+ }
36+
37+ // get length of file:
38+ f.seekg (0 , f.end );
39+ int nBufferSize = f.tellg ();
40+ f.seekg (0 , f.beg );
41+
42+ char *pBuffer = new char [nBufferSize];
43+
44+ // read data as a block:
45+ f.read (pBuffer, nBufferSize);
46+ if (!f) {
47+ delete[] pBuffer;
48+ f.close ();
49+ return " Could not read file. Only " + std::to_string (f.gcount ()) + " could be read" ;
50+ }
51+ f.close ();
52+
53+
54+ MD5 md5;
55+ md5.update (pBuffer, nBufferSize);
56+ md5.finalize ();
57+ return md5.hexdigest ();
58+ }
59+
3060std::string WsjcppHashes::getSha1ByString (const std::string &sStr ) {
3161 char hexstring[41 ]; // 40 chars + a zero
3262 std::memset (hexstring, 0 , sizeof hexstring);
@@ -37,11 +67,33 @@ std::string WsjcppHashes::getSha1ByString(const std::string &sStr) {
3767 return std::string (hexstring);
3868}
3969
40- std::string WsjcppHashes::getMd5ByFile (const std::string &sFilename ) {
41- return " todo" ;
42- }
43-
4470std::string WsjcppHashes::getSha1ByFile (const std::string &sFilename ) {
45- return " todo" ;
71+ std::ifstream f (sFilename , std::ifstream::binary);
72+ if (!f) {
73+ return " Could not open file" ;
74+ }
75+
76+ // get length of file:
77+ f.seekg (0 , f.end );
78+ int nBufferSize = f.tellg ();
79+ f.seekg (0 , f.beg );
80+
81+ char *pBuffer = new char [nBufferSize];
82+
83+ // read data as a block:
84+ f.read (pBuffer, nBufferSize);
85+ if (!f) {
86+ delete[] pBuffer;
87+ f.close ();
88+ return " Could not read file. Only " + std::to_string (f.gcount ()) + " could be read" ;
89+ }
90+ f.close ();
91+
92+ char hexstring[41 ]; // 40 chars + a zero
93+ std::memset (hexstring, 0 , sizeof hexstring);
94+ unsigned char hash[20 ];
95+ sha1::calc (pBuffer, nBufferSize, hash);
96+ sha1::toHexString (hash, hexstring);
97+ return std::string (hexstring);
4698}
4799
0 commit comments