コード例 #1
0
ファイル: Grid.cpp プロジェクト: tgfischer/SE3313-Tron
void Grid::sendSingleTo(Socket& sock, std::string gameOver) {
	ByteArray returned;
	std::string p1(1, this->p1.value);
	std::string p2(1, this->p2.value);
	char buf[33];

	sock.Write(ByteArray(this->to_string(this->p1.x)));
	sock.Read(returned);
	sock.Write(ByteArray(this->to_string(this->p1.y)));
	sock.Read(returned);
	sock.Write(ByteArray(p1));
	sock.Read(returned);
	sock.Write(ByteArray(this->to_string(this->p2.x)));
	sock.Read(returned);
	sock.Write(ByteArray(this->to_string(this->p2.y)));
	sock.Read(returned);
	sock.Write(ByteArray(p2));
	sock.Read(returned);
	sock.Write(ByteArray(gameOver));
	sock.Read(returned);
}
コード例 #2
0
ファイル: DatabaseStore.cpp プロジェクト: Mathiasdm/i2pcpp
        DatabaseStore DatabaseStore::parse(ByteArrayConstItr &begin, ByteArrayConstItr end)
        {
            DatabaseStore ds;

            std::copy(begin, begin + 32, ds.m_key.begin());
            begin += 32;

            ds.m_type = (DataType)*(begin++);
            ds.m_replyToken = parseUint32(begin);

            if(ds.m_replyToken) {
                ds.m_replyTunnelId = parseUint32(begin);

                std::copy(begin, begin + 32, ds.m_replyGateway.begin());
                begin += 32;
            }

            uint16_t size = parseUint16(begin);

            ds.m_data = ByteArray(begin, begin + size);

            return ds;
        }
コード例 #3
0
ファイル: ConnectorMySQL.cpp プロジェクト: afa311/eddyserver
ByteArray ConnectorMySQL::Select(const ByteArray &command, ErrorCode &error_code)
{
	if (IsConnected())
	{
		mysql_real_query(&mysql_, command.data(), command.size());
		int error = mysql_errno(&mysql_);
		if (error != 0)
		{
			error_code.SetError(error, mysql_error(&mysql_));
			return ByteArray();
		}

		ByteArray bytes;
		MYSQL_RES *sql_result = mysql_store_result(&mysql_);
		mysql_stuff::Serialize(sql_result, &bytes);
		mysql_free_result(sql_result);
		return bytes;
	}
	else
	{
		throw NotConnected();
	}
}
コード例 #4
0
ファイル: tcp_socket_linux.cpp プロジェクト: ropez/pieces
ByteArray TCPSocket::read(size_t maxSize)
{
    ByteArray ba(maxSize);

    // Return empty array if size is 0
    if (maxSize == 0)
    {
        return ba;
    }

    // Read from socket
    ssize_t size = ::read(d->fd, ba.data(), ba.size());

    // Check for errors
    if (size < 0)
    {
        switch (errno)
        {
        case EAGAIN:
        case ETIMEDOUT:
            throw TimeoutException("TCPSocket::read", strerror(errno));
        case EPIPE:
            throw DisconnectedException("TCPSocket::read", strerror(errno));
        default:
            throw IOException("TCPSocket::read", strerror(errno));
        }
    }

    // If size is 0, means the socket is disconnected
    if (size == 0)
    {
        throw DisconnectedException("TCPSocket::read", "Disconnected");
    }

    // Return a byte-array of the actual read size
    return ByteArray(ba.constData(), size);
}
コード例 #5
0
ByteArray SignedPreKeyRecord::serialize() const
{
    ::std::string serialized = structure.SerializeAsString();
    return ByteArray(serialized.data(), serialized.length());
}
コード例 #6
0
ByteArray SCRAMSHA1ClientAuthenticator::getInitialBareClientMessage() const {
	std::string authenticationID = StringPrep::getPrepared(getAuthenticationID(), StringPrep::SASLPrep);
	return ByteArray(std::string("n=" + escape(authenticationID) + ",r=" + clientnonce));
}
コード例 #7
0
ファイル: Serializable.cpp プロジェクト: ngrawlings/libNRCore
 void Serializable::unserialize(const Memory &bytes) {
     ssize_t len = bytes.length();
     const char* buf = bytes.getMemory().getPtr();
     int offset = 0, cnt = 0;
     
     SERIAL_OBJECT so;
     memset(&so, 0, sizeof(SERIAL_OBJECT));
     
     while (offset < len) {
         so.type = (OBJECT_TYPE)buf[offset];
         
         switch (so.type) {
             case OBJECT_TYPE_INT8:
                 so.len = 1;
                 break;
                 
             case OBJECT_TYPE_INT16:
                 so.len = 2;
                 break;
                 
             case OBJECT_TYPE_INT32:
                 so.len = 4;
                 break;
                 
             case OBJECT_TYPE_INT64:
                 so.len = 8;
                 break;
                 
             case OBJECT_TYPE_TINY_BYTEARRAY:
             case OBJECT_TYPE_TINY_SERIALIZABLE:
                 so.len = 0;
                 memcpy(&so.len, &buf[offset+1], 1);
                 offset += 1;
                 break;
                 
             case OBJECT_TYPE_MEDIUM_BYTEARRAY:
             case OBJECT_TYPE_MEDIUM_SERIALIZABLE:
                 so.len = 0;
                 memcpy(&so.len, &buf[offset+1], 2);
                 offset += 2;
                 break;
                 
             default:
                 memcpy(&so.len, &buf[offset+1], 4);
                 offset += 4;
         }
         
         so.object = (void*)&buf[offset+1];
         
         switch (so.type) {
             case OBJECT_TYPE_INT8:
             case OBJECT_TYPE_INT16:
             case OBJECT_TYPE_INT32:
             case OBJECT_TYPE_INT64:
                 memcpy(serial_objects.get(cnt).get().object, so.object, so.len);
                 break;
                 
             case OBJECT_TYPE_TINY_SERIALIZABLE:
             case OBJECT_TYPE_MEDIUM_SERIALIZABLE:
             case OBJECT_TYPE_SERIALIZABLE:
                 reinterpret_cast<Serializable*>(serial_objects.get(cnt).get().object)->unserialize(ByteArray(so.object, (int)so.len));
                 break;
                 
             default:
                 serializedObjectLoaded(cnt, &so);
                 break;
         }
         
         cnt++;
         offset += 1+so.len;
     }
 }
コード例 #8
0
ファイル: SivCompression.cpp プロジェクト: Siv3D/OpenSiv3D
		ByteArray CompressFile(const FilePath& path, const int32 compressionLevel)
		{
			BinaryReader reader(path);

			if (!reader)
			{
				return ByteArray();
			}

			const size_t inputBufferSize = ZSTD_CStreamInSize();
			const auto pInputBuffer = std::make_unique<Byte[]>(inputBufferSize);

			const size_t outputBufferSize = ZSTD_CStreamOutSize();
			const auto pOutputBuffer = std::make_unique<Byte[]>(outputBufferSize);

			ZSTD_CStream* const cStream = ZSTD_createCStream();

			if (!cStream)
			{
				return ByteArray();
			}

			const size_t initResult = ZSTD_initCStream(cStream, compressionLevel);

			if (ZSTD_isError(initResult))
			{
				ZSTD_freeCStream(cStream);
				return ByteArray();
			}

			size_t toRead = inputBufferSize;

			Array<Byte> buffer;

			while (const size_t read = static_cast<size_t>(reader.read(pInputBuffer.get(), toRead)))
			{
				ZSTD_inBuffer input = { pInputBuffer.get(), read, 0 };

				while (input.pos < input.size)
				{
					ZSTD_outBuffer output = { pOutputBuffer.get(), outputBufferSize, 0 };
					
					toRead = ZSTD_compressStream(cStream, &output, &input);
					
					if (ZSTD_isError(toRead))
					{
						ZSTD_freeCStream(cStream);
						return ByteArray();
					}

					if (toRead > inputBufferSize)
					{
						toRead = inputBufferSize;
					}

					buffer.insert(buffer.end(), pOutputBuffer.get(), pOutputBuffer.get() + output.pos);
				}
			}

			ZSTD_outBuffer output = { pOutputBuffer.get(), outputBufferSize, 0 };

			const size_t remainingToFlush = ZSTD_endStream(cStream, &output);

			ZSTD_freeCStream(cStream);

			if (remainingToFlush)
			{
				return ByteArray();
			}

			buffer.insert(buffer.end(), pOutputBuffer.get(), pOutputBuffer.get() + output.pos);

			return ByteArray(std::move(buffer));
		}
