void Chat::runSend(const QString &msg) { bool success = true; QString message; sdc::Security s; try { QByteArray unencMsg = msg.toUtf8(); sdc::ByteSeq encMsg = s.encryptAES(key, sdc::ByteSeq(unencMsg.begin(), unencMsg.end())); sessionPrx->sendMessage(encMsg, chatID.toStdString()); } catch (const sdc::SecurityException &e) { // thrown by encryptAES success = false; message = e.what(); } catch (const sdc::MessageException &e) { // thrown by sendMessage success = false; message = e.what.c_str(); } catch (const sdc::InterServerException &e) { // thrown by sendMessage success = false; message = e.what.c_str(); } catch (...) { success = false; message = "Unexpected exception"; } emit sendCompleted(success, message); }
static QByteArray wordWrap(QByteArray string, int length) { QByteArray::iterator it = string.begin(); QByteArray::iterator lastSpace = string.begin(); int distance = 0; while (it != string.end()) { while (it != string.end() && distance <= length) { distance++; if (*it == ' ') { lastSpace = it; if (length == distance) *lastSpace = '\n'; } ++it; } if (lastSpace != string.begin()) *lastSpace = '\n'; lastSpace = string.begin(); distance = 0; } return string; }
static void emplaceString(std::map<std::string, Kdbx::XorredBuffer>& strings, const char* name, const QByteArray& data, bool protect, QWidget* widget){ if (protect){ std::vector<uint8_t> mask = getRandomBytes(data.size(), widget); strings.emplace(name, Kdbx::XorredBuffer::fromRaw(data.begin(), data.end(), mask.begin())); }else{ strings.emplace(name, Kdbx::XorredBuffer(data.begin(), data.end())); } }
void msl::updateLEDs() { qDebug() << "Updating LEDs!"; QByteArray array; array.push_back(SET_COLOR); array.push_back(DIRECT_LED); array.push_back((char)this->ui.verticalSlider_uv->value()); array.push_back((char)this->ui.verticalSlider_white->value()); array.push_back(this->colorDialog->currentColor().red()); array.push_back(this->colorDialog->currentColor().green()); array.push_back(this->colorDialog->currentColor().blue()); unsigned char checksum=0; for(QByteArray::iterator it = array.begin(); it != array.end(); ++it) { checksum^=*it; } array.push_back(checksum); //Start with AA 55 array.push_front(0x55); array.push_front(0xAA); emit sendArray(array); }
void Endpoint_v1::TicketRequest::onRequestFinished() { QByteArray respbytes = reply->readAll(); reply->deleteLater(); std::string response ( respbytes.begin(), respbytes.end() ); JSONNode respnode = libJSON::parse ( response ); JSONNode errnode = respnode.at ( "error" ); if (errnode.as_string() != "") { emit failed(QString("server_failure"), QString(errnode.as_string().c_str())); return; } available = FHttpApi::Data_GetTicketDefault; JSONNode subnode = respnode.at ("ticket"); ticket = new Ticket(); ticket->ticket = subnode.as_string().c_str(); ticket->name = _un; ticket->password = _p; subnode = respnode.at("default_character"); defaultCharacter = subnode.as_string().c_str(); subnode = respnode.at("characters"); qslFromJsonArray(subnode, characters); subnode = respnode.at("bookmarks"); qslFromJsonArray(subnode, bookmarks); emit succeeded(); }
void Preprocessor::processString(const QByteArray &str) { pp proc(d->env); d->initPP(proc); proc(str.begin(), str.end(), std::back_inserter(d->result)); }
QString AMCImporter::readImage(const QString& format_) { if(m_failed) { return QString(); } quint32 l = readInt(); if(l == 0) { return QString(); } if(l > AMC_MAX_STRING_SIZE) { myDebug() << "string is too long:" << l; m_failed = true; return QString(); } QVector<char> buffer(l+1); m_ds.readRawData(buffer.data(), l); QByteArray bytes; bytes.reserve(l); qCopy(buffer.data(), buffer.data() + l, bytes.begin()); QImage img = QImage::fromData(bytes); if(img.isNull()) { myDebug() << "null image"; return QString(); } QString format = QLatin1String("PNG"); if(format_ == QLatin1String(".jpg")) { format = QLatin1String("JPEG"); } else if(format_ == QLatin1String(".gif")) { format = QLatin1String("GIF"); } return ImageFactory::addImage(img, format); }
void decode_kio_internal(Decoder *dec, QByteArray::ConstIterator &iit, QByteArray::ConstIterator &iend, QByteArray &out) { out.resize(outbufsize); QByteArray::Iterator oit = out.begin(); QByteArray::ConstIterator oend = out.end(); while(!dec->decode(iit, iend, oit, oend)) if(oit == oend) return; while(!dec->finish(oit, oend)) if(oit == oend) return; out.truncate(oit - out.begin()); }
template <> std::vector<uint8_t> Query::get(int offset) { assert(stmt.impl && stmt.impl->query.isValid()); QByteArray byteArray = stmt.impl->query.value(offset).toByteArray(); checkQueryError(stmt.impl->query); std::vector<uint8_t> blob(byteArray.begin(), byteArray.end()); return blob; }
void UploadImpl::importButton() { QString file; file = QFileDialog::getOpenFileName(this, tr("Import Exercise Data"), "", tr("Comma separated files (*.csv *.txt);;Garmin FIT file (*.fit)")); if (!file.isEmpty()) { if ( QFileInfo(file.toLower()).suffix() == "fit") { // Garmin FIT file QFile fitFile(file); if (!fitFile.open(QIODevice::ReadOnly)) return; QByteArray blob = fitFile.readAll(); std::vector<uint8_t> fitData(blob.begin(), blob.end()); FIT fit; fit.parse (fitData, exdata); } else { // csv file ReadCSV(qPrintable(file), exdata); } if (exdata.size()) { fillList(); } } }
Discovery::TrackerResponse Discovery::TrackerResponse::fromBinary(const QByteArray &data) { MessageType type = UnknownType; QList<Peer> peers; TrackerResponse rc; if (data.startsWith("BSYNC\0")) { libtorrent::entry e = libtorrent::bdecode(data.begin()+6, data.end()); libtorrent::entry::dictionary_type dict = e.dict(); try { type = (MessageType) dict.at("m").integer(); if (dict.count("peers")) { libtorrent::entry::list_type stdPeers = dict.at("peers").list(); } PeerAddress extAddr = PeerAddress::fromBinary(dict.at("ea").string()); std::string shareHash = dict.at("share").string(); rc = TrackerResponse(type, peers, extAddr, QByteArray(shareHash.data(), shareHash.length())); } catch (std::out_of_range e) { } } return rc; }
static QByteArray deriveKeyPbkdf2(QCryptographicHash::Algorithm algorithm, const QByteArray &data, const QByteArray &salt, int iterations, quint64 dkLen) { QByteArray key; quint32 currentIteration = 1; QMessageAuthenticationCode hmac(algorithm, data); QByteArray index(4, Qt::Uninitialized); while (quint64(key.length()) < dkLen) { hmac.addData(salt); qToBigEndian(currentIteration, reinterpret_cast<uchar*>(index.data())); hmac.addData(index); QByteArray u = hmac.result(); hmac.reset(); QByteArray tkey = u; for (int iter = 1; iter < iterations; iter++) { hmac.addData(u); u = hmac.result(); hmac.reset(); std::transform(tkey.cbegin(), tkey.cend(), u.cbegin(), tkey.begin(), std::bit_xor<char>()); } key += tkey; currentIteration++; } return key.left(dkLen); }
bool Vacation::parseScript( const QString & script, QString & messageText, int & notificationInterval, QStringList & aliases, bool & sendForSpam, QString & domainName ) { if ( script.trimmed().isEmpty() ) { messageText = defaultMessageText(); notificationInterval = defaultNotificationInterval(); aliases = defaultMailAliases(); sendForSpam = defaultSendForSpam(); domainName = defaultDomainName(); return true; } // The trimmed() call below prevents parsing errors. The // slave somehow omits the last \n, which results in a lone \r at // the end, leading to a parse error. const QByteArray scriptUTF8 = script.trimmed().toUtf8(); kDebug() << "scriptUtf8 = \"" + scriptUTF8 +"\""; KSieve::Parser parser( scriptUTF8.begin(), scriptUTF8.begin() + scriptUTF8.length() ); VacationDataExtractor vdx; SpamDataExtractor sdx; DomainRestrictionDataExtractor drdx; KSieveExt::MultiScriptBuilder tsb( &vdx, &sdx, &drdx ); parser.setScriptBuilder( &tsb ); if ( !parser.parse() ) return false; messageText = vdx.messageText().trimmed(); notificationInterval = vdx.notificationInterval(); aliases = vdx.aliases(); if ( !GlobalSettings::allowOutOfOfficeUploadButNoSettings() ) { sendForSpam = !sdx.found(); domainName = drdx.domainName(); } return true; }
// ---------------------------------------------------------------------------- // transformFile // ---------------------------------------------------------------------------- void MemMappedFileAppl::transformFile() { if (m_initialized == false) return; if (m_mapped_data_1 == nullptr) return; if (m_mapped_data_2 == nullptr) return; QByteArray data; data = QByteArray::fromRawData((char*)m_mapped_data_1, MAPPING_SIZE); std::for_each(data.begin(),data.end(), [](char &n){ n = '1';}); memcpy(m_mapped_data_1, data.data(), MAPPING_SIZE); // copy back to mapped file mem ... data = QByteArray::fromRawData((char*)m_mapped_data_2, MAPPING_SIZE); std::for_each(data.begin(),data.end(), [](char &n){ n = '2';}); memcpy(m_mapped_data_2, data.data(), MAPPING_SIZE); // copy back to mapped file mem ... }
string FileName::toSafeFilesystemEncoding(os::file_access how) const { // This will work on Windows for non ascii file names. QString const safe_path = toqstr(os::safe_internal_path(absFileName(), how)); QByteArray const encoded = QFile::encodeName(safe_path); return string(encoded.begin(), encoded.end()); }
int ImageLoader::readID(const QByteArray &bytes) { QByteArray reverse = bytes; std::reverse(reverse.begin(), reverse.end()); const int id = *reinterpret_cast<int*>(reverse.data()); return id; }
Image::operator ImageBlob() const { QByteArray ba; QBuffer buffer(&ba); buffer.open(QIODevice::WriteOnly); d->image.save(&buffer, "PNG", d->quality); buffer.close(); return {ba.begin(), ba.end()}; }
QString AnalyzeTask::cleanAsciiStr(const QString &str) { QByteArray ascii = str.toLatin1(); for (QByteArray::Iterator iter = ascii.begin(); iter != ascii.end(); ++iter) { if ((*iter < 0x20) || (*iter >= 0x7F)) *iter = 0x3F; } return QString::fromLatin1(ascii).remove(QLatin1Char('?')).simplified(); }
void VersionEditor::onPasswordEdited(QString pass){ QByteArray tmp = pass.toUtf8(); ui->password = Kdbx::XorredBuffer::fromRaw(SafeVector<uint8_t>(tmp.begin(), tmp.end()), safeGetRandomBytes(tmp.size(), this)); if (ui->showPasswordButton->isChecked()){ ui->passwordLabel->setText(pass); }else{ ui->passwordLabel->setText(QString(pass.size(), QChar('*'))); } }
string const to_local8bit(docstring const & s) { // This conversion can fail, depending on input. if (s.empty()) return string(); QByteArray const local = toqstr(s).toLocal8Bit(); if (local.isEmpty()) throw to_local8bit_failure(); return string(local.begin(), local.end()); }
/* void ResrouceRim(const char* filename, PDP8::CpuState& cpu) { std::vector<char> data = GetResource(filename); PDP8::LoadRim(data,cpu); } void ResrouceBin(const char* filename, PDP8::CpuState& cpu) { std::vector<char> data = GetResource(filename); PDP8::LoadBin(data,cpu); } */ std::vector<char> MainWindow::getResource(const char* filename) { QFile s(filename); if (s.open(QFile::ReadOnly)) { QByteArray bytes = s.readAll(); std::vector<char> data(bytes.begin(), bytes.end()); return data; } throw std::runtime_error("F**K YOU"); }
static void append_lf2crlf(QByteArray &out, const QByteArray &in) { if (in.isEmpty()) { return; } const unsigned int oldOutSize = out.size(); out.resize(oldOutSize + 2 * in.size()); const char *s = in.begin(); const char *const end = in.end(); char *d = out.begin() + oldOutSize; char last = '\0'; while (s < end) { if (*s == '\n' && last != '\r') { *d++ = '\r'; } *d++ = last = *s++; } out.resize(d - out.begin()); }
void bgPNG::getb(const QByteArray &b) { qDebug("[bgPNG getb: %d, %08x]", num, (uint)th->currentThreadId()); stat = 1; vector<uchar> v(b.size()); // filled by '\0' x n for(QByteArray::ConstIterator it = b.begin(); it != b.end(); it++) v.push_back(*it); for(vector<uchar>::iterator it = v.begin(); it != v.end(); it++) cout << setw(2) << setfill('0') << hex << right << (uint)*it << ", "; cout << endl; }
void ReceiveThread::run() { QByteArray dataArray; while(true) { serialPort->waitForReadyRead(-1); dataArray = serialPort->readAll(); for(QByteArray::Iterator iter = dataArray.begin(); iter != dataArray.end(); iter++) { emit receivedDataByte(*iter); } } }
void SeedManager::addTorrent(QString torrent) { QSettings s(settingsPath + torrent, QSettings::IniFormat); QByteArray data = s.value("data").toByteArray(); libtorrent::entry e = libtorrent::bdecode(data.begin(), data.end()); libtorrent::torrent_info *inf = new libtorrent::torrent_info(e); const libtorrent::torrent_handle h = session->add_torrent(inf, s.value("path").toString().toStdString(), e); h.set_upload_mode(true); h.auto_managed(false); if (h.is_paused()) h.resume(); torrentNames[h.name()] = torrent; }
bool TestNode::invokePath (const QString &path, const QStringList &, int, HttpClient *client) { if (path == "/get") { client->write ("Works."); } else if (path == "/post") { auto func = [](HttpClient *client) { QByteArray data = client->readAll (); std::reverse (data.begin (), data.end ()); client->write (data); }; client->setSlotInfo (SlotInfo (Callback::fromLambda (func))); } // return true; }
bool QXmppSaslClientScram::respond(const QByteArray &challenge, QByteArray &response) { Q_UNUSED(challenge); if (m_step == 0) { m_gs2Header = "n,,"; m_clientFirstMessageBare = "n=" + username().toUtf8() + ",r=" + m_nonce; response = m_gs2Header + m_clientFirstMessageBare; m_step++; return true; } else if (m_step == 1) { // validate input const QMap<char, QByteArray> input = parseGS2(challenge); const QByteArray nonce = input.value('r'); const QByteArray salt = QByteArray::fromBase64(input.value('s')); const int iterations = input.value('i').toInt(); if (!nonce.startsWith(m_nonce) || salt.isEmpty() || iterations < 1) { return false; } // calculate proofs const QByteArray clientFinalMessageBare = "c=" + m_gs2Header.toBase64() + ",r=" + nonce; const QByteArray saltedPassword = deriveKeyPbkdf2(m_algorithm, password().toUtf8(), salt, iterations, m_dklen); const QByteArray clientKey = QMessageAuthenticationCode::hash("Client Key", saltedPassword, m_algorithm); const QByteArray storedKey = QCryptographicHash::hash(clientKey, m_algorithm); const QByteArray authMessage = m_clientFirstMessageBare + "," + challenge + "," + clientFinalMessageBare; QByteArray clientProof = QMessageAuthenticationCode::hash(authMessage, storedKey, m_algorithm); std::transform(clientProof.cbegin(), clientProof.cend(), clientKey.cbegin(), clientProof.begin(), std::bit_xor<char>()); const QByteArray serverKey = QMessageAuthenticationCode::hash("Server Key", saltedPassword, m_algorithm); m_serverSignature = QMessageAuthenticationCode::hash(authMessage, serverKey, m_algorithm); response = clientFinalMessageBare + ",p=" + clientProof.toBase64(); m_step++; return true; } else if (m_step == 2) { const QMap<char, QByteArray> input = parseGS2(challenge); response = QByteArray(); m_step++; return QByteArray::fromBase64(input.value('v')) == m_serverSignature; } else { warning("QXmppSaslClientPlain : Invalid step"); return false; } }
static void inplace_crlf2lf(QByteArray &in) { if (in.isEmpty()) { return; } QByteArray &out = in; // inplace const char *s = in.begin(); const char *const end = in.end(); char *d = out.begin(); char last = '\0'; while (s < end) { if (*s == '\n' && last == '\r') { --d; } *d++ = last = *s++; } out.resize(d - out.begin()); }
void encode_decode_kio(bool encode, const Codec *codec, const QByteArray &infile_buffer, QFile &outfile) { Encoder *enc = 0; Decoder *dec = 0; // Get an encoder. This one you have to delete! if(encode) { enc = codec->makeEncoder(withCRLF); assert(enc); } else { dec = codec->makeDecoder(withCRLF); assert(dec); } QByteArray::ConstIterator iit = infile_buffer.begin(); QByteArray::ConstIterator iend = infile_buffer.end(); QByteArray out; do { out = QByteArray(); if(encode) encode_kio_internal(enc, iit, iend, out); else decode_kio_internal(dec, iit, iend, out); if(writing && out.size()) { Q_LONG written = outfile.writeBlock(out); assert(written == (Q_LONG)out.size()); } } while(out.size()); if(encode) delete enc; else delete dec; }
QString BaseTranscode::transcode(const QString & inalphOrig, const QString & outalph, QByteArray input, bool caseSensitive){ QString inalph=caseSensitive?inalphOrig:inalphOrig.toLower(); const unsigned int inbase=inalph.size(); const unsigned int outbase=outalph.size(); QString ret; InfInt acc=0; InfInt base=1; for(QByteArray::iterator it=input.begin(),end=input.end();it!=end;++it){ unsigned char num=*it; acc+=base*num; base*=inbase; } while (acc > 0) { unsigned int remainder = (acc % outbase).toInt(); acc /= outbase; ret=QString(outalph.at(remainder)) % ret; } return ret; }