void
BufferIODevice::addData( int block, const QByteArray& ba )
{
    Q_D( BufferIODevice );
    {
        QMutexLocker lock( &d->mut );

        while ( d->buffer.count() <= block )
            d->buffer << QByteArray();

        d->buffer.replace( block, ba );
    }

    // If this was the last block of the transfer, check if we need to fill up gaps
    if ( block + 1 == maxBlocks() )
    {
        if ( nextEmptyBlock() >= 0 )
        {
            emit blockRequest( nextEmptyBlock() );
        }
    }

    d->received += ba.count();
    emit bytesWritten( ba.count() );
    emit readyRead();
}
/*!
  Parses the \a header. This function is for internal use only.
*/
void TInternetMessageHeader::parse(const QByteArray &header)
{
    int i = 0;
    while (i < header.count()) {
        int j = header.indexOf(':', i); // field-name
        if (j < 0)
            break;

        const QByteArray field = header.mid(i, j - i).trimmed();

        // any number of LWS is allowed before and after the value
        ++j;
        QByteArray value;
        do {
            i = header.indexOf('\n', j);
            if (i < 0) {
                i = header.length();
            }

            if (!value.isEmpty())
                value += ' ';

            value += header.mid(j, i - j).trimmed();
            j = ++i;
        } while (i < header.count() && (header.at(i) == ' ' || header.at(i) == '\t'));
        
        headerPairList << qMakePair(field, value);
    }
}
Example #3
0
bool HciManager::sendCommand(OpCodeGroupField ogf, OpCodeCommandField ocf, const QByteArray &parameters)
{
    qCDebug(QT_BT_BLUEZ) << "sending command; ogf:" << ogf << "ocf:" << ocf;
    quint8 packetType = HCI_COMMAND_PKT;
    hci_command_hdr command = {
        opCodePack(ogf, ocf),
        static_cast<uint8_t>(parameters.count())
    };
    static_assert(sizeof command == 3, "unexpected struct size");
    struct iovec iv[3];
    iv[0].iov_base = &packetType;
    iv[0].iov_len  = 1;
    iv[1].iov_base = &command;
    iv[1].iov_len  = sizeof command;
    int ivn = 2;
    if (!parameters.isEmpty()) {
        iv[2].iov_base = const_cast<char *>(parameters.constData()); // const_cast is safe, since iov_base will not get modified.
        iv[2].iov_len  = parameters.count();
        ++ivn;
    }
    while (writev(hciSocket, iv, ivn) < 0) {
        if (errno == EAGAIN || errno == EINTR)
            continue;
        qCDebug(QT_BT_BLUEZ()) << "hci command failure:" << strerror(errno);
        return false;
    }
    qCDebug(QT_BT_BLUEZ) << "command sent successfully";
    return true;
}
Example #4
0
void NoSpacesProcessor::processText()
{
    QFile file(m_filename);
    if(!file.open(QIODevice::ReadOnly)) {
        emit error(tr("Could not open file %1").arg(m_filename));
        return;
    }

    const int totalLineCount = detectLineCount();
    int lineNumber(1);

    while(!file.atEnd()) {
        emit progress(lineNumber,totalLineCount,tr("Parsing text with no spaces"));
        QByteArray line = file.readLine();

        emit lineFound(line, lineNumber);

        line = line.simplified();
        if(line.isEmpty()) {
            ++lineNumber;
            continue;
        }

        for(int pos=0;pos<line.count();++pos) {
            emit progress(pos,line.count(),tr("Line %1 of %2").arg(lineNumber).arg(totalLineCount));
            for(int len=1;len<14;++len) {
                emit combinationFound(processorName(),line.mid(pos,len),lineNumber);
            }
        }
        //emit combinationFound(processorName(), word,lineNumber);
        ++lineNumber;
    }
    file.close();

}
Example #5
0
  Element IntegerGroup::EncodeBytes(const QByteArray &in) const
  {
    // We can store p bytes minus 2 bytes for padding and one more to be safe
    const int can_read = BytesPerElement();

    if(can_read < 1) qFatal("Illegal parameters");
    if(in.count() > can_read) qFatal("Cannot encode: string is too long");

    // Add initial 0xff byte and trailing 0x00 byte
    QByteArray padded;
    padded.append(0xff);
    padded.append(in.left(can_read));
    padded.append((char)0x00);
    padded.append(0xff);

    // Change byte of padded string until the
    // integer represented by the byte arry is a quadratic
    // residue. We need to be sure that every plaintext
    // message is a quadratic residue modulo p
    const int last = padded.count()-2;

    for(unsigned char pad=0x00; pad < 0xff; pad++) {
      padded[last] = pad;

      Element element(new IntegerElementData(Integer(padded)));
      if(IsElement(element)) {
        return element;
      }
    }

    qFatal("Could not encode message as quadratic residue");
    return Element(new IntegerElementData(Integer(1)));
  }