コード例 #9
0
		ByteArray Recv()
		{ return ByteArray(Buffer.begin(), Buffer.begin() + KernelUrb.actual_length); }
コード例 #10
0
bool Process::start(const ByteArray& command, const List<ByteArray>& a, const List<ByteArray>& environ)
{
    mErrorString.clear();

    Path cmd = findCommand(command);
    if (cmd.isEmpty()) {
        mErrorString = "Command not found";
        return false;
    }
    List<ByteArray> arguments = a;
#if 0
    char *contents;
    const int read = cmd.readAll(contents, 33);

    contents[std::min(read, 32)] = '\0';
    if (read > 2 && !strncmp(contents, "#!", 2)) {
        char *newLine = strchr(contents, '\n');
        if (newLine) {
            arguments.prepend(command);
            cmd = findCommand(ByteArray(contents + 2, newLine - contents - 2));
        }
    }
#endif
    int err;

    eintrwrap(err, ::pipe(mStdIn));
    eintrwrap(err, ::pipe(mStdOut));
    eintrwrap(err, ::pipe(mStdErr));

    const char* args[arguments.size() + 2];
    args[arguments.size() + 1] = 0;
    args[0] = cmd.nullTerminated();
    int pos = 1;
    for (List<ByteArray>::const_iterator it = arguments.begin(); it != arguments.end(); ++it) {
        args[pos] = it->nullTerminated();
        //printf("arg: '%s'\n", args[pos]);
        ++pos;
    }
    const char* env[environ.size() + 1];
    env[environ.size()] = 0;
    pos = 0;
    //printf("fork, about to exec '%s'\n", cmd.nullTerminated());
    for (List<ByteArray>::const_iterator it = environ.begin(); it != environ.end(); ++it) {
        env[pos] = it->nullTerminated();
        //printf("env: '%s'\n", env[pos]);
        ++pos;
    }

    mPid = ::fork();
    if (mPid == -1) {
        //printf("fork, something horrible has happened %d\n", errno);
        // bail out
        eintrwrap(err, ::close(mStdIn[1]));
        eintrwrap(err, ::close(mStdIn[0]));
        eintrwrap(err, ::close(mStdOut[1]));
        eintrwrap(err, ::close(mStdOut[0]));
        eintrwrap(err, ::close(mStdErr[1]));
        eintrwrap(err, ::close(mStdErr[0]));
        mErrorString = "Fork failed";
        return false;
    } else if (mPid == 0) {
        //printf("fork, in child\n");
        // child, should do some error checking here really
        eintrwrap(err, ::close(mStdIn[1]));
        eintrwrap(err, ::close(mStdOut[0]));
        eintrwrap(err, ::close(mStdErr[0]));

        eintrwrap(err, ::close(STDIN_FILENO));
        eintrwrap(err, ::close(STDOUT_FILENO));
        eintrwrap(err, ::close(STDERR_FILENO));

        eintrwrap(err, ::dup2(mStdIn[0], STDIN_FILENO));
        eintrwrap(err, ::close(mStdIn[0]));
        eintrwrap(err, ::dup2(mStdOut[1], STDOUT_FILENO));
        eintrwrap(err, ::close(mStdOut[1]));
        eintrwrap(err, ::dup2(mStdErr[1], STDERR_FILENO));
        eintrwrap(err, ::close(mStdErr[1]));

        if (!mCwd.isEmpty())
            eintrwrap(err, ::chdir(mCwd.nullTerminated()));
        const int ret = ::execve(cmd.nullTerminated(), const_cast<char* const*>(args), const_cast<char* const*>(env));
        ::_exit(1);
        (void)ret;
        //printf("fork, exec seemingly failed %d, %d %s\n", ret, errno, strerror(errno));
    } else {
        ProcessThread::addPid(mPid, this);

        // parent
        eintrwrap(err, ::close(mStdIn[0]));
        eintrwrap(err, ::close(mStdOut[1]));
        eintrwrap(err, ::close(mStdErr[1]));

        //printf("fork, in parent\n");

        int flags;
        eintrwrap(flags, fcntl(mStdIn[1], F_GETFL, 0));
        eintrwrap(flags, fcntl(mStdIn[1], F_SETFL, flags | O_NONBLOCK));
        eintrwrap(flags, fcntl(mStdOut[0], F_GETFL, 0));
        eintrwrap(flags, fcntl(mStdOut[0], F_SETFL, flags | O_NONBLOCK));
        eintrwrap(flags, fcntl(mStdErr[0], F_GETFL, 0));
        eintrwrap(flags, fcntl(mStdErr[0], F_SETFL, flags | O_NONBLOCK));

        //printf("fork, about to add fds: stdin=%d, stdout=%d, stderr=%d\n", mStdIn[1], mStdOut[0], mStdErr[0]);
        EventLoop::instance()->addFileDescriptor(mStdOut[0], EventLoop::Read, processCallback, this);
        EventLoop::instance()->addFileDescriptor(mStdErr[0], EventLoop::Read, processCallback, this);
    }
    return true;
}
コード例 #11
0
	void InterfaceRequest::SetInterface(u8 alt)
	{ _device->WriteControl((u8)Type::InterfaceOut, (u8)Request::SetInterface, alt, _interface, ByteArray(), _timeout); }
