Skip to content

Instantly share code, notes, and snippets.

@mitsuji
Created September 30, 2010 01:57
Show Gist options
  • Save mitsuji/603900 to your computer and use it in GitHub Desktop.
Save mitsuji/603900 to your computer and use it in GitHub Desktop.
#pragma comment(lib, "crypt32.lib")
#include <cstddef>
#include <string>
#include <windows.h>
#include <Wincrypt.h>
bool encrypt(const std::string& key, const std::string& plain, void* crypt, size_t* crypt_len )
{
DATA_BLOB key_bolb;
key_bolb.pbData = (BYTE*)key.c_str();
key_bolb.cbData = key.length()+1;
DATA_BLOB plain_bolb;
plain_bolb.pbData = (BYTE*)plain.c_str();
plain_bolb.cbData = plain.length()+1;
DATA_BLOB crypt_bolb; // must LocalFree
BOOL result
= CryptProtectData(
&plain_bolb,
L"",
&key_bolb,
NULL,
NULL,
0,
&crypt_bolb);
if(result)
{
*crypt_len = (size_t)crypt_bolb.cbData;
if(crypt != NULL )
::memcpy(crypt, crypt_bolb.pbData, *crypt_len);
}
LocalFree( crypt_bolb.pbData );
if(result)
return true;
else
return false;
}
bool decrypt(const std::string& key, const void* crypt, const size_t crypt_len, std::string& plain )
{
DATA_BLOB key_bolb;
key_bolb.pbData = (BYTE*)key.c_str();
key_bolb.cbData = key.length()+1;
DATA_BLOB crypt_bolb;
crypt_bolb.pbData = reinterpret_cast<BYTE*>(const_cast<void*>(crypt));
crypt_bolb.cbData = crypt_len;
DATA_BLOB plain_bolb; // must LocalFree
LPWSTR* desc = NULL; // must LocalFree
BOOL result
= CryptUnprotectData(
&crypt_bolb,
desc,
&key_bolb,
NULL,
NULL,
0,
&plain_bolb);
if(result)
{
plain = (char*)plain_bolb.pbData;
}
LocalFree( plain_bolb.pbData );
LocalFree( desc );
if(result)
return true;
else
return false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment