예제 #1
0
파일: client.cpp 프로젝트: GoBudokai/ozifi
void TClient::AddFriend(const std::string& friendLogin) {
    if (CurrentState != CS_Connected) {
        throw UException("not connected");
    }
    string message(1, (ui8)RT_AddFriend);
    string friendKey = GenerateKey();
    TAddFriendRequest request;
    request.set_login(friendLogin);
    request.set_encryptedkey(EncryptSymmetrical(GenerateKey(State.privatekey()), friendKey));
    message += request.SerializeAsString();
    UdtClient->Send(Serialize(EncryptSymmetrical(State.sessionkey(), Compress(message))));
    TFriendRef frnd = make_shared<TFriend>(this, friendLogin, FS_Unauthorized);
    Friends.insert(pair<string, TFriendRef>(friendLogin, frnd));
    if (Config.OnFriendAdded) {
        Config.OnFriendAdded(frnd);
    }
    if (Config.FriendlistChangedCallback) {
        Config.FriendlistChangedCallback();
    }
}
예제 #2
0
int CreateSemaphore()
{
    key_t key = GenerateKey();
    int semid;
    struct sembuf mybuf;
    if ((semid = semget(key, 1, 0666 | IPC_CREAT)) < 0)
    {
        printf("Can`t get semid\n");
        exit(-1);
    }
    return semid;
}
예제 #3
0
LobbyClient::LobbyClient()
  : _sessionKey(GenerateKey(LOBBY_KEY_LENGTH))
  , _redirectCount(0)
  , _timer(CreateWaitableTimer(NULL, FALSE, NULL))
  , _state(STATE_IDLE)
{
	// setup timer
	if( !_timer || INVALID_HANDLE_VALUE == _timer )
	{
		throw std::runtime_error("lobby: failed to create waitable timer");
	}
	g_app->RegisterHandle(_timer, CreateDelegate(&LobbyClient::OnTimer, this));
}
예제 #4
0
GrVkSampler* GrVkSampler::Create(const GrVkGpu* gpu, const GrTextureParams& params,
                                 uint32_t mipLevels) {
    static VkFilter vkMinFilterModes[] = {
        VK_FILTER_NEAREST,
        VK_FILTER_LINEAR,
        VK_FILTER_LINEAR
    };
    static VkFilter vkMagFilterModes[] = {
        VK_FILTER_NEAREST,
        VK_FILTER_LINEAR,
        VK_FILTER_LINEAR
    };

    VkSamplerCreateInfo createInfo;
    memset(&createInfo, 0, sizeof(VkSamplerCreateInfo));
    createInfo.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO;
    createInfo.pNext = 0;
    createInfo.flags = 0;
    createInfo.magFilter = vkMagFilterModes[params.filterMode()];
    createInfo.minFilter = vkMinFilterModes[params.filterMode()];
    createInfo.mipmapMode = VK_SAMPLER_MIPMAP_MODE_LINEAR;
    createInfo.addressModeU = tile_to_vk_sampler_address(params.getTileModeX());
    createInfo.addressModeV = tile_to_vk_sampler_address(params.getTileModeY());
    createInfo.addressModeW = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE; // Shouldn't matter
    createInfo.mipLodBias = 0.0f;
    createInfo.anisotropyEnable = VK_FALSE;
    createInfo.maxAnisotropy = 1.0f;
    createInfo.compareEnable = VK_FALSE;
    createInfo.compareOp = VK_COMPARE_OP_NEVER;
    // Vulkan doesn't have a direct mapping of GL's nearest or linear filters for minFilter since
    // there is always a mipmapMode. To get the same effect as GL we can set minLod = maxLod = 0.0.
    // This works since our min and mag filters are the same (this forces us to use mag on the 0
    // level mip). If the filters weren't the same we could set min = 0 and max = 0.25 to force
    // the minFilter on mip level 0.
    createInfo.minLod = 0.0f;
    bool useMipMaps = GrTextureParams::kMipMap_FilterMode == params.filterMode() && mipLevels > 1;
    createInfo.maxLod = !useMipMaps ? 0.0f : (float)(mipLevels);
    createInfo.borderColor = VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK;
    createInfo.unnormalizedCoordinates = VK_FALSE;

    VkSampler sampler;
    GR_VK_CALL_ERRCHECK(gpu->vkInterface(), CreateSampler(gpu->device(),
                                                          &createInfo,
                                                          nullptr,
                                                          &sampler));

    return new GrVkSampler(sampler, GenerateKey(params, mipLevels));
}
예제 #5
0
AIBoolean DictionaryWriter::RemoveIdentifierFromDictionary(string identifier, int CAIndex)
{
    AIErr error = kNoErr;
    AIDictKey keyForIdentifier = GenerateKey(identifier, CAIndex);
    
    error = sAIDictionary->DeleteEntry(dictionary, keyForIdentifier);
    
    if (error == kNoErr)
    {
        return TRUE;
    }
    else
    {
        return FALSE;
    }
}
예제 #6
0
void idKeypad::Event_keypadopen( int value )
{
	if (state == CONFIRM_SUCCESS)
		return;

	if (value >= 1)
	{
		int i;


		GenerateKey();

		Event_PlayAnim( "opening" , 4 );

		state = ACTIVE;

		for (i = 0; i < 9; i++)
		{
			this->frobcubes[i]->isFrobbable = true;
		}

		this->frobcubeMain->GetPhysics()->SetContents(0);
	}
	else
	{
		this->frobcubeMain->GetPhysics()->SetContents( CONTENTS_RENDERMODEL );
		this->frobcubeMain->GetPhysics()->SetClipMask( MASK_SOLID | CONTENTS_MOVEABLECLIP );

		if (state == OFF)
		{
			return;
		}

		int i;
		Event_PlayAnim( "closing" , 4);

		state = OFF;

		for (i = 0; i < 9; i++)
		{
			this->frobcubes[i]->isFrobbable = false;
		}

		bluebox->Hide();
	}
}
void DataClassManager::AddTypes(Plugin* p, IDataClassFactory* f)
{
   //auto id is shared, so lock it just to make sure
   m_objectMutex.lock();
   //add all types from the factory for the plugin
   DataClassType* t;
   std::vector<FactoryTypeInfo*>::const_iterator i;
   for(i = f->GetTypeList().begin(); i != f->GetTypeList().end(); ++i)
   {
      const FactoryTypeInfo* ti = *i;
      //unique id's across types and instances
      QString fullTypeName = p->GetNamespace() + QString(".")  + ti->GetTypeName();
      t = new DataClassType(GenerateKey(), fullTypeName, ti->GetTypeName(), ti->GetKind(),ti->GetGraphics32(),DataClassType::FACTORY_TYPE_DATACLASS,(void *)f,p,ti->GetDisplayName(),ti->GetDescription(),ti->GetScriptDocumentation());

      m_typeMap.insert(std::pair<DataClassAutoId_t, DataClassType*>(t->GetId(), t));
   }
   m_objectMutex.unlock();
}
예제 #8
0
파일: client.cpp 프로젝트: GoBudokai/ozifi
void TClient::Register(const std::string& preferedPassword,
                       const std::string& email,
                       const std::string& captcha)
{
    lock_guard<mutex> guard(Lock);
    if (CurrentState != CS_Registering) {
        throw UException("not logining");
    }
    TClientRegisterPacket packet;
    packet.set_login(State.login());
    packet.set_loginpasswordhash(Hash(State.login() + preferedPassword));
    packet.set_captchatext(captcha);
    packet.set_email(email);
    packet.set_publickey(State.publickey());
    packet.set_encryptedprivatekey(EncryptSymmetrical(GenerateKey(preferedPassword), State.privatekey()));
    assert(State.has_serverpublickey() && "no server public key found");
    string data =  EncryptAsymmetrical(State.serverpublickey(), Compress(packet.SerializeAsString()));
    CurrentState = CS_RegisteringConfirmWait;
    UdtClient->Send(Serialize(data));
}
예제 #9
0
AIUIDRef DictionaryWriter::GetUIDRefFromIdentifier(string identifier, int CAIndex)
{
    AIUIDRef uidForIdentifier = NULL;
    
    AIDictKey keyForIdentifier = GenerateKey(identifier, CAIndex);
    AIEntryRef entryForIdentifier = sAIDictionary->Get(dictionary, keyForIdentifier);
    
    if (entryForIdentifier)
    {
        AIUIDREFRef uidRefForIdentifier = NULL;
        sAIEntry->ToUIDREF(entryForIdentifier, &uidRefForIdentifier);
        if (uidRefForIdentifier)
        {
            sAIUIDREF->GetUID(uidRefForIdentifier, &uidForIdentifier);
            sAIUIDREF->Release(uidRefForIdentifier);
        }
        sAIEntry->Release(entryForIdentifier);
    }
    
    return uidForIdentifier;
}
void DataClassManager::Add(DataClass* d, DataClass* owner, DataClassType* t, Workspace* ws, bool publicScope)
{
   m_objectMutex.lock();
   ++(t->m_instanceCount);
   DataClassAutoId_t key = GenerateKey();
   d->m_autoId = key;
   d->SetOwner(owner); //use function so we wire in events
   d->m_type = t;
   d->m_workspace = ws;
   d->m_publicScope = publicScope;
   d->m_uniqueId = QUuid::createUuid().toString();
   if (t->m_instanceCount == 1)
   {
      d->m_name = t->GetDisplayName();
   }
   else
   {
      d->m_name = QObject::tr("%1 %2").arg(t->GetDisplayName()).arg(t->m_instanceCount);
   }
   m_map.insert(std::pair<DataClassAutoId_t, DataClass*>(key, d));
   m_mapUniqueIds[d->m_uniqueId] = d;
   m_objectMutex.unlock();
}
예제 #11
0
/* Generate key from the 0x40-0x4c data in g_RegExt */
void WiimoteGenerateKey(wiimote_key* const key, const u8* const keydata)
{
  u8 rand[10];
  u8 skey[6];
  u8 testkey[6];
  int idx;

  for (int i = 0; i < 10; ++i)
    rand[9 - i] = keydata[i];
  for (int i = 0; i < 6; ++i)
    skey[5 - i] = keydata[i + 10];

  for (idx = 0; idx < 7; ++idx)
  {
    GenerateKey(rand, idx, testkey);
    if (0 == memcmp(testkey, skey, 6))
      break;
  }
  // default case is idx = 7 which is valid (homebrew uses it for the 0x17 case)

  GenerateTables(rand, skey, idx, key->ft, key->sb);

  // for homebrew, ft and sb are all 0x97 which is equivalent to 0x17
}
예제 #12
0
파일: main.cpp 프로젝트: Asteral/Plasma
int main(int argc, char *argv[])
{
    bool generatingKey = false;
    bool useDefault = false;
    plFileName directory;
    plString ext;

    if (argc > 1)
    {
        for (int i = 1; i < argc; i++)
        {
            std::string arg = argv[i];
            if ((arg[0] == '-')||(arg[0] == '/'))
            {
                // this arg is a flag of some kind
                arg = arg.substr(1, arg.length()); // trim the dash or slash
                if ((stricmp(arg.c_str(), "g") == 0) || (stricmp(arg.c_str(), "generate") == 0))
                {
                    if (!generatingKey)
                        generatingKey = true;
                    else
                    {
                        print_help();
                        return 0;
                    }
                }
                else if ((stricmp(arg.c_str(), "d") == 0) || (stricmp(arg.c_str(), "default") == 0))
                {
                    if (!useDefault)
                        useDefault = true;
                    else
                    {
                        print_help();
                        return 0;
                    }
                }
                else
                {
                    print_help();
                    return 0;
                }
            }
            else
            {
                // else it is a directory or extension
                if (!directory.IsValid())
                    directory = argv[i];
                else if (ext.IsEmpty())
                    ext = argv[i];
                else
                {
                    print_help();
                    return 0;
                }
            }
        }

        if (generatingKey && ((directory.IsValid()) || (!ext.IsEmpty())))
        {
            print_help();
            return 0;
        }
    }
    else
    {
        print_help();
        return 0;
    }

    if (generatingKey)
    {
        GenerateKey(useDefault);
        return 0;
    }

    // Make sure ext is a real pattern, or we won't find anything
    if (ext.CharAt(0) == '.')
        ext = "*" + ext;
    else if (ext.CharAt(0) != '*')
        ext = "*." + ext;

    if (useDefault)
        SecureFiles(directory, ext, nil);
    else
    {
        uint32_t key[4];
        plSecureStream::GetSecureEncryptionKey(plSecureStream::kKeyFilename, key, arrsize(key));
        SecureFiles(directory, ext, key);
    }
    return 0;
}
예제 #13
0
파일: Client.cpp 프로젝트: Vaion/Server
void Client::Handle_Login(const char* data, unsigned int size)
{
	if(status != cs_waiting_for_login)
	{
		server_log->Log(log_network_error, "Login recieved after already having logged in.");
		return;
	}

	if((size - 12) % 8 != 0)
	{
		server_log->Log(log_network_error, "Login recieved packet of size: %u, this would cause a block corruption, discarding.", size);
		return;
	}

	status = cs_logged_in;

	string e_user;
	string e_hash;
	char *e_buffer = NULL;
	unsigned int d_account_id = 0;
	string d_pass_hash;

#ifdef WIN32
	e_buffer = server.eq_crypto->DecryptUsernamePassword(data, size, server.options.GetEncryptionMode());
	
	int buffer_len = strlen(e_buffer);
	e_hash.assign(e_buffer, buffer_len);
	e_user.assign((e_buffer + buffer_len + 1), strlen(e_buffer + buffer_len + 1));

	if(server.options.IsTraceOn())
	{
		server_log->Log(log_client, "User: %s", e_user.c_str());
		server_log->Log(log_client, "Hash: %s", e_hash.c_str());
	}

	server.eq_crypto->DeleteHeap(e_buffer);
#else
	e_buffer = DecryptUsernamePassword(data, size, server.options.GetEncryptionMode());

	int buffer_len = strlen(e_buffer);
	e_hash.assign(e_buffer, buffer_len);
	e_user.assign((e_buffer + buffer_len + 1), strlen(e_buffer + buffer_len + 1));

	if(server.options.IsTraceOn())
	{
		server_log->Log(log_client, "User: %s", e_user.c_str());
		server_log->Log(log_client, "Hash: %s", e_hash.c_str());
	}

	_HeapDeleteCharBuffer(e_buffer);
#endif

	bool result;
	if(server.db->GetLoginDataFromAccountName(e_user, d_pass_hash, d_account_id) == false)
	{
		server_log->Log(log_client_error, "Error logging in, user %s does not exist in the database.", e_user.c_str());
		result = false;
	}
	else
	{
		if(d_pass_hash.compare(e_hash) == 0)
		{
			result = true;
		}
		else
		{
			result = false;
		}
	}

	if(result)
	{
		server.CM->RemoveExistingClient(d_account_id);
		in_addr in;
		in.s_addr = connection->GetRemoteIP();
		server.db->UpdateLSAccountData(d_account_id, string(inet_ntoa(in)));
		GenerateKey();
		account_id = d_account_id;
		account_name = e_user;

		EQApplicationPacket *outapp = new EQApplicationPacket(OP_LoginAccepted, 10 + 80);
		const LoginLoginRequest_Struct* llrs = (const LoginLoginRequest_Struct *)data;
		LoginLoginAccepted_Struct* llas = (LoginLoginAccepted_Struct *)outapp->pBuffer;
		llas->unknown1 = llrs->unknown1;
		llas->unknown2 = llrs->unknown2;
		llas->unknown3 = llrs->unknown3;
		llas->unknown4 = llrs->unknown4;
		llas->unknown5 = llrs->unknown5;

		Login_ReplyBlock_Struct * lrbs = new Login_ReplyBlock_Struct;
		memset(lrbs, 0, sizeof(Login_ReplyBlock_Struct));

		lrbs->failed_attempts = 0;
		lrbs->message = 0x01;
		lrbs->lsid = d_account_id;
		lrbs->unknown3[3] = 0x03;
		lrbs->unknown4[3] = 0x02;
		lrbs->unknown5[0] = 0xe7;
		lrbs->unknown5[1] = 0x03;
		lrbs->unknown6[0] = 0xff;
		lrbs->unknown6[1] = 0xff;
		lrbs->unknown6[2] = 0xff;
		lrbs->unknown6[3] = 0xff;
		lrbs->unknown7[0] = 0xa0;
		lrbs->unknown7[1] = 0x05;
		lrbs->unknown8[3] = 0x02;
		lrbs->unknown9[0] = 0xff;
		lrbs->unknown9[1] = 0x03;
		lrbs->unknown11[0] = 0x63;
		lrbs->unknown12[0] = 0x01;
		memcpy(lrbs->key, key.c_str(), key.size());

#ifdef WIN32
		unsigned int e_size;
		char *encrypted_buffer = server.eq_crypto->Encrypt((const char*)lrbs, 75, e_size);
		memcpy(llas->encrypt, encrypted_buffer, 80);
		server.eq_crypto->DeleteHeap(encrypted_buffer);
#else
		unsigned int e_size;
		char *encrypted_buffer = Encrypt((const char*)lrbs, 75, e_size);
		memcpy(llas->encrypt, encrypted_buffer, 80);
		_HeapDeleteCharBuffer(encrypted_buffer);
#endif

		if(server.options.IsDumpOutPacketsOn())
		{
			DumpPacket(outapp);
		}

		connection->QueuePacket(outapp);
		delete outapp;
	}
	else
	{
		EQApplicationPacket *outapp = new EQApplicationPacket(OP_LoginAccepted, sizeof(LoginLoginFailed_Struct));
		const LoginLoginRequest_Struct* llrs = (const LoginLoginRequest_Struct *)data;
		LoginLoginFailed_Struct* llas = (LoginLoginFailed_Struct *)outapp->pBuffer;
		llas->unknown1 = llrs->unknown1;
		llas->unknown2 = llrs->unknown2;
		llas->unknown3 = llrs->unknown3;
		llas->unknown4 = llrs->unknown4;
		llas->unknown5 = llrs->unknown5;
		memcpy(llas->unknown6, FailedLoginResponseData, sizeof(FailedLoginResponseData));

		if(server.options.IsDumpOutPacketsOn())
		{
			DumpPacket(outapp);
		}

		connection->QueuePacket(outapp);
		delete outapp;
	}
}
예제 #14
0
BOOL RSAKey::GenKey(DWORD dwFlags)
{
    DWORD dwBitLen;
    DWORD dwByteLen1;
    DWORD dwByteLen2;
    DWORD dwBufferSize1;
    DWORD dwBufferSize2;
    BYTE *pb;

    dwBitLen = dwFlags >> 16;

    // use the default if not specified
    if (dwBitLen == 0)
        dwBitLen = 1024;

    if ((dwBitLen % 16 != 0) || 
        (dwBitLen > 16384))
    {
        SetLastError(NTE_BAD_FLAGS);
        return FALSE;
    }
    m_dwBitLen = dwBitLen;

    dwByteLen1 = dwBitLen / 8;
    dwByteLen2 = dwByteLen1 / 2;

    dwBufferSize1 = BigNum::GetBufferSize(dwByteLen1);
    dwBufferSize2 = BigNum::GetBufferSize(dwByteLen2);

    m_dwSize = BigNum::GetBufferSize(sizeof(DWORD)) + 
            (2 * dwBufferSize1 + 5 * dwBufferSize2);
    pb = (BYTE*)malloc(m_dwSize);
    if (pb == NULL)
    {
        SetLastError(ERROR_OUTOFMEMORY);
        return FALSE;
    }
    m_pBlob = pb;

    m_pExponent = (BigNum*)pb;
    pb += BigNum::GetBufferSize(sizeof(DWORD));

static const BYTE c_DefaultExponent[4] = { 1, 0, 1, 0 };
    BigNum::SetBytes(m_pExponent, c_DefaultExponent, sizeof(DWORD));

#define HELPER(m_pMember, size) \
    m_pMember = (BigNum*)pb; \
    pb += dwBufferSize##size;

    HELPER(m_pModulus, 1);

    HELPER(m_pPrime1, 2);
    HELPER(m_pPrime2, 2);
    HELPER(m_pExponent1, 2);
    HELPER(m_pExponent2, 2);
    HELPER(m_pCoefficient, 2);
    HELPER(m_pPrivateExponent, 1);
#undef HELPER

    if (!GenerateKey())
    {
        ClearStack();
        return FALSE;
    }

    if (!CheckKey())
    {                       
        SetLastError(E_UNEXPECTED);
        _ASSERTE(false);

        ClearStack();
        return FALSE;
    }        

    GetProvider()->SetSignatureKey(this);
    return TRUE;
}
예제 #15
0
void CBibitemView::OnButtonGeygenerate() 
{
	GenerateKey();
}
예제 #16
0
GrVkSampler* GrVkSampler::Create(GrVkGpu* gpu, const GrSamplerState& samplerState,
                                 const GrVkYcbcrConversionInfo& ycbcrInfo) {
    static VkFilter vkMinFilterModes[] = {
        VK_FILTER_NEAREST,
        VK_FILTER_LINEAR,
        VK_FILTER_LINEAR
    };
    static VkFilter vkMagFilterModes[] = {
        VK_FILTER_NEAREST,
        VK_FILTER_LINEAR,
        VK_FILTER_LINEAR
    };

    VkSamplerCreateInfo createInfo;
    memset(&createInfo, 0, sizeof(VkSamplerCreateInfo));
    createInfo.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO;
    createInfo.pNext = nullptr;
    createInfo.flags = 0;
    createInfo.magFilter = vkMagFilterModes[static_cast<int>(samplerState.filter())];
    createInfo.minFilter = vkMinFilterModes[static_cast<int>(samplerState.filter())];
    createInfo.mipmapMode = VK_SAMPLER_MIPMAP_MODE_LINEAR;
    createInfo.addressModeU = wrap_mode_to_vk_sampler_address(samplerState.wrapModeX());
    createInfo.addressModeV = wrap_mode_to_vk_sampler_address(samplerState.wrapModeY());
    createInfo.addressModeW = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE; // Shouldn't matter
    createInfo.mipLodBias = 0.0f;
    createInfo.anisotropyEnable = VK_FALSE;
    createInfo.maxAnisotropy = 1.0f;
    createInfo.compareEnable = VK_FALSE;
    createInfo.compareOp = VK_COMPARE_OP_NEVER;
    // Vulkan doesn't have a direct mapping of GL's nearest or linear filters for minFilter since
    // there is always a mipmapMode. To get the same effect as GL we can set minLod = maxLod = 0.0.
    // This works since our min and mag filters are the same (this forces us to use mag on the 0
    // level mip). If the filters weren't the same we could set min = 0 and max = 0.25 to force
    // the minFilter on mip level 0.
    createInfo.minLod = 0.0f;
    bool useMipMaps = GrSamplerState::Filter::kMipMap == samplerState.filter();
    createInfo.maxLod = !useMipMaps ? 0.0f : 10000.0f;
    createInfo.borderColor = VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK;
    createInfo.unnormalizedCoordinates = VK_FALSE;

    VkSamplerYcbcrConversionInfo conversionInfo;
    GrVkSamplerYcbcrConversion* ycbcrConversion = nullptr;
    if (ycbcrInfo.isValid()) {
        SkASSERT(gpu->vkCaps().supportsYcbcrConversion());

        ycbcrConversion =
                gpu->resourceProvider().findOrCreateCompatibleSamplerYcbcrConversion(ycbcrInfo);
        if (!ycbcrConversion) {
            return nullptr;
        }

        conversionInfo.sType = VK_STRUCTURE_TYPE_SAMPLER_YCBCR_CONVERSION_INFO;
        conversionInfo.pNext = nullptr;
        conversionInfo.conversion = ycbcrConversion->ycbcrConversion();

        createInfo.pNext = &conversionInfo;

        const VkFormatFeatureFlags& flags = ycbcrInfo.fExternalFormatFeatures;

        if (!SkToBool(flags & VK_FORMAT_FEATURE_SAMPLED_IMAGE_YCBCR_CONVERSION_LINEAR_FILTER_BIT)) {
            createInfo.magFilter = VK_FILTER_NEAREST;
            createInfo.minFilter = VK_FILTER_NEAREST;
        } else if (
                !(flags &
                  VK_FORMAT_FEATURE_SAMPLED_IMAGE_YCBCR_CONVERSION_SEPARATE_RECONSTRUCTION_FILTER_BIT)) {
            createInfo.magFilter = ycbcrInfo.fChromaFilter;
            createInfo.minFilter = ycbcrInfo.fChromaFilter;
        }

        // Required values when using ycbcr conversion
        createInfo.addressModeU = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE;
        createInfo.addressModeV = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE;
        createInfo.addressModeW = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE;
        createInfo.anisotropyEnable = VK_FALSE;
        createInfo.unnormalizedCoordinates = VK_FALSE;
    }

    VkSampler sampler;
    GR_VK_CALL_ERRCHECK(gpu->vkInterface(), CreateSampler(gpu->device(),
                                                          &createInfo,
                                                          nullptr,
                                                          &sampler));

    return new GrVkSampler(sampler, ycbcrConversion, GenerateKey(samplerState, ycbcrInfo));
}
예제 #17
0
bool Registration::CheckRegistration()
{
	HKEY hKey;
	long lReturn = RegOpenKeyEx(HKEY_CURRENT_USER, g_pszPath, 0, KEY_ALL_ACCESS, &hKey);
	if (lReturn == ERROR_SUCCESS)
	{
		char szName[16];
		char szKey[20];

		SIZE_T Length = sizeof(szName);
		SIZE_T LengthKey = sizeof(szKey);
		RegQueryValueEx(hKey, "hack_username", NULL, NULL, (LPBYTE)szName, &Length);
		RegQueryValueEx(hKey, "hack_key", NULL, NULL, (LPBYTE)szKey, &LengthKey);
		RegCloseKey(hKey);

		char szCorrectKey[20];
		GenerateKey(szName, strlen(szName), szCorrectKey);

		bool bChecks[2] = {false, false};
		if (!strcmp(szCorrectKey, szKey))
		{
			bChecks[0] = true;
		}

		int iHWIDLocal = GenerateHWID(szName);

#ifndef NO_ONLINE_HWID_CHECK
		if (!CheckOnlineHwID(bChecks[1], szName, szKey, iHWIDLocal))
		{
			MessageBox(NULL, "Connection to Webserver failed. Please disable your firewall.", "Error", MB_OK | MB_ICONSTOP);
			return false;
		}
#endif


		char szInfo[128];
		sprintf_s(szInfo, sizeof(szInfo), "Your Data:\nName:\t\t%s\nSerial:\t\t%s\nHwID:\t\t%d\n--------------------\n", szName, szKey, iHWIDLocal);
		char szFullText[256];
		char *email = "*****@*****.**";

		if (bChecks[0] == true && bChecks[1] == false)
		{
#ifndef NO_ONLINE_HWID_CHECK
			sprintf_s(szFullText, sizeof(szFullText), "%sYour serial is correct but the Online-HwID Check failed!\n\nSupport: %s", szInfo, email);
#else
			sprintf_s(szFullText, sizeof(szFullText), "%sYour serial is correct and Online-HwID Check is disabled!\n\nSupport: %s", szInfo, email);
			MessageBox(NULL, szFullText, "Check-Registration: Ok", MB_OK | MB_ICONASTERISK);
			g_bRegistered = true;
			return true;
#endif
		}
		else if (bChecks[0] == true && bChecks[1] == false)
		{
			sprintf_s(szFullText, sizeof(szFullText), "%sYour serial is incorrect, but the Online-HwID Check succeded ?!?!?!\n\n Please contact support: %s", szInfo, email);
		}
		else if (bChecks[0] == false && bChecks[1] == false)
		{
			sprintf_s(szFullText, sizeof(szFullText), "%sYour serial is incorrect and the Online-HwID Check failed!\n\nSupport: %s", szInfo, email);
		}
		else if (bChecks[0] == true && bChecks[1] == true)
		{
			sprintf_s(szFullText, sizeof(szFullText), "%sYour serial is correct and Online-HwID Check succeded ;-)", szInfo);
			MessageBox(NULL, szFullText, "Check-Registration: Ok", MB_OK | MB_ICONASTERISK);
			g_bRegistered = true;
			return true;
		}
		MessageBox(NULL, szFullText, "Registration Error", MB_OK | MB_ICONSTOP);
	}
	return false;
}
예제 #18
0
void CBibitemView::OnRecordGeneratekey() 
{
	GenerateKey();
}
/*
 * Encrypts a file using AES
 */