コード例 #12
0
	void InterfaceRequest::SetFeature(u16 feature)
	{ _device->WriteControl((u8)Type::InterfaceOut, (u8)Request::SetFeature, feature, _interface, ByteArray(), _timeout); }
コード例 #13
0
	void DeviceRequest::SetConfiguration(u8 index)
	{ _device->WriteControl((u8)Type::DeviceOut, (u8)Request::SetConfiguration, index, 0, ByteArray(), _timeout); }
コード例 #14
0
	void DeviceRequest::SetAddress(u16 address)
	{ _device->WriteControl((u8)Type::DeviceOut, (u8)Request::SetAddress, address, 0, ByteArray(), _timeout); }
コード例 #15
0
ファイル: Nilsimsa.cpp プロジェクト: visualcortex/Foundation
		ByteArray Nilsimsa::getHashValue()
		{
			byte hash[SIZE_HASH];
			getHashValue(hash);
			return ByteArray(hash, hash + SIZE_HASH);
		}
コード例 #16
0
ファイル: file.cpp プロジェクト: KSLcom/caesaria-game
ByteArray NFile::read( unsigned int sizeToRead)
{
  return _entity.isValid() ? _entity->read( sizeToRead ) : ByteArray();
}
コード例 #17
0
ファイル: p_wcle.cpp プロジェクト: tfauck/upx
void PackWcle::preprocessFixups()
{
    big_relocs = 0;

    unsigned ic,jc;

    Array(unsigned, counts, objects+2);
    countFixups(counts);

    for (ic = jc = 0; ic < objects; ic++)
        jc += counts[ic];

    if (jc == 0)
    {
        // FIXME: implement this
        throwCantPack("files without relocations are not supported");
    }

    ByteArray(rl, jc);
    ByteArray(srf, counts[objects+0]+1);
    ByteArray(slf, counts[objects+1]+1);

    upx_byte *selector_fixups = srf;
    upx_byte *selfrel_fixups = slf;
    unsigned rc = 0;

    upx_byte *fix = ifixups;
    for (ic = jc = 0; ic < pages; ic++)
    {
        while ((unsigned)(fix - ifixups) < get_le32(ifpage_table+ic+1))
        {
            const int fixp2 = get_le16_signed(fix+2);
            unsigned value;

            switch (*fix)
            {
                case 2:       // selector fixup
                    if (fixp2 < 0)
                    {
                        // cross page selector fixup
                        dputc('S',stdout);
                        fix += 5;
                        break;
                    }
                    dputc('s',stdout);
                    memcpy(selector_fixups,"\x8C\xCB\x66\x89\x9D",5); // mov bx, cs ; mov [xxx+ebp], bx
                    if (IOT(fix[4]-1,flags) & LEOF_WRITE)
                        selector_fixups[1] = 0xDB; // ds
                    set_le32(selector_fixups+5,jc+fixp2);
                    selector_fixups += 9;
                    fix += 5;
                    break;
                case 5:       // 16-bit offset
                    if ((unsigned)fixp2 < 4096 && IOT(fix[4]-1,my_base_address) == jc)
                        dputc('6',stdout);
                    else
                        throwCantPack("unsupported 16-bit offset relocation");
                    fix += (fix[1] & 0x10) ? 9 : 7;
                    break;
                case 6:       // 16:32 pointer
                    if (fixp2 < 0)
                    {
                        // cross page pointer fixup
                        dputc('P',stdout);
                        fix += (fix[1] & 0x10) ? 9 : 7;
                        break;
                    }
                    dputc('p',stdout);
                    memcpy(iimage+jc+fixp2,fix+5,(fix[1] & 0x10) ? 4 : 2);
                    set_le32(rl+4*rc++,jc+fixp2);
                    set_le32(iimage+jc+fixp2,get_le32(iimage+jc+fixp2)+IOT(fix[4]-1,my_base_address));

                    memcpy(selector_fixups,"\x8C\xCA\x66\x89\x95",5);
                    if (IOT(fix[4]-1,flags) & LEOF_WRITE)
                        selector_fixups[1] = 0xDA; // ds
                    set_le32(selector_fixups+5,jc+fixp2+4);
                    selector_fixups += 9;
                    fix += (fix[1] & 0x10) ? 9 : 7;
                    break;
                case 7:       // 32-bit offset
                    if (fixp2 < 0)
                    {
                        fix += (fix[1] & 0x10) ? 9 : 7;
                        break;
                    }
                    //if (memcmp(iimage+jc+fixp2,fix+5,(fix[1] & 0x10) ? 4 : 2))
                    //    throwCantPack("illegal fixup offset");

                    // work around a pmwunlite bug: remove duplicated fixups
                    // FIXME: fix the other cases too
                    if (rc == 0 || get_le32(rl+4*rc-4) != jc+fixp2)
                    {
                        set_le32(rl+4*rc++,jc+fixp2);
                        set_le32(iimage+jc+fixp2,get_le32(iimage+jc+fixp2)+IOT(fix[4]-1,my_base_address));
                    }
                    fix += (fix[1] & 0x10) ? 9 : 7;
                    break;
                case 8:       // 32-bit self relative fixup
                    if (fixp2 < 0)
                    {
                        // cross page self relative fixup
                        dputc('R',stdout);
                        fix += (fix[1] & 0x10) ? 9 : 7;
                        break;
                    }
                    value = get_le32(fix+5);
                    if (fix[1] == 0)
                        value &= 0xffff;
                    set_le32(iimage+jc+fixp2,(value+IOT(fix[4]-1,my_base_address))-jc-fixp2-4);
                    set_le32(selfrel_fixups,jc+fixp2);
                    selfrel_fixups += 4;
                    dputc('r',stdout);
                    fix += (fix[1] & 0x10) ? 9 : 7;
                    break;
                default:
                    throwCantPack("unsupported fixup record");
            }
        }
        jc += mps;
    }

    // resize ifixups if it's too small
    if (sofixups < 1000)
    {
        delete[] ifixups;
        ifixups = new upx_byte[1000];
    }
    fix = optimizeReloc32 (rl,rc,ifixups,iimage,1,&big_relocs);
    has_extra_code = srf != selector_fixups;
    // FIXME: this could be removed if has_extra_code = false
    // but then we'll need a flag
    *selector_fixups++ = 0xC3; // ret
    memcpy(fix,srf,selector_fixups-srf); // copy selector fixup code
    fix += selector_fixups-srf;

    memcpy(fix,slf,selfrel_fixups-slf); // copy self-relative fixup positions
    fix += selfrel_fixups-slf;
    set_le32(fix,0xFFFFFFFFUL);
    fix += 4;

    sofixups = ptr_diff(fix, ifixups);
}
コード例 #18
0
	void EndpointRequest::SetFeature(u16 feature)
	{ _device->WriteControl((u8)Type::EnpointOut, (u8)Request::SetFeature, feature, _endpoint, ByteArray(), _timeout); }
