static Hash getHash(const char* &ptr) { std::string res = getNext(ptr); Hash h; if(res != "") h.fromString(res); return h; }
void t2(){ // string key checks printf("test 1, strings----\n"); Hash h; Value v,w; char keys[HCOUNT][32]; char vals[HCOUNT][32]; for(int i=0;i<HCOUNT;i++){ sprintf(keys[i],"foo%x",i*31); Types::tString->set(&v,keys[i]); sprintf(vals[i],"bar%d",rand()%100000); Types::tString->set(&w,vals[i]); // printf("%s %s\n",keys[i],vals[i]); h.set(&v,&w); } for(int i=0;i<HCOUNT;i++){ Types::tString->set(&v,keys[i]); if(h.find(&v)){ w.copy(h.getval()); if(w.t != Types::tString) die("value not an int"); const StringBuffer& buf = w.toString(); if(strcmp(buf.get(),vals[i])){ printf("%s != %s\n",buf.get(),vals[i]); die("value mismatch"); } } else die("key not found"); } }
Hash Hasher::getResult() { Hash result; result.newData(); memcpy(result.data->hash, this->cryptographicHash.result().constData(), Hash::HASH_SIZE); return result; }
Attachment::Hash Attachment::toHash(const Attachment::List &list) { Hash hash; foreach (auto attachment, list) hash.insert(attachment.type(), attachment); return hash; }
/* Directly sum an entire stream. The stream is read in increments, to avoid loading large files into memory. You can specify the buffer size as the second parameter, the default is 16 Kb. The algorithm does not depend on size() for non-pointer streams. Pointer streams are hashed in one go, and do not advance the file pointer. Since the position of the file pointer after this operation depends on the type of stream given, it is considered undefined. */ static Hash sum(Mangle::Stream::Stream &str, int bufsize = DEFSIZE) { assert(str.isReadable); // Is this a memory stream? if(str.hasPtr) { assert(str.hasSize); // Pointer streams makes life easy return Hash(str.getPtr(), str.size()); } // No pointers today. Create a buffer and hash in increments. char *buf = new char[bufsize]; Hash result; // We do not depend on the stream size, only on eof(). while(!str.eof()) { size_t num = str.read(buf, bufsize); // If we read less than expected, we should be at the // end of the stream assert(num == bufsize || (num < bufsize && str.eof())); // Hash the data result.update(buf, num); } // Clean up and return delete[] buf; return result.finish(); }
Hash* Parser::readHash() { Tokenizer::TokenType tok = tokenizer->nextToken(); if (tok != Tokenizer::TokenBeginGroup) { tokenizer->pushBack(); return NULL; } Hash* hash = new Hash(); tok = tokenizer->nextToken(); while (tok != Tokenizer::TokenEndGroup) { if (tok != Tokenizer::TokenName) { tokenizer->pushBack(); delete hash; return NULL; } string name = tokenizer->getNameValue(); Value* value = readValue(); if (value == NULL) { delete hash; return NULL; } hash->addValue(name, *value); tok = tokenizer->nextToken(); } return hash; }
void t1(){ printf("test 1, integers----\n"); int keys[HCOUNT]; int vals[HCOUNT]; Hash h; Value v,w; for(int i=0;i<HCOUNT;i++){ keys[i]=i*31; Types::tInteger->set(&v,keys[i]); vals[i]=rand()%100000; Types::tInteger->set(&w,vals[i]); h.set(&v,&w); } for(int i=0;i<HCOUNT;i++){ Types::tInteger->set(&v,keys[i]); if(h.find(&v)){ w.copy(h.getval()); if(w.t != Types::tInteger) die("value not an int"); else if(w.toInt() != vals[i]){ printf("%d != %d\n",w.toInt(),vals[i]); die("value mismatch"); } } else die("key not found"); } }
int main(int argc, char *argv[]) { string lineBuffer; ifstream file; file.open(argv[1]); int count=0; Hash strHash; vector<string> wordArray; //insert strings into vector int g=0; while (!file.eof()){ getline(file, lineBuffer); string str=new char[lineBuffer.length()](); if (lineBuffer.length() != 0) wordArray.push_back(lineBuffer); } for(int i=0;i<wordArray.size();i++) strHash.insert((char*)&wordArray.at(i)[0]); //sort vector by string length sort(wordArray.begin(),wordArray.end()); sort(wordArray.begin(),wordArray.end(), stringCompare); for(int i=0;i<wordArray.size();i++){ //check whether this word is made up of other words if(buildWord(wordArray.at(i), true, strHash)){ count++; //only print first 2 longest word made up of other words if(count<3) cout<<wordArray.at(i)<<endl; } } //printf how many of the words in the list can be constructed of other words in the list cout<<"There are "<<count<<" words that can be constructed of other words in the list"<<endl; return 0; }
/** * A search has been completed. Store the information in the hash. * * Currently overwrites existing hash entry regardless of depth. */ void HashTable::storeHash(u64 mover, u64 enemy, int alpha, int beta, int score) { Hash* entry = hashLoc(mover, enemy); if (entry->mover != mover ||entry->enemy != enemy) { entry->init(mover, enemy); } entry->store(alpha, beta, score); }
/* returns false if checksum matched and true if failed */ void RecordSetInBase::checksum() const { int const cs(check_size(check_type_)); if (cs > 0) /* checksum records */ { Hash check; check.append (head_ + begin_, size_ - begin_); /* records */ check.append (head_, begin_ - cs); /* header */ assert(cs <= MAX_CHECKSUM_SIZE); byte_t result[MAX_CHECKSUM_SIZE]; check.gather<sizeof(result)>(result); const byte_t* const stored_checksum(head_ + begin_ - cs); if (gu_unlikely(memcmp (result, stored_checksum, cs))) { gu_throw_error(EINVAL) << "RecordSet checksum does not match:" << "\ncomputed: " << gu::Hexdump(result, cs) << "\nfound: " << gu::Hexdump(stored_checksum, cs); } } }
QByteArray BulkRound::ProcessMessage(int des_idx, int msg_index) { int count = _messages.size(); const Descriptor &des = GetDescriptors()[des_idx]; int length = des.Length(); QByteArray msg(length, 0); Hash hashalgo; bool good = true; for(int idx = 0; idx < count; idx++) { const char *tmsg = _messages[idx].constData() + msg_index; QByteArray xor_msg(QByteArray::fromRawData(tmsg, length)); if(des.XorMessageHashes()[idx] != hashalgo.ComputeHash(xor_msg)) { qWarning() << "Xor message does not hash properly"; _bad_message_hash.append(BadHash(des_idx, idx)); good = false; } if(good) { Xor(msg, msg, xor_msg); } } if(good) { return msg; } else { return QByteArray(); } }
void BulkRound::CreateDescriptor(const QByteArray &data) { int length = data.size(); Hash hashalgo; QByteArray xor_message(length, 0); QVector<QByteArray> hashes; int my_idx = GetGroup().GetIndex(GetLocalId()); foreach(const PublicIdentity &gc, GetGroup().GetRoster()) { QByteArray seed = _anon_dh.GetSharedSecret(gc.GetDhKey()); if(hashes.size() == my_idx) { hashes.append(QByteArray()); continue; } QByteArray msg(length, 0); CryptoRandom(seed).GenerateBlock(msg); hashes.append(hashalgo.ComputeHash(msg)); Xor(xor_message, xor_message, msg); } QByteArray my_xor_message = QByteArray(length, 0); Xor(my_xor_message, xor_message, data); SetMyXorMessage(my_xor_message); hashes[my_idx] = hashalgo.ComputeHash(my_xor_message); QByteArray hash = hashalgo.ComputeHash(data); Descriptor descriptor(length, _anon_dh.GetPublicComponent(), hashes, hash); SetMyDescriptor(descriptor); }
static NAN_METHOD(Copy) { Hash *src = Nan::ObjectWrap::Unwrap<Hash>(info.This()); const unsigned argc = 1; v8::Local<v8::Value> argv[argc] = { Nan::New<v8::String>("bypass").ToLocalChecked() }; v8::Local<v8::FunctionTemplate> construct = Nan::New<v8::FunctionTemplate>(hash_constructor); v8::Local<v8::Object> inst = construct->GetFunction()->NewInstance(argc, argv); // Construction may fail with a JS exception, in which case we just need // to return. if(inst.IsEmpty()) { return; } Hash *dest = new Hash(); dest->Wrap(inst); dest->initialized_ = src->initialized_; dest->any_blake2_update = src->any_blake2_update; dest->any_blake2_final = src->any_blake2_final; dest->outbytes = src->outbytes; dest->state = src->state; info.GetReturnValue().Set(inst); }
void LCA(int u, int d) { p[u] = u; dist[u] = d; int k; visit[u] = true; for (k = head[u]; k != 0; k = edge[k].next) { if (!visit[edge[k].to]) { LCA(edge[k].to, d + 1); p[edge[k].to] = u; } } for (k = qhead[qhead_hash.findHash(id_to_name[u])]; k != 0; k = qedge[k].next) { std::vector<int>::iterator j, j_first, j_last; j_first = name_to_id[surnames.findHash(qedge[k].to)].begin(); j_last = name_to_id[surnames.findHash(qedge[k].to)].end(); for (j = j_first; j != j_last; ++j) { if (visit[*j]) { int lca = find(*j); int query1 = qmap_hash.findHash(make_pair(id_to_name[u], qedge[k].to)); int query2 = qmap_hash.findHash(make_pair(qedge[k].to, id_to_name[u])); qmap[query1] = max(qmap[query1], dist[u] + dist[*j] - 2 * dist[lca]); qmap[query2] = max(qmap[query2], dist[u] + dist[*j] - 2 * dist[lca]); } } } }
void Servicios::agregarAlHash(string nombreHash, string clavePasada, unsigned int idNueva) { string pathHash = Parametros().getParametro(CARPETA_DATOS); pathHash += nombreHash; Hash *hash = new Hash(pathHash); Registro* registro= hash->buscar(clavePasada); unsigned int offset; //si ya existe la lista// if (registro){ //cout << "lista ya existente" << endl; offset = registro->getAtributosEnteros()->front(); ListasIds().agregarIdDeLibro(&offset,idNueva,false); } //no existe la lista de ids else{ //cout << "lista nueva" << endl; ListasIds().agregarIdDeLibro(&offset, idNueva,true); registro = new Registro(); registro->setString(clavePasada); registro->agregarAtribEntero(offset); hash->insertar(registro); } delete registro; delete hash; }
void HashTest::test_performance() { const int ITERATION_COUNT = 1000000; { Hash hf; clock_t t = clock(); for(int i = 0; i < ITERATION_COUNT; ++i) { Id<16> id(true); hf.AddData(id.ConstData(), id.Size); GUINT32 hash = hf.Final(); GUTIL_UNUSED(hash); } clock_t e = clock(); qDebug("Number of ticks to do %d hashes was: %d", ITERATION_COUNT, (int)(e - t)); } { std::hash<string> hf; clock_t t = clock(); for(int i = 0; i < ITERATION_COUNT; ++i) { Id<16> id(true); string s((char const *)id.ConstData(), id.Size); GUINT32 hash = hf(s); GUTIL_UNUSED(hash); } clock_t e = clock(); qDebug("Number of ticks to do %d standard hashes was: %d", ITERATION_COUNT, (int)(e - t)); } }
CompositeIntegerGroup::CompositeIntegerGroup(Integer n) : _n(n) { // We pick the generator deterministically n Hash *hash = CryptoFactory::GetInstance().GetLibrary()->GetHashAlgorithm(); QByteArray seed = hash->ComputeHash(n.GetByteArray()); for(_s=3; ; _s = _s+1) { if(!_s.IsPrime()) continue; _p = (2 * _s * _n) + 1; if(_p.IsPrime()) break; } // Set g to some random element Integer g, h; const Integer e_test = 2*_s; for(Integer i=0; ; i = i+1) { h = (Integer(seed) + i) % _p; // Make sure that g generates a subgroup that is bigger // than order 2 and s and smaller than order P. // Since we do not know the factorization of n=qr, // we might be generating a subgroup of order q or r. if((g = h.Pow(e_test, _p)) != 1) break; } _g = Element(new IntegerElementData(g)); /* qDebug() << "_p" << _p.GetByteArray().toHex(); qDebug() << "_s" << _s.GetByteArray().toHex(); */ };
int _tmain(int argc, _TCHAR* argv[]) { Hash *h = new Hash; h->init(); printf("Reading from file...\n"); FILE * fd = fopen("FILE.TXT", "r"); char str[100]; while(fscanf(fd, "%s", str) != EOF) h->add(str); fclose(fd); /*printf("Input word which needs to find\n"); scanf("%s", str); HashList *tmp = h->find(str); if (tmp) printf("words count is %d\n", tmp->count); else printf("There is no \"%s\"", str); */ h->printStats(); delete h; scanf("%*s"); return 0; }
void append_transform_to(Hash& hash) { xform.append(hash); knob("xform")->append(hash, NULL); hash.append(flip_); hash.append(flop_); hash.append(wrap_); }
Hash get_hash(int l, int r, Hash h[maxn]) { Hash res = h[r]; if (l != 0) res = res - h[l - 1]; res = res.up(N / 2 - l); return res; }
/** * Return a new rand hash. */ Hash Hash::rand() { Hash hash; hash.newData(); for (int i = 0; i < HASH_SIZE; i++) hash.data->hash[i] = static_cast<char>(Hash::mtrand.randInt(255)); return hash; }
void append(Hash& hash) { hash.append(VERSION); // Knobs that change the SyLens algo hash.append(distorter.compute_hash()); hash.append(uv_attrib_name); ModifyGeo::append(hash); // the super called he wants his pointers back }
Hash Hash::rand(quint32 seed) { MTRand mtrand(seed); Hash hash; hash.newData(); for (int i = 0; i < HASH_SIZE; i++) hash.data->hash[i] = static_cast<char>(mtrand.randInt(255)); return hash; }
void HashTest::test_collisions() { // Do a collision check. It should be practically impossible to get a collision double my_avg = 0; const int ITERATION_COUNT = 25; for(int i = 0; i < ITERATION_COUNT; ++i) { //qDebug("Iteration %d", i); set<GUINT32> hashes; GUINT32 cnt = 0; bool collision = false; Hash hf; forever{ cnt++; Id<16> id(true); hf.AddData(id.ConstData(), id.Size); GUINT32 hash = hf.Final(); collision = hashes.find(hash) != hashes.end(); if(!collision) hashes.insert(hash); else break; } //qDebug(QString("Did %1 hashes before a collision").arg(cnt).toAscii()); //QVERIFY(cnt > 10000); my_avg += cnt; } my_avg /= ITERATION_COUNT; qDebug("My average number of hashes before collision was: %f", my_avg); QVERIFY(my_avg > 50000); // Compare our results with the standard hash double their_avg = 0; for(int i = 0; i < ITERATION_COUNT; ++i) { set<GUINT32> hashes; GUINT32 cnt = 0; bool collision = false; std::hash<string> sh; forever{ cnt++; Id<16> id(true); string s((char const *)id.ConstData(), id.Size); GUINT32 hash = sh(s); collision = hashes.find(hash) != hashes.end(); if(!collision) hashes.insert(hash); else break; } their_avg += cnt; //qDebug(QString("Standard hash did %1 hashes before a collision").arg(cnt).toAscii()); } their_avg /= ITERATION_COUNT; qDebug("The average number of standard hashes before collision was: %f", their_avg); }
static Mapping hashToBiMap(const Hash &hash) { Mapping biMap; Hash::const_iterator it = hash.constBegin(); const Hash::const_iterator end = hash.constEnd(); for ( ; it != end; ++it) biMap.insert(Mapping::value_type(it.key(), it.value())); return biMap; }
void testAdd() { Hash<int, int> h; h.put(42, 11); if (h.get(42) == h.end()) { cout << "testAdd failed\n"; } }
void GasInfoSettings::setValue(const QString & key, const QVariant & value) { Hash* h = reg(); if (h->contains(key)) { (*h)[key] = value; } QSettings::setValue(key, value); }
ConstBufferPtr Digest<Hash>::computeDigest(const uint8_t* buffer, size_t size) { Hash hash; BufferPtr result = make_shared<Buffer>(hash.DigestSize()); hash.Update(buffer, size); hash.Final(result->get()); return result; }
bool Hash::operator ==(const Hash &second) const { if(getType() != second.getType()) return false; if(getBuffer() != second.getBuffer()) return false; return true; }
T read_hash (const string &key) { if (local_hash.count(key) > 0) { return read<T>(local_hash[key]); } if (global_hash.count(key) > 0) { return read<T>(global_hash[key]); } cerr << "hash key not found: " << key << endl; exit(-1); }