Example #6
0
TlvList Tlv::fromByteArray(const QByteArray& data, quint64 offset)
{
    TlvList list;

    QByteArray buffer = data.left(data.count() - offset);
    qint32 count = buffer.count();
    qint32 index = 0;

    while (count > index)
    {
        quint8 type = buffer.at(index);
        ++index;

        switch (type)
        {
            case Tlv::Null:
                break;

            case Tlv::Terminator:
            {
                list.append(Tlv::createTerminatorTlv());
                index = count;
            }
            break;

            default:
            {
                if ((count - index) > 0)
                {
                    quint16 length = buffer.at(index);
                    ++index;

                    if (length > 0xfe)
                    {
                        length = 0;

                        if ((count - index) > 2)
                        {
                            length = (quint8(buffer.at(index)) << 8) | quint8(buffer.at(index + 1));
                            index += 2;
                        }
                    }

                    if ((count - index) >= length)
                    {
                        list.append(Tlv(type, buffer.mid(index, length)));
                        index += length;
                    }
                    else
                    {
                        index = count;
                    }
                }
            }
            break;
        }
    }

    return list;
}
Example #7
0
bool UdpDecorator::execute(Request &req, QIODevice &io)
{
    form(req);
    io.readAll();
    io.write(req.getBody());
    QByteArray rxData;
    int cnt = 0;
    while(1) {
        int wait = 15;
        if(req.getWaitTime()!=0) wait = req.getWaitTime();
        int length=0;
        for(int i=0; i<wait; i++) {
            QThread::currentThread()->msleep(1);
            rxData+=io.readAll();
            if(rxData.count()) {
                if(length==rxData.count()) break;
                length = rxData.count();
            }
        }
        if(rxData.count()) {
            req.updateRdData(rxData);
            req.setAnswerData(rxData);
            if(checkAnAnswer(req)) {
                getAnAnswer(req);
                return true;
            }
        } else cnt++;
        if(cnt>=20) {
            req.setAnswerData(QByteArray());
            break;
        }
    }
    return false;
}
Example #8
0
  bool CppECGroup::DecodeBytes(const Element &a, QByteArray &out) const
  {
    // output value = floor( x/k )
    CryptoPP::Integer x = GetPoint(a).x;
   
    // x = floor(x/k)
    CryptoPP::Integer remainder, quotient;
    CryptoPP::Integer::Divide(remainder, quotient, x, CryptoPP::Integer(_k));

    QByteArray data = FromCppInteger(quotient).GetByteArray(); 
    if(data.count() < 2) {
      qWarning() << "Data is too short";
      return false;
    }

    const unsigned char c = 0xff;
    const unsigned char d0 = data[0];
    const unsigned char dlast = data[data.count()-1];
    if((d0 != c) || (dlast != c)) {
      qWarning() << "Data has improper padding";
      return false;
    }

    out = data.mid(1, data.count()-2);
    return true;
  }