コード例 #19
0
ファイル: ProcessParameter.cpp プロジェクト: SunGong1993/PCL
Variant ProcessParameter::DefaultValue() const
{
   if ( IsNull() )
      return Variant();

   uint32 apiType = (*API->Process->GetParameterType)( m_data->handle );
   if ( apiType == 0 )
      throw APIFunctionError( "GetParameterType" );

   apiType &= PTYPE_TYPE_MASK;

   if ( apiType == PTYPE_TABLE )
      throw Error( "ProcessParameter::DefaultValue(): Invoked for a table parameter" );

   if ( apiType == PTYPE_BLOCK )
      return ByteArray();

   if ( apiType == PTYPE_STRING )
   {
      size_type len = 0;
      (*API->Process->GetParameterDefaultValue)( m_data->handle, 0, &len );

      String value;
      if ( len > 0 )
      {
         value.SetLength( len );
         if ( (*API->Process->GetParameterDefaultValue)( m_data->handle, value.c_str(), &len ) == api_false )
            throw APIFunctionError( "GetParameterDefaultValue" );
         value.ResizeToNullTerminated();
      }
      return value;
   }

   if ( apiType == PTYPE_ENUM )
   {
      int index = (*API->Process->GetParameterDefaultElementIndex)( m_data->handle );
      if ( index < 0 )
         throw APIFunctionError( "GetParameterDefaultElementIndex" );
      return index;
   }

   union
   {
      uint8    u8;
      int8     i8;
      uint16   u16;
      int16    i16;
      uint32   u32;
      int32    i32;
      uint64   u64;
      int64    i64;
      float    f;
      double   d;
      api_bool b;
   }
   value;

   if ( (*API->Process->GetParameterDefaultValue)( m_data->handle, &value, 0 ) == api_false )
      throw APIFunctionError( "GetParameterDefaultValue" );

   switch ( apiType )
   {
   case PTYPE_UINT8:  return value.u8;
   case PTYPE_INT8:   return value.i8;
   case PTYPE_UINT16: return value.u16;
   case PTYPE_INT16:  return value.i16;
   case PTYPE_UINT32: return value.u32;
   case PTYPE_INT32:  return value.i32;
   case PTYPE_UINT64: return value.u64;
   case PTYPE_INT64:  return value.i64;
   case PTYPE_FLOAT:  return value.f;
   case PTYPE_DOUBLE: return value.d;
   case PTYPE_BOOL:   return value.b != api_false;
   default:
      throw Error( "ProcessParameter::DefaultValue(): Internal error: Unknown parameter type" );
   }
}
コード例 #20
0
ファイル: EffectManager.cpp プロジェクト: Pocsel/pocsel
 std::unique_ptr<Effect> EffectManager::CreateEffect(std::vector<char> const& effect)
 {
     return CreateEffect(ByteArray(effect));
 }
