/* * The default hash function, using md5 algorithm * @instr: input string */ size_t _defaultBloomHash(const char *instr) { int i; size_t hash = 0; unsigned char digest[16]; md5_state_t md5state; md5_init(&md5state); md5_append(&md5state, (const unsigned char *)instr, strlen(instr)); md5_finish(&md5state, digest); /* use successive 4-bytes from hash as numbers */ for(i = 0; i < 4; i++) { hash += ((size_t)(digest[i*4 + 3]&0xFF) << 24) | ((size_t)(digest[i*4 + 2]&0xFF) << 16) | ((size_t)(digest[i*4 + 1]&0xFF) << 8) | ((size_t)(digest[i*4 + 0]&0xFF)); } return hash; }
string Utilities::GenerateMD5( string my_string ) { #define MD5_LENGTH 16 md5_state_t *md5_state = new md5_state_t(); unsigned char *md5_digest = new unsigned char[MD5_LENGTH]; md5_init(md5_state); md5_append(md5_state, (const unsigned char *)my_string.c_str(), my_string.size() ); md5_finish(md5_state, md5_digest); char md5String[(MD5_LENGTH * 2) + 1]; int di = 0; for (di = 0; di < MD5_LENGTH; ++di) { sprintf(md5String + (di * 2), "%02x", md5_digest[di]); } *(md5String + (di * 2)) = '\0'; delete [] md5_state; delete [] md5_digest; return string( md5String ); }
void md5_finish(md5_state_t *pms, md5_byte_t digest[16]) { static const md5_byte_t pad[64] = { 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; md5_byte_t data[8]; int i; /* Save the length before padding. */ for (i = 0; i < 8; ++i) data[i] = (md5_byte_t)(pms->count[i >> 2] >> ((i & 3) << 3)); /* Pad to 56 bytes mod 64. */ md5_append(pms, pad, ((55 - (pms->count[0] >> 3)) & 63) + 1); /* Append the length. */ md5_append(pms, data, 8); for (i = 0; i < 16; ++i) digest[i] = (md5_byte_t)(pms->abcd[i >> 2] >> ((i & 3) << 3)); }
BSONObj md5sumFile(const BSONObj& args, void* data) { BSONElement e = singleArg(args); stringstream ss; FILE* f = fopen(e.valuestrsafe(), "rb"); uassert(CANT_OPEN_FILE, "couldn't open file", f ); ON_BLOCK_EXIT(fclose, f); md5digest d; md5_state_t st; md5_init(&st); enum {BUFLEN = 4*1024}; char buffer[BUFLEN]; int bytes_read; while( (bytes_read = fread(buffer, 1, BUFLEN, f)) ) { md5_append( &st , (const md5_byte_t*)(buffer) , bytes_read ); } md5_finish(&st, d); return BSON( "" << digestToString( d ) ); }
md5_byte_t *getcrcsignatureuntil(char *filename, off_t max_read) { off_t fsize; off_t toread; md5_state_t state; static md5_byte_t digest[MD5_DIGEST_LENGTH]; static md5_byte_t chunk[CHUNK_SIZE]; FILE *file; md5_init(&state); fsize = filesize(filename); if (max_read != 0 && fsize > max_read) fsize = max_read; file = fopen(filename, "rb"); if (file == NULL) { errormsg("error opening file %s\n", filename); return NULL; } while (fsize > 0) { toread = (fsize >= CHUNK_SIZE) ? CHUNK_SIZE : fsize; if (fread(chunk, toread, 1, file) != 1) { errormsg("error reading from file %s\n", filename); fclose(file); return NULL; } md5_append(&state, chunk, toread); fsize -= toread; } md5_finish(&state, digest); fclose(file); return digest; }
static void send_auth(char *username, char *password) { struct mt_packet data; unsigned short width = 0; unsigned short height = 0; char *terminal = getenv("TERM"); char md5data[100]; unsigned char md5sum[17]; int plen; md5_state_t state; /* Concat string of 0 + password + encryptionkey */ md5data[0] = 0; strncpy(md5data + 1, password, 82); md5data[83] = '\0'; memcpy(md5data + 1 + strlen(password), encryptionkey, 16); /* Generate md5 sum of md5data with a leading 0 */ md5_init(&state); md5_append(&state, (const md5_byte_t *)md5data, strlen(password) + 17); md5_finish(&state, (md5_byte_t *)md5sum + 1); md5sum[0] = 0; /* Send combined packet to server */ init_packet(&data, MT_PTYPE_DATA, srcmac, dstmac, sessionkey, outcounter); plen = add_control_packet(&data, MT_CPTYPE_PASSWORD, md5sum, 17); plen += add_control_packet(&data, MT_CPTYPE_USERNAME, username, strlen(username)); plen += add_control_packet(&data, MT_CPTYPE_TERM_TYPE, terminal, strlen(terminal)); if (is_a_tty && get_terminal_size(&width, &height) != -1) { width = htole16(width); height = htole16(height); plen += add_control_packet(&data, MT_CPTYPE_TERM_WIDTH, &width, 2); plen += add_control_packet(&data, MT_CPTYPE_TERM_HEIGHT, &height, 2); } outcounter += plen; /* TODO: handle result */ send_udp(&data, 1); }
bool NormalStringToMD5String16(char szDestMD5String[64], const char cszSrcString[]) { bool bResult = false; md5_state_t md5_state; unsigned char MD5Value[16]; int nSrcStringLen = 0; if (!szDestMD5String) goto Exit0; szDestMD5String[0] = '\0'; if (!cszSrcString) goto Exit0; nSrcStringLen = strlen(cszSrcString); if (!nSrcStringLen) goto Exit0; md5_init(&md5_state); md5_append(&md5_state, (unsigned char *)cszSrcString, nSrcStringLen); md5_finish(&md5_state, MD5Value); sprintf( szDestMD5String, "%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X", MD5Value[ 0], MD5Value[ 1], MD5Value[ 2], MD5Value[ 3], MD5Value[ 4], MD5Value[ 5], MD5Value[ 6], MD5Value[ 7], MD5Value[ 8], MD5Value[ 9], MD5Value[10], MD5Value[11], MD5Value[12], MD5Value[13], MD5Value[14], MD5Value[15] ); bResult = true; Exit0: return bResult; }
static int md5_getHash(const char *path, char *szpHash) { FF_T_UINT8 readBuf[8192]; FILE *pFile; //FF_ERROR ffError; int len; md5_state_t state; md5_byte_t digest[16]; char temp[3]; int di; //pFile = FF_Open(pEnv->pIoman, path, FF_MODE_READ, &ffError); pFile = fopen(path, "rb"); if(pFile) { md5_init(&state); do { //len = FF_Read(pFile, 1, 8192, readBuf); len = fread(readBuf, 1, 8192, pFile); md5_append(&state, (const md5_byte_t *)readBuf, len); } while(len); md5_finish(&state, digest); strcpy(szpHash, ""); for (di = 0; di < 16; ++di) { sprintf(temp, "%02x", digest[di]); strcat(szpHash, temp); } //FF_Close(pFile); fclose(pFile); return 0; } return -1; }
int file_input_stream_test() { hbc::file_input_stream input_stream("tinyxml/utf8test.xml"); int total = 0; unsigned char buffer[690]; int read; while ((read = input_stream.read(buffer+total, 256)) != -1) { total += read; } printf("actual[%i], expected[690]\n", total); md5_state_t state; md5_byte_t digest[16]; md5_init(&state); md5_append(&state, (const md5_byte_t*)buffer, 690); md5_finish(&state, digest); char hex_output[33]; hex_output[32] = 0; for (int i = 0; i < 16; i++) { sprintf(hex_output+(i*2), "%02x", digest[i]); } printf("actual[%s], expected[60125088e7992e07e224685e1c9fca6f]\n", hex_output); if (strcmp(hex_output, "60125088e7992e07e224685e1c9fca6f") != 0) { throw -1; } return 0; }
std::string MD5File(std::string fileName) { FILE* targetFile; // Open source and target file errno = 0; targetFile = fopen(fileName.c_str(), "rb"); if (errno != 0) { ZPatcher::Log(ZPatcher::LOG_FATAL, "Error opening file \"%s\" to calculate MD5 Hash: %s", fileName.c_str(), strerror(errno)); return false; } // Buffer to read the file const uint64_t buffer_size = 1 << 16; unsigned char readBuffer[buffer_size]; size_t bytesRead; // MD5 hashing utilities md5_state_t state; md5_byte_t digest[16]; char hex_output[16 * 2 + 1]; // Read file and generate MD5 hash md5_init(&state); while (bytesRead = fread(readBuffer, 1, buffer_size, targetFile)) md5_append(&state, (const md5_byte_t*)readBuffer, static_cast<int>(bytesRead)); fclose(targetFile); // Close the file. It won't be needed anymore. md5_finish(&state, digest); for (int di = 0; di < 16; ++di) snprintf(hex_output + di * 2, 3, "%02x", digest[di]); // Return MD5 hash return hex_output; }
int md5check (const char *const inputString, const char *const hash) { md5_state_t state; md5_byte_t digest[16]; char hex_output[33]; md5_init(&state); md5_append(&state, (const md5_byte_t *)inputString, (int)strlen(inputString)); md5_finish(&state, digest); for (int di = 0; di<16; ++di) { sprintf(hex_output + di * 2, "%02x", digest[di]); //printf("MD5 (\"%s\") = ", TestString); //puts(hex_output); } if (strcmp(hex_output, hash) == 0) { return 1; } else return 0; }
std::string RAGenerateMD5( const BYTE* pRawData, size_t nDataLen ) { static char buffer[33]; md5_state_t pms; md5_byte_t digest[16]; static_assert( sizeof( md5_byte_t ) == sizeof( BYTE ), "Must be equivalent for the MD5 to work!" ); md5_init( &pms ); md5_append( &pms, static_cast<const md5_byte_t*>( pRawData ), nDataLen ); md5_finish( &pms, digest ); memset( buffer, 0, MD5_STRING_LEN+1 ); sprintf_s( buffer, MD5_STRING_LEN + 1, "%02x%02x%02x%02x%02x%02x%02x%02x" "%02x%02x%02x%02x%02x%02x%02x%02x", digest[ 0 ], digest[ 1 ], digest[ 2 ], digest[ 3 ], digest[ 4 ], digest[ 5 ], digest[ 6 ], digest[ 7 ], digest[ 8 ], digest[ 9 ], digest[ 10 ], digest[ 11 ], digest[ 12 ], digest[ 13 ], digest[ 14 ], digest[ 15 ] ); return buffer; // Implicit promotion to std::string }
int md5_generate(char *filename, char text_digest[MD5_TEXT_DIGEST_SIZE + 1]) { int fd = open(filename, O_RDONLY); if(fd == -1) { return -1; } md5_state_t md5_state; md5_init(&md5_state); char buf[4096]; int amt = 0; while((amt = read(fd, buf, 4096)) > 0) { md5_append(&md5_state, (md5_byte_t *) buf, amt); } md5_finish_text(&md5_state, text_digest, 1); text_digest[MD5_TEXT_DIGEST_SIZE] = '\0'; return 0; }
int tst_md5(FILE *ifile, md5_byte_t *digest) { char *file_data; unsigned int len; md5_state_t state; // allocate source buffer fseek(ifile, 0, SEEK_END); len = ftell(ifile); fseek(ifile, 0, SEEK_SET); file_data = (char*) malloc(len); // read file len = fread(file_data, 1, len, ifile); // compute md5 md5_init(&state); md5_append(&state, (const md5_byte_t *)file_data, len); md5_finish(&state, digest); return 0; }
int alipay_precreatebak(char* precr, int* len) { char encrypt[1024]; md5_state_t state; md5_byte_t digest[16]; char hex_output[16*2 + 1]; int di; //without goods_detail //sprintf(encrypt,"_input_charset=%s&out_trade_no=%s&partner=%s&product_code=%s&service=%s&subject=%s&total_fee=%s%s",_input_charset, out_trade_no,partner,product_code,service,subject,total_fee,key); //with goods_detail //sprintf(encrypt,"_input_charset=%s&goods_detail=%s&out_trade_no=%s&partner=%s&product_code=%s&service=%s&subject=%s&total_fee=%s%s",_input_charset, goods_detail, out_trade_no,partner,product_code,service,subject,total_fee,key); //with royalty sprintf(encrypt,"_input_charset=%s&goods_detail=%s&out_trade_no=%s&partner=%s&product_code=%s&royalty_parameters=%s&service=%s&subject=%s&total_fee=%s%s",_input_charset, goods_detail, out_trade_no,partner,product_code,royalty_parameters,service,subject,total_fee,key); printf("\nMD5 input:encrypt=\n%s", encrypt); md5_init(&state); md5_append(&state, (const md5_byte_t *)encrypt, strlen(encrypt)); md5_finish(&state, digest); for (di = 0; di < 16; ++di) sprintf(hex_output + di * 2, "%02x", digest[di]); printf("\nencrypt output:\n"); puts(hex_output); printf("\nalipay.acquire.precreate:\n"); char https[1024*3]; char encrypt1wokey[1024*3]; //without goods_detail //sprintf(encrypt1wokey,"_input_charset=%s&out_trade_no=%s&partner=%s&product_code=%s&service=%s&subject=%s&total_fee=%s",_input_charset,out_trade_no,partner,product_code,service,subject,total_fee); //with goods_detail //sprintf(encrypt1wokey,"_input_charset=%s&goods_detail=%s&out_trade_no=%s&partner=%s&product_code=%s&service=%s&subject=%s&total_fee=%s",_input_charset,goods_detail,out_trade_no,partner,product_code,service,subject,total_fee); sprintf(encrypt1wokey,"_input_charset=%s&goods_detail=%s&out_trade_no=%s&partner=%s&product_code=%s&royalty_parameters=%s&service=%s&subject=%s&total_fee=%s",_input_charset,goods_detail,out_trade_no,partner,product_code,royalty_parameters,service,subject,total_fee); *len = sprintf(https,"https://mapi.alipay.com/gateway.do?%s&sign_type=MD5&sign=%s",encrypt1wokey,hex_output); puts(https); memset(precr, 0, *len+1); memcpy(precr, https, *len); return *len; }
/* multi query */ int alipay_query(char* precr, int* len, char* str_imsi) { char https[1024]; char encrypt[1024]; char encrypt1wokey[1024]; md5_state_t state; md5_byte_t digest[16]; char hex_output[16*2 + 1]; int di; if(time_mark[0]=='\0') *len = sprintf(encrypt,"IMSI=%s&time_mark=%s#%s", str_imsi, str_timemark, jfkey); else *len = sprintf(encrypt,"IMSI=%s&time_mark=%s#%s", str_imsi, time_mark, jfkey); printf("\nMD5 input:encrypt=%s", encrypt); md5_init(&state); md5_append(&state, (const md5_byte_t *)encrypt, strlen(encrypt)); md5_finish(&state, digest); for (di = 0; di < 16; ++di) sprintf(hex_output + di * 2, "%02x", digest[di]); printf("\nencrypt output:"); puts(hex_output); if(time_mark[0]=='\0') *len = sprintf(encrypt1wokey,"IMSI=%s&time_mark=%s", str_imsi, str_timemark); else *len = sprintf(encrypt1wokey,"IMSI=%s&time_mark=%s", str_imsi, time_mark); //*len = sprintf(https,"http://192.168.1.104:8180/qrcode/preorder/?IMSI=123456789012345&serial_number=12&total_fee=0.01&subject=ccc&order_time=2014-08-0211:21:20"); //*len = sprintf(https,"http://%s:%d/qrcode/preorder/?IMSI=%s&serial_number=%d&total_fee=%d&subject=%s&order_time=%s", jfserver, portnumber, IMSI, serial_number, jftotal_fee, jfsubject, order_time); *len = sprintf(https,"http://%s:%d/qrcode/query/?%s&sign=%s",jfserver, portnumber, encrypt1wokey, hex_output); puts(https); memset(precr, 0, *len+1); memcpy(precr, https, *len); return *len; }
int __cdecl main() { static const char *const test[7] = { "", /*d41d8cd98f00b204e9800998ecf8427e*/ "a", /*0cc175b9c0f1b6a831c399e269772661*/ "abc", /*900150983cd24fb0d6963f7d28e17f72*/ "message digest", /*f96b697d7cb7938d525a2f31aaf161d0*/ "abcdefghijklmnopqrstuvwxyz", /*c3fcd3d76192e4007dfb496cca67e13b*/ "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", /*d174ab98d277d9f5a5611c2c9f419d9f*/ "12345678901234567890123456789012345678901234567890123456789012345678901234567890" /*57edf4a22be3c955ac49da2e2107b67a*/ }; int i; for (i = 0; i < 7; ++i) { md5_state_t state; md5_byte_t digest[16]; md5_init(&state); md5_append(&state, (const md5_byte_t *)test[i], (int) strlen(test[i])); md5_finish(&state, digest); printf("MD5 (\"%s\") = ", test[i]); for (int di = 0; di < 16; ++di) { printf("%02x", digest[di]); } printf("\n"); MD5Digest d; d.update((const md5_byte_t *)test[i], strlen(test[i])); printf("MD5*(\"%s\") = ", test[i]); for (int di = 0; di < 16; ++di) { printf("%02x", d.digest()[di]); } printf("\n"); } return 0; }
//---------------------------------------------------------------- void FileToMd5(HANDLE Hfic, char *md5) { //ouverture du fichier en lecture partagé md5[0]=0; DWORD taille_fic = GetFileSize(Hfic,NULL); if (taille_fic>0 && taille_fic!=INVALID_FILE_SIZE) { unsigned char *buffer = (LPBYTE)HeapAlloc(GetProcessHeap(), 0, sizeof(unsigned char*)*taille_fic+1); if (buffer == NULL)return; //lecture du fichier DWORD copiee, position = 0, increm = 0; if (taille_fic > DIXM)increm = DIXM; else increm = taille_fic; BOOL read = TRUE; while (position<taille_fic && increm!=0 && read)//gestion pour éviter les bug de sync permet une ouverture de fichiers énormes ^^ { copiee = 0; read =ReadFile(Hfic, buffer+position, increm,&copiee,0); position +=copiee; if (taille_fic-position < increm)increm = taille_fic-position ; } //traitement en MD5 md5_state_t state; md5_byte_t digest[16]; md5_init(&state); md5_append(&state,(const md5_byte_t *)buffer,taille_fic); md5_finish(&state,digest); //génération du md5 en chaine unsigned short i; for(i=0;i<16;i++)snprintf(md5+i*2,3,"%02x",digest[i]); md5[32]=0; HeapFree(GetProcessHeap(), 0,buffer); } }
int md5_file(const char* path, char* output, double& nbytes) { unsigned char buf[4096]; unsigned char binout[16]; md5_state_t state; int i, n; nbytes = 0; #ifndef _USING_FCGI_ FILE *f = fopen(path, "rb"); #else FILE *f = FCGI::fopen(path, "rb"); #endif if (!f) { fprintf(stderr, "md5_file: can't open %s\n", path); #ifndef _USING_FCGI_ std::perror("md5_file"); #else FCGI::perror("md5_file"); #endif return ERR_FOPEN; } md5_init(&state); while (1) { n = (int)fread(buf, 1, 4096, f); if (n<=0) break; nbytes += n; md5_append(&state, buf, n); } md5_finish(&state, binout); for (i=0; i<16; i++) { sprintf(output+2*i, "%02x", binout[i]); } output[32] = 0; fclose(f); return 0; }
void Toolbox::ComputeMD5(std::string& result, const void* data, size_t length) { md5_state_s state; md5_init(&state); if (length > 0) { md5_append(&state, reinterpret_cast<const md5_byte_t*>(data), static_cast<int>(length)); } md5_byte_t actualHash[16]; md5_finish(&state, actualHash); result.resize(32); for (unsigned int i = 0; i < 16; i++) { result[2 * i] = GetHexadecimalCharacter(actualHash[i] / 16); result[2 * i + 1] = GetHexadecimalCharacter(actualHash[i] % 16); } }
/* TODO: replace this with a faster hash function? */ char *etag_new(const char *p, size_t sz) { md5_byte_t buf[16]; char *etag = calloc(34 + 1, 1); int i; if(!etag) return NULL; md5_state_t pms; md5_init(&pms); md5_append(&pms, (const md5_byte_t *)p, (int)sz); md5_finish(&pms, buf); for(i = 0; i < 16; ++i) { sprintf(etag + 1 + 2*i, "%.2x", (unsigned char)buf[i]); } etag[0] = '"'; etag[33] = '"'; return etag; }
/* Encrypt `src' of length `len' and store the result in `dest'. If the * resulting string would be longer than `size', return -1 and leave `dest' * unchanged; else return 0. */ static int myencrypt(const char *src, int len, char *dest, int size) { #ifdef ENCRYPT_MD5 md5_state_t context; char digest[33]; char dest2[16]; int i; if (size < 32) return -1; memset(&context, 0, sizeof(context)); memset(&digest, 0, sizeof(digest)); md5_init(&context); md5_append(&context, (unsigned const char *) src, (size_t) len); md5_finish(&context, (unsigned char *) digest); for (i = 0; i < 32; i += 2) dest2[i / 2] = XTOI(digest[i]) << 4 | XTOI(digest[i + 1]); /* convert to hex, skipping last 8 bytes (constant) -- jilles */ strcpy(dest, "$ircservices$"); for (i = 0; i <= 7; i++) sprintf(dest + 13 + 2 * i, "%02x", 255 & dest2[i]); return 0; #else return -1; /* unknown encryption algorithm */ #endif }
char* calculateMD5(const void* token, int len, char* wdigest) { //algo for md5 digest char dig [18]; md5_state_t state; md5_byte_t digest[16]; int di; char* ret = NULL; md5_init (&state); md5_append(&state, (const md5_byte_t *)token, len); md5_finish(&state, digest); for (di = 0; di < 16; ++di) { sprintf(dig + di, "%c", digest[di]); } if (wdigest == NULL) { ret = new char[16]; memcpy(ret, dig, 16); return ret; } else { memcpy(wdigest, dig, 16); return NULL; } }
static gboolean is_duplicate_rel_time(guint8* fd, guint32 len, const nstime_t *current) { int i; md5_state_t ms; cur_dup_entry++; if (cur_dup_entry >= dup_window) cur_dup_entry = 0; /* Calculate our digest */ md5_init(&ms); md5_append(&ms, fd, len); md5_finish(&ms, fd_hash[cur_dup_entry].digest); fd_hash[cur_dup_entry].len = len; fd_hash[cur_dup_entry].time.secs = current->secs; fd_hash[cur_dup_entry].time.nsecs = current->nsecs; /* * Look for relative time related duplicates. * This is hopefully a reasonably efficient mechanism for * finding duplicates by rel time in the fd_hash[] cache. * We check starting from the most recently added hash * entries and work backwards towards older packets. * This approach allows the dup test to be terminated * when the relative time of a cached entry is found to * be beyond the dup time window. * * Of course this assumes that the input trace file is * "well-formed" in the sense that the packet timestamps are * in strict chronologically increasing order (which is NOT * always the case!!). * * The fd_hash[] table was deliberatly created large (1,000,000). * Looking for time related duplicates in large trace files with * non-fractional dup time window values can potentially take * a long time to complete. */ for (i = cur_dup_entry - 1;; i--) { nstime_t delta; int cmp; if (i < 0) { i = dup_window - 1; } if (i == cur_dup_entry) { /* * We've decremented back to where we started. * Check no more! */ break; } if (nstime_is_unset(&(fd_hash[i].time))) { /* * We've decremented to an unused fd_hash[] entry. * Check no more! */ break; } nstime_delta(&delta, current, &fd_hash[i].time); if(delta.secs < 0 || delta.nsecs < 0) { /* * A negative delta implies that the current packet * has an absolute timestamp less than the cached packet * that it is being compared to. This is NOT a normal * situation since trace files usually have packets in * chronological order (oldest to newest). * * There are several possible ways to deal with this: * 1. 'continue' dup checking with the next cached frame. * 2. 'break' from looking for a duplicate of the current frame. * 3. Take the absolute value of the delta and see if that * falls within the specifed dup time window. * * Currently this code does option 1. But it would pretty * easy to add yet-another-editcap-option to select one of * the other behaviors for dealing with out-of-sequence * packets. */ continue; } cmp = nstime_cmp(&delta, &relative_time_window); if(cmp > 0) { /* * The delta time indicates that we are now looking at * cached packets beyond the specified dup time window. * Check no more! */ break; } else if (fd_hash[i].len == fd_hash[cur_dup_entry].len && memcmp(fd_hash[i].digest, fd_hash[cur_dup_entry].digest, 16) == 0) { return TRUE; } } return FALSE; }
static gchar * sasl_md5_prepare_response (LmSASL *sasl, GHashTable *challenge) { GString *response; const gchar *realm, *nonce; gchar *a1, *a1h, *a2, *a2h, *kd, *kdh; gchar *cnonce = NULL; gchar *tmp; md5_byte_t digest_md5[16]; md5_state_t md5_calc; gsize len; response = g_string_new (""); if (sasl->username == NULL || sasl->password == NULL) { g_log (LM_LOG_DOMAIN, LM_LOG_LEVEL_SASL, "%s: no username or password provided", G_STRFUNC); if (sasl->handler) { sasl->handler (sasl, sasl->connection, FALSE, "no username/password provided"); } goto error; } nonce = g_hash_table_lookup (challenge, "nonce"); if (nonce == NULL || nonce == '\0') { g_log (LM_LOG_DOMAIN, LM_LOG_LEVEL_SASL, "%s: server didn't provide a nonce in the challenge", G_STRFUNC); if (sasl->handler) { sasl->handler (sasl, sasl->connection, FALSE, "server error"); } goto error; } cnonce = sasl_digest_md5_generate_cnonce (); /* FIXME challenge can contain multiple realms */ realm = g_hash_table_lookup (challenge, "realm"); if (realm == NULL) { realm = sasl->server; } /* FIXME properly escape values */ g_string_append_printf (response, "username=\"%s\"", sasl->username); g_string_append_printf (response, ",realm=\"%s\"", realm); g_string_append_printf (response, ",digest-uri=\"xmpp/%s\"", realm); g_string_append_printf (response, ",nonce=\"%s\",nc=00000001", nonce); g_string_append_printf (response, ",cnonce=\"%s\"", cnonce); /* FIXME should check if auth is in the cop challenge val */ g_string_append_printf (response, ",qop=auth,charset=utf-8"); tmp = g_strdup_printf ("%s:%s:%s", sasl->username, realm, sasl->password); md5_init (&md5_calc); md5_append (&md5_calc, (const md5_byte_t *)tmp, strlen(tmp)); md5_finish (&md5_calc, digest_md5); g_free (tmp); a1 = g_strdup_printf ("0123456789012345:%s:%s", nonce, cnonce); len = strlen (a1); memcpy (a1, digest_md5, 16); a1h = sasl_md5_hex_hash (a1, len); a2 = g_strdup_printf ("AUTHENTICATE:xmpp/%s", realm); a2h = sasl_md5_hex_hash (a2, strlen(a2)); kd = g_strdup_printf ("%s:%s:00000001:%s:auth:%s", a1h, nonce, cnonce, a2h); kdh = sasl_md5_hex_hash (kd, strlen(kd)); g_string_append_printf (response, ",response=%s", kdh); g_free (kd); g_free (kdh); g_free (a2); g_free (a2h); /* Calculate the response we expect from the server */ a2 = g_strdup_printf (":xmpp/%s", realm); a2h = sasl_md5_hex_hash (a2, strlen(a2)); kd = g_strdup_printf ("%s:%s:00000001:%s:auth:%s", a1h, nonce, cnonce, a2h); g_free (sasl->digest_md5_rspauth); sasl->digest_md5_rspauth = sasl_md5_hex_hash (kd, strlen(kd)); g_free (a1); g_free (a1h); g_free (a2); g_free (a2h); g_free (kd); out: g_free (cnonce); if (response) { return g_string_free (response, FALSE); } else { return NULL; } error: g_string_free (response, TRUE); response = NULL; goto out; }
static storage_status_t xml_save( irc_t *irc, int overwrite ) { char path[512], *path2, *pass_buf = NULL; set_t *set; account_t *acc; int fd; md5_byte_t pass_md5[21]; md5_state_t md5_state; GSList *l; path2 = g_strdup( irc->user->nick ); nick_lc( path2 ); g_snprintf( path, sizeof( path ) - 2, "%s%s%s", global.conf->configdir, path2, ".xml" ); g_free( path2 ); if( !overwrite && g_access( path, F_OK ) == 0 ) return STORAGE_ALREADY_EXISTS; strcat( path, ".XXXXXX" ); if( ( fd = mkstemp( path ) ) < 0 ) { irc_rootmsg( irc, "Error while opening configuration file." ); return STORAGE_OTHER_ERROR; } /* Generate a salted md5sum of the password. Use 5 bytes for the salt (to prevent dictionary lookups of passwords) to end up with a 21- byte password hash, more convenient for base64 encoding. */ random_bytes( pass_md5 + 16, 5 ); md5_init( &md5_state ); md5_append( &md5_state, (md5_byte_t*) irc->password, strlen( irc->password ) ); md5_append( &md5_state, pass_md5 + 16, 5 ); /* Add the salt. */ md5_finish( &md5_state, pass_md5 ); /* Save the hash in base64-encoded form. */ pass_buf = base64_encode( pass_md5, 21 ); if( !xml_printf( fd, 0, "<user nick=\"%s\" password=\"%s\" version=\"%d\">\n", irc->user->nick, pass_buf, XML_FORMAT_VERSION ) ) goto write_error; g_free( pass_buf ); for( set = irc->b->set; set; set = set->next ) if( set->value && !( set->flags & SET_NOSAVE ) ) if( !xml_printf( fd, 1, "<setting name=\"%s\">%s</setting>\n", set->key, set->value ) ) goto write_error; for( acc = irc->b->accounts; acc; acc = acc->next ) { unsigned char *pass_cr; char *pass_b64; int pass_len; pass_len = arc_encode( acc->pass, strlen( acc->pass ), (unsigned char**) &pass_cr, irc->password, 12 ); pass_b64 = base64_encode( pass_cr, pass_len ); g_free( pass_cr ); if( !xml_printf( fd, 1, "<account protocol=\"%s\" handle=\"%s\" password=\"%s\" " "autoconnect=\"%d\" tag=\"%s\"", acc->prpl->name, acc->user, pass_b64, acc->auto_connect, acc->tag ) ) { g_free( pass_b64 ); goto write_error; } g_free( pass_b64 ); if( acc->server && acc->server[0] && !xml_printf( fd, 0, " server=\"%s\"", acc->server ) ) goto write_error; if( !xml_printf( fd, 0, ">\n" ) ) goto write_error; for( set = acc->set; set; set = set->next ) if( set->value && !( set->flags & ACC_SET_NOSAVE ) ) if( !xml_printf( fd, 2, "<setting name=\"%s\">%s</setting>\n", set->key, set->value ) ) goto write_error; /* This probably looks pretty strange. g_hash_table_foreach is quite a PITA already (but it can't get much better in C without using #define, I'm afraid), and since it doesn't seem to be possible to abort the foreach on write errors, so instead let's use the _find function and return TRUE on write errors. Which means, if we found something, there was an error. :-) */ if( g_hash_table_find( acc->nicks, xml_save_nick, & fd ) ) goto write_error; if( !xml_printf( fd, 1, "</account>\n" ) ) goto write_error; } for( l = irc->channels; l; l = l->next ) { irc_channel_t *ic = l->data; if( ic->flags & IRC_CHANNEL_TEMP ) continue; if( !xml_printf( fd, 1, "<channel name=\"%s\" type=\"%s\">\n", ic->name, set_getstr( &ic->set, "type" ) ) ) goto write_error; for( set = ic->set; set; set = set->next ) if( set->value && strcmp( set->key, "type" ) != 0 ) if( !xml_printf( fd, 2, "<setting name=\"%s\">%s</setting>\n", set->key, set->value ) ) goto write_error; if( !xml_printf( fd, 1, "</channel>\n" ) ) goto write_error; } if( !xml_printf( fd, 0, "</user>\n" ) ) goto write_error; fsync( fd ); close( fd ); path2 = g_strndup( path, strlen( path ) - 7 ); if( rename( path, path2 ) != 0 ) { irc_rootmsg( irc, "Error while renaming temporary configuration file." ); g_free( path2 ); unlink( path ); return STORAGE_OTHER_ERROR; } g_free( path2 ); return STORAGE_OK; write_error: g_free( pass_buf ); irc_rootmsg( irc, "Write error. Disk full?" ); close( fd ); return STORAGE_OTHER_ERROR; }
void Hasher::addData( const void * keyData , size_t numBytes ) { md5_append( &_md5State , static_cast< const md5_byte_t * >( keyData ), numBytes ); }
Hasher::Hasher( HashSeed seed ) : _seed( seed ) { md5_init( &_md5State ); md5_append( &_md5State , reinterpret_cast< const md5_byte_t * >( & _seed ) , sizeof( _seed ) ); }
bool run(const char *ns, BSONObj& cmdObj, string& errmsg, BSONObjBuilder& result, bool fromRepl) { log(1) << " authenticate: " << cmdObj << endl; string user = cmdObj.getStringField("user"); string key = cmdObj.getStringField("key"); string received_nonce = cmdObj.getStringField("nonce"); if( user.empty() || key.empty() || received_nonce.empty() ) { log() << "field missing/wrong type in received authenticate command " << cc().database()->name << endl; errmsg = "auth fails"; sleepmillis(10); return false; } stringstream digestBuilder; { bool reject = false; nonce *ln = lastNonce.release(); if ( ln == 0 ) { reject = true; } else { digestBuilder << hex << *ln; reject = digestBuilder.str() != received_nonce; } if ( reject ) { log() << "auth: bad nonce received or getnonce not called. could be a driver bug or a security attack. db:" << cc().database()->name << endl; errmsg = "auth fails"; sleepmillis(30); return false; } } static BSONObj userPattern = fromjson("{\"user\":1}"); string systemUsers = cc().database()->name + ".system.users"; OCCASIONALLY Helpers::ensureIndex(systemUsers.c_str(), userPattern, false, "user_1"); BSONObj userObj; { BSONObjBuilder b; b << "user" << user; BSONObj query = b.done(); if( !Helpers::findOne(systemUsers.c_str(), query, userObj) ) { log() << "auth: couldn't find user " << user << ", " << systemUsers << endl; errmsg = "auth fails"; return false; } } md5digest d; { string pwd = userObj.getStringField("pwd"); digestBuilder << user << pwd; string done = digestBuilder.str(); md5_state_t st; md5_init(&st); md5_append(&st, (const md5_byte_t *) done.c_str(), done.size()); md5_finish(&st, d); } string computed = digestToString( d ); if ( key != computed ){ log() << "auth: key mismatch " << user << ", ns:" << ns << endl; errmsg = "auth fails"; return false; } AuthenticationInfo *ai = cc().getAuthenticationInfo(); if ( userObj[ "readOnly" ].isBoolean() && userObj[ "readOnly" ].boolean() ) { if ( readLockSupported() ){ ai->authorizeReadOnly( cc().database()->name.c_str() ); } else { log() << "warning: old version of boost, read-only users not supported" << endl; ai->authorize( cc().database()->name.c_str() ); } } else { ai->authorize( cc().database()->name.c_str() ); } return true; }
void setup_metadata(kbconfig *config) { LOG(1, "Writing metadata.\n"); fs_metadata *md = fs_metadata_open(config->name); fs_metadata_clear(md); fs_metadata_set(md, FS_MD_NAME, config->name); fs_metadata_set(md, FS_MD_HASHFUNC, FS_HASH); fs_metadata_set(md, FS_MD_STORE, "native"); fs_metadata_set(md, FS_MD_MODEL_DATA, "true"); if (config->model_files) { fs_metadata_set(md, FS_MD_MODEL_FILES, "true"); } else { fs_metadata_set(md, FS_MD_MODEL_FILES, "false"); } fs_metadata_set(md, FS_MD_CODE_VERSION, GIT_REV); for (int seg = 0; seg < config->segments; seg++) { if (primary_segment(config, seg)) fs_metadata_add_int(md, FS_MD_SEGMENT_P, seg); if (mirror_segment(config, seg)) fs_metadata_add_int(md, FS_MD_SEGMENT_M, seg); } /* Generate store UUID for skolemisation */ #if defined(USE_LINUX_UUID) uuid_t uu; uuid_string_t uus; uuid_generate(uu); uuid_unparse(uu, uus); #elif defined(USE_BSD_UUID) uuid_t uu; char *uus = NULL; int status = -1; uuid_create(&uu, &status); if (status) { fs_error(LOG_ERR, "bad return from uuid_create"); exit(1); } uuid_to_string(&uu, &uus, &status); if (status || uus == NULL) { fs_error(LOG_ERR, "bad return from uuid_to_string"); exit(1); } #elif defined(USE_OSSP_UUID) uuid_t *uu = NULL; char *uus = NULL; if (uuid_create(&uu)) { fs_error(LOG_ERR, "bad return from uuid_create"); exit(1); } if (uuid_make(uu, UUID_MAKE_V1)) { fs_error(LOG_ERR, "bad return from uuid_make"); exit(1); } if (uuid_export(uu, UUID_FMT_STR, &uus, NULL) || uus == NULL) { fs_error(LOG_ERR, "bad return from uuid_export"); exit(1); } #endif fs_metadata_add(md, FS_MD_UUID, uus); #if defined(USE_OSSP_UUID) uuid_destroy(uu); #endif unsigned char stage1[20], stage2[16]; char hash[33] = "none"; int now = 0; if (config->password) { md5_state_t md5; char *pw = g_strdup_printf("%s:%s", config->name, config->password); /* stage1 will contain the 4 byte Unix time_t value as a salt ... */ now = time(NULL); memcpy(stage1, &now, sizeof(now)); /* ... followed by the on-wire 16 byte MD5 auth string */ md5_init(&md5); md5_append(&md5, (md5_byte_t *) pw, strlen(pw)); md5_finish(&md5, stage1 + 4); /* now use MD5 on all 20 bytes and store both the salt and the hash */ md5_init(&md5); md5_append(&md5, stage1, sizeof(stage1)); md5_finish(&md5, stage2); sprintf(hash, "%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x", stage2[0], stage2[1], stage2[2], stage2[3], stage2[4], stage2[5], stage2[6], stage2[7], stage2[8], stage2[9], stage2[10], stage2[11], stage2[12], stage2[13], stage2[14], stage2[15]); g_free(pw); } fs_metadata_add_int(md, FS_MD_VERSION, FS_CURRENT_TABLE_VERSION); fs_metadata_add_int(md, FS_MD_SEGMENTS, config->segments); fs_metadata_add_int(md, FS_MD_SALT, now); fs_metadata_add_int(md, FS_MD_BNODE, 1); fs_metadata_add(md, FS_MD_HASH, hash); fs_metadata_flush(md); fs_metadata_close(md); fs_error(LOG_INFO, "created RDF metadata for KB %s", config->name); }