QVariant QNearFieldTagType4Symbian::decodeResponse(const QByteArray &command, const QByteArray &response)
{
    BEGIN
    QVariant result;

    OutputByteArray(response);
    if ((command.count() > 2) && (0x00 == command.at(0)))
    {
        if ( (0xA4 == command.at(1)) || (0xD6 == command.at(1)) )
        {
            if (response.count() >= 2)
            {
                LOG("select or write command");
                QByteArray resp = response.right(2);
                result = ((resp.at(0) == 0x90) && (resp.at(1) == 0x00));
            }
        }
        else
        {
            LOG("read command");
            result = response;
        }
    }
    END
    return result;
}
void CoreMidiOutputDevice::writeSysEx(QByteArray message)
{
    if(message.isEmpty())
        return;

    if (isOpen() == false)
        return;

    int bufferSize = message.count() + 100; // Todo this is not correct

    Byte buffer[bufferSize];    // osx max=65536
    MIDIPacketList* list = (MIDIPacketList*) buffer;
    MIDIPacket* packet = MIDIPacketListInit(list);

    /* Add the MIDI command to the packet list */
    packet = MIDIPacketListAdd(list, bufferSize, packet, 0, message.count(), (Byte *)message.data());
    if (packet == 0)
    {
        qWarning() << "MIDIOut buffer overflow";
        return;
    }

    /* Send the MIDI packet list */
    OSStatus s = MIDISend(m_outPort, m_destination, list);
    if (s != 0)
        qWarning() << Q_FUNC_INFO << "Unable to send MIDI data to" << name();
}
void ServeurUdpPull::traiterRequete(QByteArray requete, QHostAddress hostAddress)
{
    if (requete.count("\r\n")>3)
    {
        struct ClientUdp nouveauClient;
        nouveauClient.addresse=hostAddress;
        nouveauClient.port = requete.split('\n')[1].trimmed().
                             split(' ')[1].trimmed().toInt();
        nouveauClient.tailleFragment = requete.split('\n')[2].trimmed().
                             split(' ')[1].trimmed().toInt();// Kev dit -64, WTF?
        nouveauClient.numImage=1;
        clientsConnectes.append(nouveauClient);
/*
        qDebug()<<clientsConnectes[0].addresse;
        qDebug()<<clientsConnectes[0].port;
        qDebug()<<clientsConnectes[0].tailleFragment;
*/
    }
    else if (requete.count("\r\n")==2)
    {
        if (requete.startsWith("END"))
        {
        //detruire le client proprement (s'il existe!!)
        }
        else
        {
            envoieImage(hostAddress);
        }
    }
}
Example #12
0
// only accept CTCPs in their simplest form, i.e. one ctcp, from start to
// end, no text around it; not as per the 'specs', but makes people happier
void CtcpParser::parseSimple(IrcEventRawMessage *e, Message::Type messagetype, QByteArray dequotedMessage, CtcpEvent::CtcpType ctcptype, Message::Flags flags)
{
    if (dequotedMessage.count(XDELIM) != 2 || dequotedMessage[0] != '\001' || dequotedMessage[dequotedMessage.count() -1] != '\001') {
        displayMsg(e, messagetype, targetDecode(e, dequotedMessage), e->prefix(), e->target(), flags);
    } else {
        int spacePos = -1;
        QString ctcpcmd, ctcpparam;

        QByteArray ctcp = xdelimDequote(dequotedMessage.mid(1, dequotedMessage.count() - 2));
        spacePos = ctcp.indexOf(' ');
        if (spacePos != -1) {
            ctcpcmd = targetDecode(e, ctcp.left(spacePos));
            ctcpparam = targetDecode(e, ctcp.mid(spacePos + 1));
        } else {
            ctcpcmd = targetDecode(e, ctcp);
            ctcpparam = QString();
        }
        ctcpcmd = ctcpcmd.toUpper();

        // we don't want to block /me messages by the CTCP ignore list
        if (ctcpcmd == QLatin1String("ACTION") || !coreSession()->ignoreListManager()->ctcpMatch(e->prefix(), e->network()->networkName(), ctcpcmd)) {
            QUuid uuid = QUuid::createUuid();
            _replies.insert(uuid, CtcpReply(coreNetwork(e), nickFromMask(e->prefix())));
            CtcpEvent *event = new CtcpEvent(EventManager::CtcpEvent, e->network(), e->prefix(), e->target(),
                ctcptype, ctcpcmd, ctcpparam, e->timestamp(), uuid);
            emit newEvent(event);
            CtcpEvent *flushEvent = new CtcpEvent(EventManager::CtcpEventFlush, e->network(), e->prefix(), e->target(),
                ctcptype, "INVALID", QString(), e->timestamp(), uuid);
            emit newEvent(flushEvent);
        }
    }
}
Example #13
0
void QHttpNetworkReplyPrivate::parseHeader(const QByteArray &header)
{
    // see rfc2616, sec 4 for information about HTTP/1.1 headers.
    // allows relaxed parsing here, accepts both CRLF & LF line endings
    const QByteArrayMatcher lf("\n");
    const QByteArrayMatcher colon(":");
    int i = 0;
    while (i < header.count()) {
        int j = colon.indexIn(header, i); // field-name
        if (j == -1)
            break;
        const QByteArray field = header.mid(i, j - i).trimmed();
        j++;
        // any number of LWS is allowed before and after the value
        QByteArray value;
        do {
            i = lf.indexIn(header, j);
            if (i == -1)
                break;
            if (!value.isEmpty())
                value += ' ';
            // check if we have CRLF or only LF
            bool hasCR = (i && header[i-1] == '\r');
            int length = i -(hasCR ? 1: 0) - j;
            value += header.mid(j, length).trimmed();
            j = ++i;
        } while (i < header.count() && (header.at(i) == ' ' || header.at(i) == '\t'));
        if (i == -1)
            break; // something is wrong

        fields.append(qMakePair(field, value));
    }
}
Example #14
0
void Server::readyRead()
{
	QTcpSocket * socket = static_cast<QTcpSocket *>(sender());
	QByteArray * buffer = _buffers.value(socket);
	qint32 size = *_sizes.value(socket);
	while(socket->bytesAvailable() > 0)
	{
		buffer->append(socket->readAll());
		// While can process data, process it
		while ((buffer->count() >= 4 && size == 0) || (buffer->count() >= size && size > 0))
		{
			// If size of data has received completely, then store it on global variable
			if (buffer->count() >= 4 && size == 0)
			{
				size = arrayToInt(buffer->mid(0, 4));
				buffer->remove(0, 4);
			}
			// If data has received completely
			if (buffer->count() >= size && size > 0)
			{
				QByteArray data = buffer->mid(0, size);
				buffer->remove(0, size);
				size = 0;
				processData(data, socket);
			}
		}
	}
}
QByteArray MultipleSequenceAlignmentRowData::toByteArray(U2OpStatus &os, qint64 length) const {
    if (length < getCoreEnd()) {
        coreLog.trace("Incorrect length was passed to MultipleSequenceAlignmentRowData::toByteArray");
        os.setError("Failed to get row data");
        return QByteArray();
    }

    if (gaps.isEmpty() && sequence.length() == length) {
        return sequence.constSequence();
    }

    QByteArray bytes = joinCharsAndGaps(true, true);

    // Append additional gaps, if necessary
    if (length > bytes.count()) {
        QByteArray gapsBytes;
        gapsBytes.fill(U2Msa::GAP_CHAR, length - bytes.count());
        bytes.append(gapsBytes);
    }
    if (length < bytes.count()) {
        // cut extra trailing gaps
        bytes = bytes.left(length);
    }

    return bytes;
}
void CIEC104DeliverQuery::SetData(const QByteArray &bytearrayFrame_)
{
    ClearBuffer();
    memcpy(m_ByteBuffer,bytearrayFrame_.data(),bytearrayFrame_.count());
    m_pBufferHead = m_ByteBuffer;
    m_nInfomationSize = bytearrayFrame_.count();
}
Example #17
0
QByteArray QDeclarativeListModelParser::compile(const QList<QDeclarativeCustomParserProperty> &customProps)
{
    QList<ListInstruction> instr;
    QByteArray data;
    listElementTypeName = QByteArray(); // unknown

    for(int ii = 0; ii < customProps.count(); ++ii) {
        const QDeclarativeCustomParserProperty &prop = customProps.at(ii);
        if(!prop.name().isEmpty()) { // isn't default property
            error(prop, QDeclarativeListModel::tr("ListModel: undefined property '%1'").arg(QString::fromUtf8(prop.name())));
            return QByteArray();
        }

        if(!compileProperty(prop, instr, data)) {
            return QByteArray();
        }
    }

    int size = sizeof(ListModelData) +
               instr.count() * sizeof(ListInstruction) +
               data.count();

    QByteArray rv;
    rv.resize(size);

    ListModelData *lmd = (ListModelData *)rv.data();
    lmd->dataOffset = sizeof(ListModelData) +
                     instr.count() * sizeof(ListInstruction);
    lmd->instrCount = instr.count();
    for (int ii = 0; ii < instr.count(); ++ii)
        lmd->instructions()[ii] = instr.at(ii);
    ::memcpy(rv.data() + lmd->dataOffset, data.constData(), data.count());

    return rv;
}
double MatchingService::getSongQuality(const QByteArray &pitchAlignment, char transposition) {
    QString alignment(pitchAlignment);

    int firstHitChord = alignment.replace(QRegExp("[mwi]"), ".").indexOf(".");
    int lastHitChord = alignment.replace(QRegExp("[mwi]"), ".").lastIndexOf(".");

    int open = pitchAlignment.count(NeedlemanWunsch::OPEN);
    int played = pitchAlignment.count(NeedlemanWunsch::MATCH);
    //int missed = pitchAlignment.count(NeedlemanWunsch::DELETED);
    int extra = pitchAlignment.count(NeedlemanWunsch::INSERT);
    int wrong = pitchAlignment.count(NeedlemanWunsch::WRONG);

    double rangeFactor = (double)(played+wrong+extra)/(double)(lastHitChord - firstHitChord + 1);
    double progressFactor = (double)(played+wrong)/(double)(played+wrong+extra+open);
    double matchFactor = (double)(played)/(double)(played+wrong+extra);

    double transpositionFactor;
    if (transposition >= 0) {
        transpositionFactor = 1.0 - transposition/1100.0;
    } else {
        transpositionFactor = 0.99 + transposition/1100.0;
    }

    double quality = rangeFactor*matchFactor*MAX2(0.9, progressFactor)*transpositionFactor;

    if (std::isinf(quality) || std::isnan(quality)) {
        return 0.0;
    } else {
        return quality;
    }
}
Example #19
0
QStringList Helper::loadTextFile(QSharedPointer<QFile> file, bool trim_lines, QChar skip_header_char, bool skip_empty_lines)
{
	QStringList output;
	while (!file->atEnd())
	{
		QByteArray line = file->readLine();

		//remove newline or trim
		if (trim_lines)
		{
			line = line.trimmed();
		}
		else
		{
			while (line.endsWith('\n') || line.endsWith('\r')) line.chop(1);
		}

		//skip empty lines
		if (skip_empty_lines && line.count()==0) continue;

		//skip header lines
		if (skip_header_char!=QChar::Null && line.count()!=0 && line[0]==skip_header_char.toLatin1()) continue;

		output.append(line);
	}

	return output;
}
Example #20
0
Note* NoteFactory::createNoteUnknown(const QMimeData *source, Basket *parent/*, const QString &annotations*/)
{
	// Save the MimeSource in a file: create and open the file:
	QString fileName = createFileForNewNote(parent, "unknown");
	QFile file(parent->fullPath() + fileName);
	if ( ! file.open(QIODevice::WriteOnly) )
		return 0L;
	QDataStream stream(&file);

	// Echo MIME types:
	QStringList formats = source->formats();
	for (int i = 0; formats.size(); ++i)
		stream << QString(formats[i]); // Output the '\0'-terminated format name string

	// Echo end of MIME types list delimiter:
	stream << "";

	// Echo the length (in bytes) and then the data, and then same for next MIME type:
	for (int i = 0; formats.size(); ++i){
		QByteArray data = source->data(formats[i]);
		stream << (quint32)data.count();
		stream.writeRawData(data.data(), data.count());
	}
	file.close();

	Note *note = new Note(parent);
	new UnknownContent(note, fileName);
	return note;
}
Example #21
0
void MainWindow::saveFile(){
	if(!fileOpened){
		QString fileName = QFileDialog::getSaveFileName(this,
			tr("Save File"),
			"untitled.xml",tr("XML files (*.xml)"));
		if(fileName!=""){
			file = new QFile(fileName);
			fileOpened = true;
		}
	}
	if(fileOpened){
		QByteArray text = textEdit->toPlainText().toLatin1();
		long bytes = -1;
		qDebug() << "Writing " << (text.count()) << "bytes to " << (file->fileName());
		file->open(QIODevice::WriteOnly);
		bytes = file->write(text);
		file->close();
		if(bytes==text.count()){
			qDebug() << "File successfully writed to " << (file->fileName());
			xmlParser = new XmlParser(text);
			glWidget->setObjects(xmlParser->getObjects());
		}else if(bytes!=-1){
			qDebug() << "Wrote " << bytes << " bytes to " << (file->fileName());
		}else{
			qDebug() << "Failed to save " << (file->fileName());
		}
	}
}
Example #22
0
 QByteArray SimpleCrypt::encryptToByteArray(QByteArray plaintext)
 {
     if (m_keyParts.isEmpty()) {
         qWarning() << "No key set.";
         m_lastError = ErrorNoKeySet;
         return QByteArray();
     }
  
  
     QByteArray ba = plaintext;
  
     CryptoFlags flags = CryptoFlagNone;
     if (m_compressionMode == CompressionAlways) {
         ba = qCompress(ba, 9); //maximum compression
         flags |= CryptoFlagCompression;
     } else if (m_compressionMode == CompressionAuto) {
         QByteArray compressed = qCompress(ba, 9);
         if (compressed.count() < ba.count()) {
             ba = compressed;
             flags |= CryptoFlagCompression;
         }
     }
  
     QByteArray integrityProtection;
     if (m_protectionMode == ProtectionChecksum) {
         flags |= CryptoFlagChecksum;
         QDataStream s(&integrityProtection, QIODevice::WriteOnly);
         s << qChecksum(ba.constData(), ba.length());
     } else if (m_protectionMode == ProtectionHash) {
         flags |= CryptoFlagHash;
         QCryptographicHash hash(QCryptographicHash::Sha1);
         hash.addData(ba);
  
         integrityProtection += hash.result();
     }
  
     //prepend a random char to the string
     char randomChar = char(qrand() & 0xFF);
     ba = randomChar + integrityProtection + ba;
  
     int pos(0);
     char lastChar(0);
  
     int cnt = ba.count();
  
     while (pos < cnt) {
         ba[pos] = ba.at(pos) ^ m_keyParts.at(pos % 8) ^ lastChar;
         lastChar = ba.at(pos);
         ++pos;
     }
  
     QByteArray resultArray;
     resultArray.append(char(0x03));  //version for future updates to algorithm
     resultArray.append(char(flags)); //encryption flags
     resultArray.append(ba);
  
     m_lastError = ErrorNoError;
     return resultArray;
 }