int AesEncrypt(Aes* aes, byte* key, int size, FILE* inFile, FILE* outFile)
{
    RNG     rng;
    byte    iv[AES_BLOCK_SIZE];
    byte*   input;
    byte*   output;
    byte    salt[SALT_SIZE] = {0};

    int     i = 0;
    int     ret = 0;
    int     inputLength;
    int     length;
    int     padCounter = 0;

    fseek(inFile, 0, SEEK_END);
    inputLength = ftell(inFile);
    fseek(inFile, 0, SEEK_SET);

    length = inputLength;
    /* pads the length until it evenly matches a block / increases pad number*/
    while (length % AES_BLOCK_SIZE != 0) {
        length++;
        padCounter++;
    }

    input = malloc(length);
    output = malloc(length);

    ret = wc_InitRng(&rng);
    if (ret != 0) {
        printf("Failed to initialize random number generator\n");
        return -1030;
    }

    /* reads from inFile and writes whatever is there to the input array */
    ret = fread(input, 1, inputLength, inFile);
    if (ret == 0) {
        printf("Input file does not exist.\n");
        return -1010;
    }
    for (i = inputLength; i < length; i++) {
        /* pads the added characters with the number of pads */
        input[i] = padCounter;
    }

    ret = wc_RNG_GenerateBlock(&rng, iv, AES_BLOCK_SIZE);
    if (ret != 0)
        return -1020;

    /* stretches key to fit size */
    ret = GenerateKey(&rng, key, size, salt, padCounter);
    if (ret != 0)
        return -1040;

    /* sets key */
    ret = wc_AesSetKey(aes, key, AES_BLOCK_SIZE, iv, AES_ENCRYPTION);
    if (ret != 0)
        return -1001;

    /* encrypts the message to the output based on input length + padding */
    ret = wc_AesCbcEncrypt(aes, output, input, length);
    if (ret != 0)
        return -1005;

    /* writes to outFile */
    fwrite(salt, 1, SALT_SIZE, outFile);
    fwrite(iv, 1, AES_BLOCK_SIZE, outFile);
    fwrite(output, 1, length, outFile);

    /* closes the opened files and frees the memory*/
    memset(input, 0, length);
    memset(output, 0, length);
    memset(key, 0, size);
    free(input);
    free(output);
    free(key);
    fclose(inFile);
    fclose(outFile);
    wc_FreeRng(&rng);

    return ret;
}
예제 #20
0
파일: client.cpp 프로젝트: GoBudokai/ozifi
void TClient::OnDataReceived(const TBuffer& data) {
    switch (CurrentState) {
    case CS_Registering: {
        Buffer += data.ToString();
        string packetStr;
        if (Deserialize(Buffer, packetStr)) {
            packetStr = Decompress(packetStr);
            TServerRegisterPacket packet;
            if (!packet.ParseFromString(packetStr)) {
                ForceDisconnect();
                Config.RegisterResultCallback(RR_ConnectionFailure);
                return;
            }
            string captcha = packet.captcha();
            State.set_serverpublickey(packet.publickey());
            Config.CaptchaAvailableCallback(captcha);
        }
    } break;
    case CS_RegisteringConfirmWait: {
        Buffer += data.ToString();
        string packetStr;
        if (Deserialize(Buffer, packetStr)) {
            packetStr = Decompress(DecryptAsymmetrical(State.privatekey(), packetStr));
            if (packetStr.size() != 1) {
                ForceDisconnect();
                Config.RegisterResultCallback(RR_ConnectionFailure);
                return;
            }
            ERegisterResult registerResult;
            registerResult = (ERegisterResult)packetStr[0];
            if (registerResult == RR_Success) {
                SaveState();
            }
            ForceDisconnect();
            Config.RegisterResultCallback(registerResult);
            return;
        }
    } break;
    case CS_Logining: {
        Buffer += data.ToString();
        string packetStr;
        if (Deserialize(Buffer, packetStr)) {
            packetStr = Decompress(packetStr);
            TServerLoginPacket packet;
            if (!packet.ParseFromString(packetStr)) {
                ForceDisconnect();
                Config.LoginResultCallback(LR_ConnectionFail);
                return;
            }
            string captcha = packet.captcha();
            State.set_serverpublickey(packet.publickey());
            Config.CaptchaAvailableCallback(captcha);
        }
    } break;
    case CS_LoginingConfirmWait: {
        Buffer += data.ToString();
        string packetStr;
        if (Deserialize(Buffer, packetStr)) {
            packetStr = Decompress(packetStr);
            TServerLoginConfirm packet;
            if (!packet.ParseFromString(packetStr)) {
                ForceDisconnect();
                Config.LoginResultCallback(LR_ConnectionFail);
                return;
            }
            if (packet.result() != LR_Success) {
                ForceDisconnect();
                Config.LoginResultCallback(packet.result());
            } else {
                assert(packet.has_publickey() && "no public key in packet");
                assert(packet.has_encryptedprivatekey() && "no private key in packet");
                assert(!Password.empty() && "no password");
                State.set_publickey(packet.publickey());
                State.set_privatekey(DecryptSymmetrical(GenerateKey(Password), packet.encryptedprivatekey()));
                Password.clear();
                SaveState();
                ForceDisconnect();
                Config.LoginResultCallback(packet.result());
            }
            ForceDisconnect();
        }
    } break;
    case CS_Connecting: {
        Buffer += data.ToString();
        string packetStr;
        if (Deserialize(Buffer, packetStr)) {
            packetStr = Decompress(packetStr);
            TServerAuthorizeRequest packet;
            if (!packet.ParseFromString(packetStr)) {
                ForceDisconnect();
                Config.ConnectedCallback(false);
                return;
            }
            if (!CheckSignature(State.serverpublickey(), packet.randomsequence(), packet.signature())) {
                ForceDisconnect();
                Config.ConnectedCallback(false);
                return;
            }
            TClientAuthorizeRequest request;
            assert(State.has_login() && "no login in state");
            request.set_login(State.login());
            string hash = Hash(packet.randomsequence());
            request.set_randomsequencehash(hash);
            request.set_randomsequencehashsignature(Sign(State.privatekey(), hash));
            string response = Compress(request.SerializeAsString());
            response = Serialize(EncryptAsymmetrical(State.serverpublickey(), response));
            CurrentState = CS_ConnectingConfirmWait;
            UdtClient->Send(response);
        }
    } break;
    case CS_ConnectingConfirmWait: {
        Buffer += data.ToString();
        string packetStr;
        if (Deserialize(Buffer, packetStr)) {
            assert(State.has_privatekey());
            string sessionKey = Decompress(DecryptAsymmetrical(State.privatekey(), packetStr));
            State.set_sessionkey(sessionKey);
            CurrentState = CS_Connected;
            Config.ConnectedCallback(true);


            string response;
            response.resize(1);
            response[0] = RT_SyncMessages;
            TSyncMessagesRequest syncRequest;
            if (State.has_lastsync()) {
                syncRequest.set_from(State.lastsync());
            } else {
                syncRequest.set_from(0);
            }
            syncRequest.set_to(TDuration::Max().GetValue()); // request all messages after connection
            response += syncRequest.SerializeAsString();
            response = EncryptSymmetrical(State.sessionkey(), Compress(response));
            UdtClient->Send(Serialize(response));
        }
    } break;
    case CS_Connected: {
        Buffer += data.ToString();
        string packetStr;
        if (Deserialize(Buffer, packetStr)) {
            assert(!packetStr.empty() && "empty packet");
            packetStr = DecryptSymmetrical(State.sessionkey(), packetStr);
            assert(!packetStr.empty() && "empty decrypted");
            packetStr = Decompress(packetStr);
            assert(!packetStr.empty() && "empty decompress");
            EServerPacket packetType = (EServerPacket)packetStr[0];
            packetStr = packetStr.substr(1);
            switch (packetType) {
            case SP_FriendAlreadyExists: {
                // todo: just sync friendList if required
                // send repeated authorization request
            } break;
            case SP_FriendAdded: {
                // todo: send authorization request
            } break;
               case SP_SyncMessages: {
                TClientSyncPacket packet;
                if (!packet.ParseFromString(packetStr)) {
                    throw UException("failed to parse client sync message packet");
                }
                for (size_t i = 0; i < packet.encryptedmessages_size(); ++i) {
                    const TDirectionedMessage& currMessage = packet.encryptedmessages(i);
                    auto friendIt = Friends.find(currMessage.login());
                    if (friendIt == Friends.end()) {
                        cerr << "warning: friend login not found\n";
                        continue;
                    }
                    TFriendRef& frnd = friendIt->second;
                    frnd->OnOfflineMessageReceived(currMessage.message(), currMessage.incoming());
                }
                State.set_lastsync(packet.to());
                SaveState();
            } break;
            case SP_SyncInfo: {
                TClientSyncInfoPacket packet;
                if (!packet.ParseFromString(packetStr)) {
                    throw UException("failed to parse client sync info packet");
                }
                for (TFriendIterator it = Friends.begin(); it != Friends.end(); ++it) {
                    TFriendRef& frnd = it->second;
                    frnd->ToDelete = true;
                }
                bool friendListUpdated = false;
                for (size_t i = 0; i < packet.friends_size(); ++i) {
                    const TSyncFriend& frnd = packet.friends(i);
                    auto frndIt = Friends.find(frnd.login());
                    TFriendRef currentFrnd;
                    bool friendAdded = false;
                    if (frndIt == Friends.end()) {
                        // todo: refactor syncing
                        friendListUpdated = true;
                        friendAdded = true;
                        Friends.insert(pair<string, TFriendRef>(frnd.login(), make_shared<TFriend>(this)));
                        currentFrnd = Friends[frnd.login()];
                        currentFrnd->FullLogin = frnd.login();
                        currentFrnd->PublicKey = frnd.publickey();
                        currentFrnd->ServerPublicKey = frnd.serverpublickey();
                        currentFrnd->SelfOfflineKey = DecryptSymmetrical(GenerateKey(State.privatekey()), frnd.encryptedkey());
                        if (frnd.status() == AS_WaitingAuthorization) {
                            currentFrnd->Status = FS_AddRequest;
                            Config.FriendRequestCallback(frnd.login());
                        } else if (frnd.status() == AS_UnAuthorized) {
                            currentFrnd->Status = FS_Unauthorized;
                        } else if (frnd.status() == AS_Authorized) {
                            currentFrnd->Status = FS_Offline;
                            // todo: start trying to connect
                        } else {
                            assert(!"unknown status");
                        }
                    } else {
                        currentFrnd = frndIt->second;
                        if (currentFrnd->PublicKey.empty()) {
                            currentFrnd->PublicKey = frnd.publickey();
                        } else {
                            if (currentFrnd->PublicKey != frnd.publickey()) {
                                throw UException("public keys missmatch");
                            }
                        }
                        if (currentFrnd->SelfOfflineKey.empty()) {
                            currentFrnd->SelfOfflineKey = DecryptSymmetrical(GenerateKey(State.privatekey()), frnd.encryptedkey());
                        } else {
                            if (!frnd.encryptedkey().empty() &&
                                currentFrnd->SelfOfflineKey != DecryptSymmetrical(GenerateKey(State.privatekey()), frnd.encryptedkey()))
                            {
                                throw UException("public keys missmatch");
                            }
                        }
                        if (currentFrnd->ServerPublicKey.empty()) {
                            currentFrnd->ServerPublicKey = frnd.serverpublickey();
                        } else {
                            if (currentFrnd->ServerPublicKey != frnd.serverpublickey()) {
                                throw UException("server public keys missmatch");
                            }
                        }
                        if ((currentFrnd->Status == FS_Unauthorized ||
                             currentFrnd->Status == FS_AddRequest) &&
                                frnd.status() == AS_Authorized)
                        {
                            friendListUpdated = true;
                            currentFrnd->Status = FS_Offline;
                            // todo: start trying to connect
                        } else if (frnd.status() == AS_WaitingAuthorization) {
                            currentFrnd->Status = FS_AddRequest;
                        } else if (frnd.status() == AS_UnAuthorized) {
                            currentFrnd->Status = FS_Unauthorized;
                        }
                    }

                    if (currentFrnd->FriendOfflineKey.empty() && IsAuthorized(currentFrnd->Status)) {
                        if (frnd.has_offlinekey() && frnd.has_offlinekeysignature()) {
                            assert(!frnd.offlinekey().empty() && "empty offline key");
                            string offlineSignature = DecryptAsymmetrical(State.privatekey(), frnd.offlinekey());
                            assert(!currentFrnd->PublicKey.empty() && "no public key for friend");
                            if (!CheckSignature(currentFrnd->PublicKey, offlineSignature, frnd.offlinekeysignature())) {
                                cerr << "all bad, wrong signature\n"; // todo: normal handling
                                continue;
                            }
                            currentFrnd->FriendOfflineKey = DecryptAsymmetrical(State.privatekey(), frnd.offlinekey());
                        }
                    }

                    currentFrnd->ToDelete = false;
                    if (friendAdded && Config.OnFriendAdded) {
                        Config.OnFriendAdded(currentFrnd);
                    }

                    if (frnd.has_needofflinekey() && frnd.needofflinekey()) {
                        string response;
                        response.resize(1);
                        response[0] = RT_SetFriendOfflineKey;
                        TFriendOfflineKey offlineKeyPacket;
                        assert(!currentFrnd->PublicKey.empty() && "missing friend public key");
                        assert(!currentFrnd->SelfOfflineKey.empty() && "missing self offline key for friend");
                        offlineKeyPacket.set_offlinekey(EncryptAsymmetrical(currentFrnd->PublicKey, currentFrnd->SelfOfflineKey));
                        offlineKeyPacket.set_offlinekeysignature(Sign(State.privatekey(), currentFrnd->SelfOfflineKey));
                        offlineKeyPacket.set_login(currentFrnd->GetLogin());
                        response += offlineKeyPacket.SerializeAsString();
                        response = EncryptSymmetrical(State.sessionkey(), Compress(response));
                        UdtClient->Send(Serialize(response));
                    }
                }

                for (TFriendIterator it = Friends.begin(); it != Friends.end();) {
                    TFriendRef& frnd = it->second;
                    if (frnd->ToDelete) {
                        friendListUpdated = true;
                        if (Config.OnFriendRemoved) {
                            Config.OnFriendRemoved(frnd);
                        }
                        it = Friends.erase(it);
                    } else {
                        frnd->Connect();
                        ++it;
                    }
                }
                if (friendListUpdated && Config.FriendlistChangedCallback) {
                    Config.FriendlistChangedCallback();
                }
            } break;
            case SP_ConnectToFriend: {
                auto frndIt = Friends.find(packetStr);
                if (frndIt == Friends.end()) {
                    throw UException("no friend to connect to");
                }
                TFriendRef& frnd = frndIt->second;
                frnd->ConnectAccept();
            }
            }
        }
    } break;
    default:
        assert(false && "unknown state");
        break;
    }
}