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
00030 #include <stdio.h>
00031 #include <stdlib.h>
00032 #include <stdbool.h>
00033 #include <string.h>
00034 #include <unistd.h>
00035 #include <fcntl.h>
00036 #include <sys/types.h>
00037 #include <sys/stat.h>
00038 #include "md5/md5_global.h"
00039 #include "md5/md5.h"
00040 #include "qDecoder.h"
00041 #include "qInternal.h"
00042
00056 unsigned char *qHashMd5(const void *data, size_t nbytes) {
00057 if(data == NULL) return NULL;
00058
00059 unsigned char *digest = (unsigned char*)malloc(sizeof(char) * (16 + 1));
00060 if (digest == NULL) return NULL;
00061
00062 MD5_CTX context;
00063 MD5Init(&context);
00064 MD5Update(&context, (unsigned char*)data, (unsigned int)nbytes);
00065 MD5Final(digest, &context);
00066 digest[16] = '\0';
00067
00068 return digest;
00069 }
00070
00085 char *qHashMd5Str(const void *data, size_t nbytes) {
00086 if(data == NULL) return NULL;
00087
00088 unsigned char *digest = qHashMd5(data, nbytes);
00089 if (digest == NULL) return NULL;
00090
00091 char *md5hex = (char*)malloc(sizeof(char) * (16 * 2 + 1));
00092 if (md5hex == NULL) return NULL;
00093
00094 int i;
00095 for (i = 0; i < 16; i++) {
00096 sprintf(md5hex + (i * 2), "%02x", digest[i]);
00097 }
00098 free(digest);
00099
00100 return md5hex;
00101 }
00102
00135 char *qHashMd5File(const char *filepath, size_t *nbytes) {
00136 int fd = open(filepath, O_RDONLY, 0);
00137 if (fd < 0) return NULL;
00138
00139 struct stat st;
00140 if (fstat(fd, &st) < 0) return NULL;
00141
00142 size_t size = st.st_size;
00143 if(nbytes != NULL) {
00144 if(*nbytes > size) *nbytes = size;
00145 else size = *nbytes;
00146 }
00147
00148 MD5_CTX context;
00149 MD5Init(&context);
00150 ssize_t retr = 0;
00151 unsigned char buf[256*1024], szDigest[16];
00152 while (size > 0) {
00153 if (size > sizeof(buf)) retr = read(fd, buf, sizeof(buf));
00154 else retr = read(fd, buf, size);
00155 if (retr < 0) break;
00156 MD5Update(&context, buf, retr);
00157 size -= retr;
00158 }
00159 close(fd);
00160 MD5Final(szDigest, &context);
00161
00162 if(nbytes != NULL) *nbytes -= size;
00163
00164 char *md5hex = (char*)malloc(sizeof(char) * (16 * 2 + 1));
00165 if (md5hex == NULL) return NULL;
00166
00167 int i;
00168 for (i = 0; i < 16; i++) {
00169 sprintf(md5hex + (i * 2), "%02x", szDigest[i]);
00170 }
00171
00172 return md5hex;
00173 }
00174
00194 unsigned int qHashFnv32(unsigned int max, const void *data, size_t nbytes) {
00195 if(data == NULL) return 0;
00196
00197 unsigned char *dp;
00198 unsigned int hval = (unsigned int)0x811c9dc5;
00199
00200 for (dp = (unsigned char *)data; *dp && nbytes > 0; dp++, nbytes--) {
00201 hval *= (unsigned int)0x01000193;
00202 hval ^= (unsigned int)*dp;
00203 }
00204 if (max > 0) hval %= max;
00205
00206 return hval;
00207 }