Example #23
0
std::vector<unsigned int> toInternalFormat(QByteArray spirvBinary)
{
    std::vector<unsigned int> data;
    auto size = spirvBinary.count() * sizeof(char) / sizeof(unsigned int);
    data.resize(size);
    memcpy(&data[0], spirvBinary.data(), spirvBinary.count());
    return data;
}
Example #24
0
bool reedSolomonCoder::encode(QByteArray &ba,QString extension,eRSType rsType)
{
  int i,j;
  unsigned char dataByte;
  QByteArray temp;
  tr_buf=ba;
  fileType=rsType;
  rs_bsize=RSBSIZE;
  switch (fileType)
    {
    case RST1: rs_dsize=RSDSIZERS1; break;
    case RST2: rs_dsize=RSDSIZERS2; break;
    case RST3: rs_dsize=RSDSIZERS3; break;
    case RST4: rs_dsize=RSDSIZERS4; break;
    case RSTNONE: return FALSE;
    }
  init_rs(rs_dsize);
  got = tr_buf.size();
  chunks = (got+7) / rs_dsize ;
  if (((got+7) % rs_dsize ) > 0) chunks++ ;
  bep_size=chunks;
//  ec_buf.resize(bep_size*RSBSIZE);
  ec_buf.clear();
  bk_buf.resize(bep_size*RSBSIZE);

  dataByte = (unsigned char) ( rs_dsize - ( got % rs_dsize)) ; /* surplus in filelength */
  ec_buf.append(dataByte);
  dataByte = (unsigned char) ( chunks % 256) ;
  ec_buf.append(dataByte);
  dataByte = (unsigned char) (chunks/256) ;
  ec_buf.append(dataByte);
  ec_buf.append(extension.toLatin1().at(0));
  ec_buf.append(extension.toLatin1().at(1));
  ec_buf.append(extension.toLatin1().at(2));
  dataByte=0;
  ec_buf.append(dataByte);
  ec_buf.append(tr_buf.left(rs_dsize-7));
  ec_buf.resize(ec_buf.count()+RSBSIZE-rs_dsize);
  rse32(((byte *)ec_buf.data()),((byte *)ec_buf.data()+(rs_dsize)));
  for (i=1;i<bep_size;i++)
    {
      temp=tr_buf.mid(i*rs_dsize-7,rs_dsize);
      if(temp.count()==0) break;
      ec_buf.append(temp);
      if(temp.count()<rs_dsize)
        {
          for(j=0;j<(rs_dsize-temp.count());j++)
            {
              ec_buf.append((char)0);
            }
        }
      ec_buf.resize(ec_buf.count()+RSBSIZE-rs_dsize);
      rse32(((byte *)ec_buf.data()+i*rs_bsize),((byte *)ec_buf.data()+i*rs_bsize+rs_dsize));
    }
  ba.resize(ec_buf.count());
  distribute((byte *)ec_buf.data(),(byte *)ba.data(),bep_size,rs_bsize,ENCODE);
  return TRUE;
}
Example #25
0
void MainWindow::on_actionFind_all_text_string_16_bit_triggered()
{
    HexEditorWidget* v = dynamic_cast<HexEditorWidget*>(ui->twHex->currentWidget());
    if (v==NULL)return;
    QByteArray br = v->data();
    QByteArray akk;
    int lastAdr=0;

    QProgressDialog * progress = new QProgressDialog(tr("Search..."), tr("Cancel"), 0, br.size(), this);
    progress->setWindowModality(Qt::WindowModal);
    progress->show();

    for(int i=0;i<=br.count()-1;i=i+2)
    {
        if (i % 1000 == 0 )
        {
            progress->setValue(i);
            QCoreApplication::processEvents ();
            if (progress->wasCanceled()) break;
        }

        unsigned char c = br[i];
        unsigned char d = br[i+1];

        bool mached = false;

        if( d >= 0x20 && d <= 0x7E && c == 0x00)
        {
            if(akk.count()==0)lastAdr=i;
            akk.append(d);
            mached = true;

        }

        if( d >= 0x20 && d <= 0x7E && c >= 0x20 && c <= 0x7E)
        {
            if(akk.count()==0)lastAdr=i;
            akk.append(d);
            akk.append(c);
            mached = true;

        }

        if(!mached)
        {
            if (akk.length()>3)
            {
                QString s;
                s.setNum(lastAdr,16);
                ui->consoleView->appendPlainText(s.toUpper() + " : \""+akk+"\"");
            }
            akk.clear();
        }
    }

    progress->close();
    delete progress;
}
Example #26
0
void tCougarIO::SetCSMSettings(tCSMSettings* pNewSettings)
{
    QByteArray bytesResponse = tCSMSettings::GetBytesFromCSMSettings(pNewSettings, CSM_SETTINGS_SIZE, true);
    unsigned short dataCRC = tSPIDataProcessing::CalculateCRC_16bits(bytesResponse);
    unsigned short dataLength = static_cast<unsigned short>(bytesResponse.count());
    QByteArray msgResponse(CSM_SETTINGS_SIZE + 10, 0);
    int index = 0;
    
    // Start Sequence
    msgResponse.data()[index++] = ((tSPIDataProcessing::MESSAGE_START_SEQUENCE & 0x00FF) >> 0);
    msgResponse.data()[index++] = ((tSPIDataProcessing::MESSAGE_START_SEQUENCE & 0xFF00) >> 8);
    
    // MsgID
#if USE_HEADER_CHECKSUM
    msgResponse.data()[index++] = (tSPIDataProcessing::MSG_ID_SET_CSM_SETTINGS & 0xFF);
    
    int headerIndex = 0;
    QByteArray HeaderData(7, 0);    
    HeaderData.data()[headerIndex++] = ((tSPIDataProcessing::MESSAGE_START_SEQUENCE & 0x00FF) >> 0);
    HeaderData.data()[headerIndex++] = ((tSPIDataProcessing::MESSAGE_START_SEQUENCE & 0xFF00) >> 8);
    HeaderData.data()[headerIndex++] = (tSPIDataProcessing::MSG_ID_SET_CSM_SETTINGS & 0xFF);
    HeaderData.data()[headerIndex++] = ((dataLength & 0x00FF) >> 0);
    HeaderData.data()[headerIndex++] = ((dataLength & 0xFF00) >> 8);
    HeaderData.data()[headerIndex++] = ((dataCRC & 0x00FF) >> 0);
    HeaderData.data()[headerIndex++] = ((dataCRC & 0xFF00) >> 8);

    if(m_CSMSoftwareVersion >= HEADER_CHECKSUM_CSM_SOFTWARE_VERSION)
        msgResponse.data()[index++] = tSPIDataProcessing::CalculateChecksum_8bits(HeaderData);
    else
        msgResponse.data()[index++] = 0;
#else
    msgResponse.data()[index++] = ((tSPIDataProcessing::MSG_ID_SET_CSM_SETTINGS & 0x00FF) >> 0);
    msgResponse.data()[index++] = ((tSPIDataProcessing::MSG_ID_SET_CSM_SETTINGS & 0xFF00) >> 8);
#endif

    // DataLenght
    msgResponse.data()[index++] = ((dataLength & 0x00FF) >> 0);
    msgResponse.data()[index++] = ((dataLength & 0xFF00) >> 8);
    
    // Data CRC 
    msgResponse.data()[index++] = ((dataCRC & 0x00FF) >> 0);
    msgResponse.data()[index++] = ((dataCRC & 0xFF00) >> 8);
    //DbgPrintf("Checksum = %x", dataCRC);

    // Data
    memcpy((msgResponse.data() + index), bytesResponse.data(), dataLength);
    index += bytesResponse.count();
    
    // End Sequence
    msgResponse.data()[index++] = ((tSPIDataProcessing::MESSAGE_END_SEQUENCE & 0x00FF) >> 0);
    msgResponse.data()[index++] = ((tSPIDataProcessing::MESSAGE_END_SEQUENCE & 0xFF00) >> 8);

    Assert(index <= msgResponse.size());

    m_DrvSPI->Write(msgResponse);
}
Example #27
0
qint64 QHttpMultiPartIODevice::readData(char *data, qint64 maxSize)
{
    qint64 bytesRead = 0, index = 0;

    // skip the parts we have already read
    while (index < multiPart->parts.count() &&
           readPointer >= partOffsets.at(index) + multiPart->parts.at(index).d->size()
           + multiPart->boundary.count() + 6) // 6 == 2 boundary dashes, \r\n after boundary, \r\n after multipart
        index++;

    // read the data
    while (bytesRead < maxSize && index < multiPart->parts.count()) {

        // check whether we need to read the boundary of the current part
        QByteArray boundaryData = "--" + multiPart->boundary + "\r\n";
        qint64 boundaryCount = boundaryData.count();
        qint64 partIndex = readPointer - partOffsets.at(index);
        if (partIndex < boundaryCount) {
            qint64 boundaryBytesRead = qMin(boundaryCount - partIndex, maxSize - bytesRead);
            memcpy(data + bytesRead, boundaryData.constData() + partIndex, boundaryBytesRead);
            bytesRead += boundaryBytesRead;
            readPointer += boundaryBytesRead;
            partIndex += boundaryBytesRead;
        }

        // check whether we need to read the data of the current part
        if (bytesRead < maxSize && partIndex >= boundaryCount && partIndex < boundaryCount + multiPart->parts.at(index).d->size()) {
            qint64 dataBytesRead = multiPart->parts[index].d->readData(data + bytesRead, maxSize - bytesRead);
            if (dataBytesRead == -1)
                return -1;
            bytesRead += dataBytesRead;
            readPointer += dataBytesRead;
            partIndex += dataBytesRead;
        }

        // check whether we need to read the ending CRLF of the current part
        if (bytesRead < maxSize && partIndex >= boundaryCount + multiPart->parts.at(index).d->size()) {
            if (bytesRead == maxSize - 1)
                return bytesRead;
            memcpy(data + bytesRead, "\r\n", 2);
            bytesRead += 2;
            readPointer += 2;
            index++;
        }
    }
    // check whether we need to return the final boundary
    if (bytesRead < maxSize && index == multiPart->parts.count()) {
        QByteArray finalBoundary = "--" + multiPart->boundary + "--\r\n";
        qint64 boundaryIndex = readPointer + finalBoundary.count() - size();
        qint64 lastBoundaryBytesRead = qMin(finalBoundary.count() - boundaryIndex, maxSize - bytesRead);
        memcpy(data + bytesRead, finalBoundary.constData() + boundaryIndex, lastBoundaryBytesRead);
        bytesRead += lastBoundaryBytesRead;
        readPointer += lastBoundaryBytesRead;
    }
    return bytesRead;
}
Example #28
0
  Element CppECGroup::EncodeBytes(const QByteArray &in) const
  {
    /*
    * See the article 
    *  "Encoding And Decoding  of  a Message in the 
    *  Implementation of Elliptic Curve Cryptography 
    *  using Koblitz’s Method" for details on how this works.
    * 
    * k == MessageSerializationParameter defines the percentage
    * chance that we won't be able to encode a given message
    * in a given elliptic curve point. The failure probability
    * is 2^(-k).
    *
    * We can store b = log_2(p/k) bytes in every 
    * elliptic curve point, where p is the security
    * parameter (prime size) of the elliptic curve.
    *
    * For p = 2^256, k = 256, b = 224 (minus 2 padding bytes)
    */

    if(in.count() > BytesPerElement()) {
      qFatal("Failed to serialize over-sized string");
    }

    // Holds the data to be encoded plus a leading and a trailing
    // 0xFF byte
    QByteArray data;
    data.append(0xff);
    data += in;
    data.append(0xff);

    // r is an encoding of the string in a big integer
    CryptoPP::Integer r(reinterpret_cast<const byte*>(data.constData()), data.count());

    //qDebug() << "r" << FromCppInteger(r)).GetByteArray().toHex();
    
    Q_ASSERT(r < _curve.FieldSize());

    Element point;
    CryptoPP::Integer x, y;
    for(int i=0; i<_k; i++) {
      // x = rk + i mod p
      x = ((r*_k)+i);

      Q_ASSERT(x < _curve.FieldSize());

      if(SolveForY(x, point)) {
        return point;
      } 
    }

    qFatal("Failed to find point");
    return Element(new CppECElementData(CryptoPP::ECPPoint()));
  }
Example #29
0
void db_base::updatePKI(pki_base *pki)
{
	db mydb(dbName);

	QByteArray ba = pki->toData();

	if (ba.count() > 0) {
		mydb.set((const unsigned char*)ba.constData(), ba.count(),
			pki->getVersion(), pki->getType(), pki->getIntName());
	}
}
Example #30
0
QByteArray prettyDigest(const QByteArray &digest)
{
    QByteArray hexDigest = digest.toHex().toUpper();
    QByteArray prettyDigest;
    prettyDigest.fill(':', hexDigest.count() + (hexDigest.count() / 2) - 1);

    for (int i = 0; i * 2 < hexDigest.count(); i++) {
        prettyDigest.replace(i * 3, 2, hexDigest.mid(i * 2, 2));
    }
    return prettyDigest;
}