コード例 #21
0
ByteArray SmartcardSlot::decrypt(std::string &keyId, std::string &pin, ByteArray &data)
		throw (SmartcardModuleException)
{
	int rc, found = 0, nret, keySize, j, errorCode;
	PKCS11_KEY *keys;
	ByteArray ret;
    unsigned int nKeys, i;
    std::string idTmp;
    char *bufferId;
    ERR_clear_error();
    if (pin.size() < 4 || pin.size() > 8)
    {
    	throw SmartcardModuleException(SmartcardModuleException::INVALID_PIN, "SmartcardSlot::decrypt", true);
    }
	rc = PKCS11_login(this->slot, 0, pin.c_str());
	if (rc != 0)
    {
    	errorCode = ERR_GET_REASON(ERR_get_error());
    	if (errorCode == SmartcardModuleException::BLOCKED_PIN)
    	{
    		throw SmartcardModuleException(SmartcardModuleException::BLOCKED_PIN, "SmartcardSlot::decrypt", true);
    	}
    	else if (errorCode == SmartcardModuleException::INVALID_PIN)
    	{
    		throw SmartcardModuleException(SmartcardModuleException::INVALID_PIN, "SmartcardSlot::decrypt", true);
    	}
    	else
    	{
    		throw SmartcardModuleException(SmartcardModuleException::UNKNOWN, "SmartcardSlot::decrypt", true);
    	}
    }
	rc = PKCS11_enumerate_keys(this->slot[0].token, &keys, &nKeys);
	if (rc != 0 || nKeys == 0)
	{
		PKCS11_logout(this->slot);
		throw SmartcardModuleException(SmartcardModuleException::ENUMERATING_PRIVATE_KEYS, "SmartcardSlot::decrypt", true);
	}
	found = -1;
	for (i=0;(i<nKeys)&&(found==-1);i++)
	{
		bufferId = (char *)calloc((keys[i].id_len * 2) + 1, sizeof(char));
		for (j=0;j<keys[i].id_len;j++)
		{
			sprintf(&(bufferId[j*2]), "%02X", keys[i].id[j]);
		}
		idTmp = bufferId;
		free(bufferId);
        if (keyId == idTmp)
        {
            found = i;
            keySize = PKCS11_get_key_size(&keys[i]);
        }
    }
	if (found < 0)
	{
		PKCS11_logout(this->slot);
		//TODO: apagar todas as chaves encontradas, não tem na libp11
		throw SmartcardModuleException(SmartcardModuleException::ID_NOT_FOUND, "SmartcardSlot::decrypt", true);
	}
	ret = ByteArray(keySize);
    nret = PKCS11_private_decrypt(data.size(), data.getDataPointer(), ret.getDataPointer(), &keys[found], RSA_PKCS1_PADDING);
    PKCS11_logout(this->slot);
    if (nret <= 0)
    {
		throw SmartcardModuleException(SmartcardModuleException::DECRYPTING_DATA, "SmartcardSlot::decrypt", true);
    }
    ret = ByteArray(ret.getDataPointer(), nret);
    return ret;
}
コード例 #22
0
 ByteArray AbstractField::getBinaryValue()
 {
     return getBinaryValue(ByteArray());
 }
コード例 #23
0
ファイル: http_client.cpp プロジェクト: Ace17/godot
ByteArray HTTPClient::read_response_body_chunk() {

	ERR_FAIL_COND_V( status !=STATUS_BODY, ByteArray() );

	Error err=OK;

	if (chunked) {

		while(true) {

			if (chunk_left==0) {
				//reading len
				uint8_t b;
				int rec=0;
				err = connection->get_partial_data(&b,1,rec);

				if (rec==0)
					break;

				chunk.push_back(b);

				if (chunk.size()>32) {
					ERR_PRINT("HTTP Invalid chunk hex len");
					status=STATUS_CONNECTION_ERROR;
					return ByteArray();
				}

				if (chunk.size()>2 && chunk[chunk.size()-2]=='\r' && chunk[chunk.size()-1]=='\n') {

					int len=0;
					for(int i=0;i<chunk.size()-2;i++) {
						char c = chunk[i];
						int v=0;
						if (c>='0' && c<='9')
							v=c-'0';
						else if (c>='a' && c<='f')
							v=c-'a'+10;
						else if (c>='A' && c<='F')
							v=c-'A'+10;
						else {
							ERR_PRINT("HTTP Chunk len not in hex!!");
							status=STATUS_CONNECTION_ERROR;
							return ByteArray();
						}
						len<<=4;
						len|=v;
						if (len>(1<<24)) {
							ERR_PRINT("HTTP Chunk too big!! >16mb");
							status=STATUS_CONNECTION_ERROR;
							return ByteArray();
						}

					}

					if (len==0) {
						//end!
						status=STATUS_CONNECTED;
						chunk.clear();
						return ByteArray();
					}

					chunk_left=len+2;
					chunk.resize(chunk_left);

				}
			} else {

				int rec=0;
				err = connection->get_partial_data(&chunk[chunk.size()-chunk_left],chunk_left,rec);
				if (rec==0) {
					break;
				}
				chunk_left-=rec;

				if (chunk_left==0) {

					if (chunk[chunk.size()-2]!='\r' || chunk[chunk.size()-1]!='\n') {
						ERR_PRINT("HTTP Invalid chunk terminator (not \\r\\n)");
						status=STATUS_CONNECTION_ERROR;
						return ByteArray();
					}

					ByteArray ret;
					ret.resize(chunk.size()-2);
					{
						ByteArray::Write w = ret.write();
						copymem(w.ptr(),chunk.ptr(),chunk.size()-2);
					}
					chunk.clear();

					return ret;

				}

				break;
			}
		}

	} else {
		ByteArray ret;
		ret.resize(MAX(body_left,tmp_read.size()));
		ByteArray::Write w = ret.write();
		int _offset = 0;
		while (body_left > 0) {
			ByteArray::Write r = tmp_read.write();
			int rec=0;
			err = connection->get_partial_data(r.ptr(),MIN(body_left,tmp_read.size()),rec);
			if (rec>0) {
				copymem(w.ptr()+_offset,r.ptr(),rec);
				body_left-=rec;
				_offset += rec;
			}
		}
		if (body_left==0) {
			status=STATUS_CONNECTED;
		}
		return ret;

	}


	if (err!=OK) {
		close();
		if (err==ERR_FILE_EOF) {

			status=STATUS_DISCONNECTED; //server disconnected
		} else {

			status=STATUS_CONNECTION_ERROR;
		}
	} else if (body_left==0 && !chunked) {

		status=STATUS_CONNECTED;
	}

	return ByteArray();
}
コード例 #24
0
ByteArray HKDF::extract(const ByteArray &salt, const ByteArray &inputKeyMaterial) const
{
    unsigned char out[32];
	HMAC_SHA256((unsigned char*)inputKeyMaterial.c_str(), inputKeyMaterial.size(), (unsigned char*)salt.c_str(), salt.size(), out);
    return ByteArray((const char*)out, 32);
}
コード例 #25
0
ファイル: Serializable.cpp プロジェクト: ngrawlings/libNRCore
 ByteArray Serializable::serialize() {
     beforeSerialization();
     
     int len = serial_objects.length();
     LinkedListState< Ref<SERIAL_OBJECT> > objs(&serial_objects);
     
     SERIAL_OBJECT *obj;
     ByteArray ret;
     ByteArray ba_obj;
     
     for (int i=0; i<len; i++) {
         ba_obj.clear();
         obj = objs.next().getPtr();
         
         if (obj->type != OBJECT_TYPE_SERIALIZABLE)
             ba_obj.append(ByteArray((const char*)&obj->type, 1));
         
         switch (obj->type) {
             case OBJECT_TYPE_OTHER:
                 {
                     ByteArray s = serializeOther(i, obj->object);
                     ssize_t len = s.length();
                     ba_obj.append(ByteArray((const char*)&len, 4));
                     ba_obj.append(s);
                 }
                 break;
                 
             case OBJECT_TYPE_SERIALIZABLE:
                 {
                     ByteArray s = reinterpret_cast<Serializable*>(obj->object)->serialize();
                     ssize_t len = s.length();
                     
                     if (len <= 0xFF)
                         obj->type = OBJECT_TYPE_TINY_SERIALIZABLE;
                     else if (len <= 0xFFFF)
                         obj->type = OBJECT_TYPE_MEDIUM_SERIALIZABLE;
                     
                     ba_obj.append(ByteArray((const char*)&obj->type, 1));
                     
                     if (obj->type == OBJECT_TYPE_TINY_SERIALIZABLE)
                         ba_obj.append(ByteArray((const char*)&len, 1));
                     else if (obj->type == OBJECT_TYPE_MEDIUM_SERIALIZABLE)
                         ba_obj.append(ByteArray((const char*)&len, 2));
                     else
                         ba_obj.append(ByteArray((const char*)&len, 4));
                     
                     ba_obj.append(s);
                 }
                 break;
                 
             case OBJECT_TYPE_TINY_BYTEARRAY:
                 ba_obj.append(ByteArray((const char*)&obj->len, 1));
                 ba_obj.append(ByteArray((const char*)obj->object, (int)obj->len));
                 break;
                 
             case OBJECT_TYPE_MEDIUM_BYTEARRAY:
                 ba_obj.append(ByteArray((const char*)&obj->len, 2));
                 ba_obj.append(ByteArray((const char*)obj->object, (int)obj->len));
                 break;
                 
             case OBJECT_TYPE_BYTEARRAY:
                 ba_obj.append(ByteArray((const char*)&obj->len, 4));
                 ba_obj.append(ByteArray((const char*)obj->object, (int)obj->len));
                 break;
                 
             default:
                 ba_obj.append(ByteArray((const char*)obj->object, (int)obj->len));
         }
         
         ret.append(ba_obj);
     }
     
     return ret;
 }
コード例 #26
0
 ByteArray MultipleTermPositions::getPayload(ByteArray data, int32_t offset)
 {
     boost::throw_exception(UnsupportedOperationException());
     return ByteArray();
 }
コード例 #27
0
ByteArray SignedPreKeyRecord::getSignature() const
{
    ::std::string signature = structure.signature();
    return ByteArray(signature.data(), signature.length());
}
コード例 #28
0
ファイル: DatabaseSearchReply.cpp プロジェクト: HymiR/i2pcpp
		ByteArray DatabaseSearchReply::getBytes() const
		{
			return ByteArray();
		}
コード例 #29
0
ファイル: BOSHSessionStream.cpp プロジェクト: swift/swift
ByteArray BOSHSessionStream::getTLSFinishMessage() const {
    return ByteArray();
}
コード例 #30
0
ファイル: file.cpp プロジェクト: KSLcom/caesaria-game
ByteArray NFile::readLine()
{
  return _entity.isValid() ? _entity->readLine() : ByteArray();
}