void testStripSpacesAtEnd() { vmime::parsingContext ctx; const vmime::string buffer = "Field: \r\n\tfield data "; vmime::ref <vmime::headerField> hfield = vmime::headerField::parseNext(ctx, buffer, 0, buffer.size()); vmime::ref <vmime::text> hvalue = hfield->getValue().dynamicCast <vmime::text>(); VASSERT_EQ("Field name", "Field", hfield->getName()); VASSERT_EQ("Field value", toHex("field data"), toHex(hvalue->getWholeBuffer())); }
bool TestClient::SetInferior(llvm::ArrayRef<std::string> inferior_args) { std::stringstream command; command << "A"; for (size_t i = 0; i < inferior_args.size(); i++) { if (i > 0) command << ','; std::string hex_encoded = toHex(inferior_args[i]); command << hex_encoded.size() << ',' << i << ',' << hex_encoded; } if (!SendMessage(command.str())) return false; if (!SendMessage("qLaunchSuccess")) return false; std::string response; if (!SendMessage("qProcessInfo", response)) return false; auto create_or_error = ProcessInfo::Create(response); if (auto create_error = create_or_error.takeError()) { GTEST_LOG_(ERROR) << toString(std::move(create_error)); return false; } m_process_info = *create_or_error; return true; }
void testObj::test<8>(void) { auto out = toHex( {0x00, 0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70, 0x80, 0x90, 0xA0, 0xB0, 0xC0, 0xD0, 0xE0, 0xF0, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f} ); ensure_equals("invalid hex string", out, "00102030405060708090a0b0c0d0e0f0" "000102030405060708090a0b0c0d0e0f"); }
Address toAddress(Secret _private) { secp256k1_start(); byte pubkey[65]; int pubkeylen = 65; int ok = secp256k1_ecdsa_seckey_verify(_private.data()); if (!ok) return Address(); ok = secp256k1_ecdsa_pubkey_create(pubkey, &pubkeylen, _private.data(), 0); assert(pubkeylen == 65); if (!ok) return Address(); ok = secp256k1_ecdsa_pubkey_verify(pubkey, 65); if (!ok) return Address(); auto ret = right160(dev::eth::sha3(bytesConstRef(&(pubkey[1]), 64))); #if ETH_ADDRESS_DEBUG cout << "---- ADDRESS -------------------------------" << endl; cout << "SEC: " << _private << endl; cout << "PUB: " << toHex(bytesConstRef(&(pubkey[1]), 64)) << endl; cout << "ADR: " << ret << endl; #endif return ret; }
NarrowString HTMLEntityCodec::encodeCharacter(const StringArray& immune, const NarrowString& ch) const { // ASSERT(!immune.empty()); ASSERT(!ch.empty()); if(ch.empty()) return NarrowString(); // check for immune characters StringArray::const_iterator it1 = std::find(immune.begin(), immune.end(), ch); if(it1 != immune.end()) return ch; // check for simple alphanumeric characters if(ch.length() == 1 && ::isalnum(ch[0])) return ch; // check for illegal characterss //if ( ( c <= 0x1f && c != L'\t' && c != L'\n' && c != L'\r' ) || ( c >= 0x7f && c <= 0x9f ) ) //{ // hex = REPLACEMENT_HEX(); // Let's entity encode this instead of returning it // c = REPLACEMENT_CHAR(); //} // check if there's a defined entity const EntityMap& map = getCharacterToEntityMap(); EntityMapIterator it2 = map.find(ch); if(it2 != map.end()) return String("&") + it2->second + String(";"); // return the hex entity as suggested in the spec return NarrowString("&#x") + toHex(ch) + NarrowString(";"); }
//Specify how to get the line and column data QVariant HexFileModel::headerData(int section, Qt::Orientation orientation, int role) const { if(role == Qt::DisplayRole) { if(orientation == Qt::Horizontal) { //Hex area if(section>=1 && section < 17) { if(section < 11) { return QVariant(section-1); } else { char ch = 'A' + (section-11); return QVariant(QString::fromLatin1(&ch,1)); } } } else { return QVariant(QString(toHex(section*16).c_str())); } } if (role == Qt::TextAlignmentRole) { return Qt::AlignLeft; } return QVariant(); }
// Prints an unsigned int as a block of four bytes // Least to most sigificant void printBlock(unsigned int block) { // Split into four bytes unsigned char bytes[4]; for (int i = 0; i < 4; i++) { bytes[3 - i] = block % 256; block = block >> 8; } // Print bytes from LEAST to MOST significant for (int i = 3; i >= 0; i--) { char * h = toHex(bytes[i]); printf("\\x%s", toHex(bytes[i])); free(h); } }
string toHex(const uint8_t* array, size_t arrayLength) { ostringstream result; toHex(array, arrayLength, result); return result.str(); }
virtual void endOutput( const uint8_t *p, uint64_t value, const uint8_t *txHash, uint64_t outputIndex, const uint8_t *outputScript, uint64_t outputScriptSize ) { if (active) { numTxOutputs++; totalTxOutput += value; // Script uint8_t script[1 + 2*outputScriptSize]; toHex(script, outputScript, outputScriptSize); // Receiving address uint8_t address[40]; address[0] = 'X'; address[1] = 0; uint8_t addrType[3]; uint160_t pubKeyHash; int type = solveOutputScript(pubKeyHash.v, outputScript, outputScriptSize, addrType); if(likely(0<=type)) hash160ToAddr(address, pubKeyHash.v); // N.B. Input hash and index are NULL at this stage fprintf(outputFile, "%" PRIu64 ",%" PRIu64 ",%" PRIu64 ",\"%s\",\"%s\",,\n", txID, outputIndex, value, script, address); } }
virtual void startTX( const uint8_t *p, const uint8_t *hash ) { if (active) { txStart = p; numBlkTxs++; numTxInputs = 0; numTxOutputs = 0; totalTxInput = 0; totalTxOutput = 0; // ID fprintf(txFile, "%" PRIu64 ",", txID); // Hash uint8_t buf[1 + 2*kSHA256ByteSize]; toHex(buf, hash); fprintf(txFile, "\"%s\",", buf); // Version LOAD(uint32_t, version, p); fprintf(txFile, "%" PRIu32 ",", version); // Block ID fprintf(txFile, "%" PRIu64 ",", blkID); } }
void MemTrie::insert(std::string const& _key, std::string const& _value) { if (_value.empty()) remove(_key); auto h = toHex(_key); m_root = m_root ? m_root->insert(&h, _value) : new TrieLeafNode(bytesConstRef(&h), _value); }
std::string CEncrypt::urlEncode(std::string strVal) { const char *pszVal = strVal.c_str(); std::string strTemp = ""; size_t iLens = strVal.size(); for (size_t i = 0; i < iLens; i++) { if (isalnum((unsigned char)pszVal[i]) || ('-' == pszVal[i]) || ('_' == pszVal[i]) || ('.' == pszVal[i]) || ('~' == pszVal[i])) { strTemp += pszVal[i]; } else if (' ' == pszVal[i]) { strTemp += "+"; } else { strTemp += '%'; strTemp += toHex((unsigned char)pszVal[i] >> 4); strTemp += toHex((unsigned char)pszVal[i] % 16); } } return strTemp; }
void CModListView::loadScreenshots() { if (ui->tabWidget->currentIndex() == 2 && ui->modInfoWidget->isVisible()) { ui->screenshotsList->clear(); QString modName = ui->allModsView->currentIndex().data(ModRoles::ModNameRole).toString(); assert(modModel->hasMod(modName)); //should be filtered out by check above for (QString & url : modModel->getMod(modName).getValue("screenshots").toStringList()) { // URL must be encoded to something else to get rid of symbols illegal in file names auto hashed = QCryptographicHash::hash(url.toUtf8(), QCryptographicHash::Md5); auto hashedStr = QString::fromUtf8(hashed.toHex()); QString fullPath = CLauncherDirs::get().downloadsPath() + '/' + hashedStr + ".png"; QPixmap pixmap(fullPath); if (pixmap.isNull()) { // image file not exists or corrupted - try to redownload downloadFile(hashedStr + ".png", url, "screenshots"); } else { // managed to load cached image QIcon icon(pixmap); QListWidgetItem * item = new QListWidgetItem(icon, QString(tr("Screenshot %1")).arg(ui->screenshotsList->count() + 1)); ui->screenshotsList->addItem(item); } } } }
QString toHex(FastoCommonItem* item) { if(!item){ return QString(); } if(!item->childrenCount()){ QString val = item->value(); std::string sval = common::convertToString(val); std::string hexstr; common::HexEDcoder hex; common::Error er = hex.encode(sval, hexstr); if(er){ return QString(); } return common::convertFromString<QString>(hexstr); } QString value; for(int i = 0; i < item->childrenCount(); ++i){ value += toHex(dynamic_cast<FastoCommonItem*>(item->child(i))); } return value; }
static bool testAddr2Hash( const uint8_t *addr, const uint8_t *hexHash ) { uint8_t result[kRIPEMD160ByteSize]; auto ok = addrToHash160(result, addr, true); TEST_CHECK(ok, ok, "failed to decode address %s", addr); uint8_t hash[kRIPEMD160ByteSize]; fromHex(hash, (const uint8_t*)hexHash, kRIPEMD160ByteSize, false); uint8_t hexResult[1 + 2*kRIPEMD160ByteSize]; toHex(hexResult, result, kRIPEMD160ByteSize, false); TEST_CHECK( ok, 0==memcmp(result, hash, kRIPEMD160ByteSize), "decode fail\n" " for addr: %s\n" " expected: %s\n" " got: %s\n" "\n", addr, hexHash, hexResult ); return ok; }
std::ostream& operator<<(std::ostream& os, const KeyLocator& keyLocator) { switch (keyLocator.getType()) { case KeyLocator::KeyLocator_Name: { return os << "Name=" << keyLocator.getName(); } case KeyLocator::KeyLocator_KeyDigest: { const size_t MAX_DIGEST_OCTETS_TO_SHOW = 5; const Block& digest = keyLocator.getKeyDigest(); os << "KeyDigest=" << toHex(digest.value(), digest.value_size()).substr(0, MAX_DIGEST_OCTETS_TO_SHOW * 2); if (digest.value_size() > MAX_DIGEST_OCTETS_TO_SHOW) { os << "..."; } return os; } case KeyLocator::KeyLocator_None: { return os << "None"; } case KeyLocator::KeyLocator_Unknown: { return os << "Unknown"; } } return os << "Unknown"; }
void AssetClient::handleAssetGetInfoReply(QSharedPointer<ReceivedMessage> message, SharedNodePointer senderNode) { MessageID messageID; message->readPrimitive(&messageID); auto assetHash = message->read(SHA256_HASH_LENGTH); AssetServerError error; message->readPrimitive(&error); AssetInfo info { assetHash.toHex(), 0 }; if (error == AssetServerError::NoError) { message->readPrimitive(&info.size); } // Check if we have any pending requests for this node auto messageMapIt = _pendingInfoRequests.find(senderNode); if (messageMapIt != _pendingInfoRequests.end()) { // Found the node, get the MessageID -> Callback map auto& messageCallbackMap = messageMapIt->second; // Check if we have this pending request auto requestIt = messageCallbackMap.find(messageID); if (requestIt != messageCallbackMap.end()) { auto callback = requestIt->second; callback(true, error, info); messageCallbackMap.erase(requestIt); } // Although the messageCallbackMap may now be empty, we won't delete the node until we have disconnected from // it to avoid constantly creating/deleting the map on subsequent requests. } }
void MockAppLayer::SendUnsolicited(APDU& arAPDU) { LOG_BLOCK(LEV_COMM, "=> " << toHex(arAPDU.GetBuffer(), arAPDU.Size(), true)); LOG_BLOCK(LEV_INTERPRET, "=> " << arAPDU.ToString()); mFragments.push_back(arAPDU); this->DoSendUnsol(); }
string urlEncoding( string &sIn ) { cout << "size: " << sIn.size() << endl; string sOut; for( int ix = 0; ix < sIn.size(); ix++ ) { BYTE buf[4]; memset( buf, 0, 4 ); if( isalnum( (BYTE)sIn[ix] ) ) { buf[0] = sIn[ix]; } else if ( isspace( (BYTE)sIn[ix] ) ) { buf[0] = '+'; } else { buf[0] = '%'; buf[1] = toHex( (BYTE)sIn[ix] >> 4 ); buf[2] = toHex( (BYTE)sIn[ix] % 16); } sOut += (char *)buf; } return sOut; }
std::string UrlEncode(const std::string & sIn) { std::string sOut; for(size_t i=0; i < sIn.size(); ++i) { unsigned char buf[4]; memset(buf, 0, 4); if(isalnum((unsigned char)sIn[i])) { buf[0] = sIn[i]; } else if(isspace((unsigned char)sIn[i])) { buf[0] = '+'; } else { buf[0] = '%'; buf[1] = toHex((unsigned char)sIn[i] >> 4); buf[2] = toHex((unsigned char)sIn[i] % 16); } sOut += (char *)buf; } return sOut; }
virtual void edge( uint64_t value, const uint8_t *upTXHash, uint64_t outputIndex, const uint8_t *outputScript, uint64_t outputScriptSize, const uint8_t *downTXHash, uint64_t inputIndex, const uint8_t *inputScript, uint64_t inputScriptSize ) { if(dump) { uint8_t buf[1 + 2*kSHA256ByteSize]; toHex(buf, upTXHash); printf(" outputIndex = %" PRIu64 "\n", outputIndex); printf(" value = %.8f\n", value*1e-6); printf(" upTXHash = %s\n\n", buf); printf(" # challenge answer script, bytes=%" PRIu64 " (on downstream input) =\n", inputScriptSize); showScript(inputScript, inputScriptSize, 0, " "); printf(" ||\n"); printf(" VV\n"); printf(" # challenge script, bytes=%" PRIu64 " (on upstream output)=\n", outputScriptSize); showScript(outputScript, outputScriptSize, 0, " "); showScriptInfo(outputScript, outputScriptSize); valueIn += value; } }
int Drawboard::authenticate(Client* client) { uint32_t curpos = 1; uint32_t len=getUint16((uint8_t *)(&client->buffer[0]+curpos)); curpos += 2; #ifdef DEBUG std::cout << " Len: " << len << std::endl; #endif if(client->buffer.size()-curpos < len) { return NEED_MORE_DATA; } std::string hash(' ',32); int32_t UID=getSint16((uint8_t *)(&client->buffer[0]+curpos)); curpos += 2; uint8_t chanID = client->buffer[curpos]; curpos++; uint64_t timestamp = getUint64((uint8_t *)(&client->buffer[0]+curpos)); curpos += 8; uint8_t adminbit = client->buffer[curpos]; curpos++; memcpy((void *)hash.data(), (uint8_t *)(&client->buffer[0]+curpos),32); curpos += 32; uint32_t nicklen=client->buffer[curpos]; curpos++; std::string nick; for(uint32_t i = 0; i < nicklen; i++) { nick+=(char)client->buffer[curpos]; curpos ++; } //Clear the data from the buffer client->eraseFromBuffer(curpos); //ToDo: implement configuration reader etc if(0)//config.check_auth) { std::string user_time; myItoa(timestamp,user_time,10); //Check the auth data std::string combination=user_time+"|SECRET_STRING|"+(char)('0'+adminbit)+"|"+nick; std::string hash2; MD5_CTX mdContext; MD5Init (&mdContext); MD5Update (&mdContext, (unsigned char *)(combination.c_str()), combination.size()); MD5Final (&mdContext); for (int iii = 0; iii < 16; iii++) hash2+=toHex((unsigned int)mdContext.digest[iii]); if(hash2 != hash) { return DATA_ERROR; } } client->nick = nick; client->admin = (adminbit==0)?false:true; return DATA_OK; }
void ConfigArray::save(std::ostream &sout) { list<ConfigValue*>::iterator it; for (it = values.begin(); it != values.end(); it++){ string s; string quoted; if ((*it)->isList){ static_cast<ConfigList*>(*it)->save(sout); continue; } if (!(*it)->save(s)) continue; for (unsigned i = 0; i < s.size(); i++){ switch (s[i]){ case '\\': quoted += "\\\\"; break; case '\n': quoted += "\\n"; break; default: if ((unsigned char)s[i] >= ' '){ quoted += s[i]; }else if (s[i]){ quoted += "\\x"; quoted += toHex(s[i] >> 4); quoted += toHex(s[i]); } } } sout << (*it)->m_name << "=" << quoted << "\n"; } }
std::string toUUID(h128 const& _uuid) { std::string ret = toHex(_uuid.ref()); for (unsigned i: {20, 16, 12, 8}) ret.insert(ret.begin() + i, '-'); return ret; }
void IUpperLayer::OnReceive(const apl::byte_t* apData, size_t aNumBytes) { if(this->LogReceive()) { LOG_BLOCK(LEV_COMM, RecvString() << " " << toHex(apData, aNumBytes, true)); } this->_OnReceive(apData, aNumBytes); //call the implementation }
// https://secure.wikimedia.org/wikipedia/en/wiki/URL_encoding void urlEncode(char* _out, uint32_t _max, const StringView& _str) { _max--; // need space for zero terminator const char* str = _str.getPtr(); const char* term = _str.getTerm(); uint32_t ii = 0; for (char ch = *str++ ; str <= term && ii < _max ; ch = *str++ ) { if (isAlphaNum(ch) || ch == '-' || ch == '_' || ch == '.' || ch == '~') { _out[ii++] = ch; } else if (ii+3 < _max) { _out[ii++] = '%'; _out[ii++] = toHex(ch>>4); _out[ii++] = toHex(ch); } }
void DigestTree::Node::recomputeDigest() { SHA256_CTX sha256; SHA256_Init(&sha256); uint8_t number[4]; int32ToLittleEndian(sessionNo_, number); SHA256_Update(&sha256, number, sizeof(number)); int32ToLittleEndian(sequenceNo_, number); SHA256_Update(&sha256, number, sizeof(number)); uint8_t sequenceDigest[ndn_SHA256_DIGEST_SIZE]; SHA256_Final(sequenceDigest, &sha256); SHA256_Init(&sha256); SHA256_Update(&sha256, &dataPrefix_[0], dataPrefix_.size()); uint8_t nameDigest[ndn_SHA256_DIGEST_SIZE]; SHA256_Final(nameDigest, &sha256); SHA256_Init(&sha256); SHA256_Update(&sha256, nameDigest, sizeof(nameDigest)); SHA256_Update(&sha256, sequenceDigest, sizeof(sequenceDigest)); uint8_t nodeDigest[ndn_SHA256_DIGEST_SIZE]; SHA256_Final(nodeDigest, &sha256); digest_ = toHex(nodeDigest, sizeof(nodeDigest)); }
std::string const& MemTrie::at(std::string const& _key) const { if (!m_root) return c_nullString; auto h = toHex(_key); return m_root->at(bytesConstRef(&h)); }
static void findBlockParent( Block *b ) { auto where = lseek64( b->chunk->getMap()->fd, b->chunk->getOffset(), SEEK_SET ); if(where!=(signed)b->chunk->getOffset()) { sysErrFatal( "failed to seek into block chain file %s", b->chunk->getMap()->name.c_str() ); } uint8_t buf[gHeaderSize]; auto nbRead = read( b->chunk->getMap()->fd, buf, gHeaderSize ); if(nbRead<(signed)gHeaderSize) { sysErrFatal( "failed to read from block chain file %s", b->chunk->getMap()->name.c_str() ); } auto i = gBlockMap.find(4 + buf); if(unlikely(gBlockMap.end()==i)) { uint8_t bHash[2*kSHA256ByteSize + 1]; toHex(bHash, b->hash); uint8_t pHash[2*kSHA256ByteSize + 1]; toHex(pHash, 4 + buf); warning( "in block %s failed to locate parent block %s", bHash, pHash ); return; } b->prev = i->second; }
Event* SystemExclusive::getAsEvent(timeT absoluteTime) const { Event *e = new Event(EventType, absoluteTime, 0, EventSubOrdering); std::string hex(toHex(m_rawData)); e->set<String>(DATABLOCK, hex); return e; }