00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023
00024
00025
00026
00027
00028
00029
00030
00031
00032
00033 #ifndef _HASH_UTIL_H
00034 #define _HASH_UTIL_H
00035
00036 #include <string>
00037 #include <openssl/sha.h>
00038 #include <openssl/md2.h>
00039 #include <openssl/evp.h>
00040 #include "Exception.h"
00041 #include "mstring.h"
00042
00048 typedef mace::string sha1;
00049 typedef mace::string md5;
00050
00056
00057 class HashUtil {
00058
00059 public:
00060 class Context {
00061 public:
00062 virtual ~Context();
00063 const mace::string& getHash();
00064 void update(const std::string& buf);
00065 void finalize();
00066
00067 protected:
00068 Context(const EVP_MD* md);
00069
00070 protected:
00071 const EVP_MD* md;
00072 EVP_MD_CTX* ctx;
00073 bool finalized;
00074 mace::string hash;
00075 };
00076
00077 class MD5Context : public Context {
00078 public:
00079 MD5Context();
00080 };
00081
00082 class Sha1Context : public Context {
00083 public:
00084 Sha1Context();
00085 };
00086
00087 public:
00088 static void computeSha1(const std::string& buf, sha1& r);
00089 static void computeSha1(int buf, sha1& r);
00090 static void computeSha1(const void* buf, size_t size, sha1& r);
00091 static void computeMD5(const void* buf, size_t size, md5& r);
00092
00100 static void computeFileSha1(const std::string& filePath, sha1& h, struct stat& sbuf,
00101 bool dostat = true,
00102 bool followlink = false) throw (FileException);
00111 static void computeFileMD5(const std::string& filePath, md5& h, struct stat& sbuf,
00112 bool dostat = true,
00113 bool followlink = false) throw (FileException);
00115 static size_t compute32bit(const std::string& buf) {
00116 static const hash_string hasher = hash_string();
00117 return hasher(buf);
00118 }
00119
00121 static std::string compute32bitHex(const std::string& buf) {
00122 size_t hash = compute32bit(buf);
00123 std::string h((const char*)&hash, sizeof(hash));
00124 std::string r = "";
00125 for (size_t i = 0; i < h.size(); i++) {
00126 char c[3];
00127 sprintf(c, "%02hhx", (unsigned char)h[i]);
00128 r += c;
00129 }
00130 return r;
00131 }
00132
00134 static void computeHash(const void* buf, size_t size, std::string& r,
00135 const EVP_MD* md);
00137 static void computeFileHash(const std::string& path, std::string& h,
00138 struct stat& sbuf, bool dostat, bool followlink,
00139 const EVP_MD* md) throw(FileException);
00140
00142 static EVP_MD_CTX* initCTX(const EVP_MD* md);
00144 static void finalizeCTX(EVP_MD_CTX* mdctx, std::string& r);
00146 static void freeCTX(EVP_MD_CTX* mdctx);
00147
00148 static const sha1& NULL_HASH;
00149
00150 protected:
00151 static sha1& nullHash();
00152
00153
00154 protected:
00155 static const size_t BLOCK_SIZE;
00156 static const size_t MAX_RETRY_COUNT;
00157 };
00158
00161 #endif // _HASH_UTIL_H