First 16 bytes of AES-128 CFB-8 decryption are damaged - c++

I've been working on a project recently that should connect to a server with the help of a protocol. So far so good, but when I combed to decrypt the packages, I quickly noticed that something is not working properly.
The first 16 bytes of all packets are decrypted incorrectly. I have tried it with different libraries but that does not work either. I work in the C++ language and have so far used Crypto++ and OpenSSL for decryption, without success.
Under this Link you can find the protocol, here the decryption protocol Link and here is my corresponding code:
OpenSSL:
void init() {
unsigned char* sharedSecret = new unsigned char[AES_BLOCK_SIZE];
std::generate(sharedSecret,
sharedSecret + AES_BLOCK_SIZE,
std::bind(&RandomGenerator::GetInt, &m_RNG, 0, 255));
for (int i = 0; i < 16; i++) {
sharedSecretKey += sharedSecret[i];
}
// Initialize AES encryption and decryption
if (!(m_EncryptCTX = EVP_CIPHER_CTX_new()))
std::cout << "123" << std::endl;
if (!(EVP_EncryptInit_ex(m_EncryptCTX, EVP_aes_128_cfb8(), nullptr, (unsigned char*)sharedSecretKey.c_str(), (unsigned char*)sharedSecretKey.c_str())))
std::cout << "123" << std::endl;
if (!(m_DecryptCTX = EVP_CIPHER_CTX_new()))
std::cout << "123" << std::endl;
if (!(EVP_DecryptInit_ex(m_DecryptCTX, EVP_aes_128_cfb8(), nullptr, (unsigned char*)sharedSecretKey.c_str(), (unsigned char*)sharedSecretKey.c_str())))
std::cout << "123" << std::endl;
m_BlockSize = EVP_CIPHER_block_size(EVP_aes_128_cfb8());
}
std::string result;
int size = 0;
result.resize(1000);
EVP_DecryptUpdate(m_DecryptCTX, &((unsigned char*)result.c_str())[0], &size, &sendString[0], data.size());
Crypto++:
CryptoPP::CFB_Mode<CryptoPP::AES>::Decryption AESDecryptor((byte*)sharedSecret.c_str(), (unsigned int)16, sharedSecret.c_str(), 1);
std::string sTarget("");
CryptoPP::StringSource ss(data, true, new CryptoPP::StreamTransformationFilter(AESDecryptor, new CryptoPP::StringSink(sTarget)));
I think important to mention is that I use one and the same shared secret for the key and the iv (initialization vector). In other posts, this was often labeled as a problem. I do not know how to fix it in this case because the protocol want it.
I would be looking forward to a constructive feedback.

EVP_EncryptInit_ex(m_EncryptCTX, EVP_aes_128_cfb8(), nullptr,
(unsigned char*)sharedSecretKey.c_str(), (unsigned char*)sharedSecretKey.c_str()))
And:
CFB_Mode<AES>::Decryption AESDecryptor((byte*)sharedSecret.c_str(),
(unsigned int)16, sharedSecret.c_str(), 1);
std::string sTarget("");
StringSource ss(data, true, new StreamTransformationFilter(AESDecryptor, new StringSink(sTarget)));
It is not readily apparent, but you need to set feedback size for the mode of operation of the block cipher in Crypto++. The Crypto++ feedback size is 128 by default.
The code to set the feedback size of CFB mode can be found at CFB Mode on the Crypto++ wiki. You want the 3rd or 4th example down the page.
AlgorithmParameters params =
MakeParameters(Name::FeedbackSize(), 1 /*8-bits*/)
(Name::IV(), ConstByteArrayParameter(iv));
That is kind of an awkward way to pass parameters. It is documented in the sources files and on the wiki at NameValuePairs. It allows you to pass arbitrary parameters through consistent interfaces. It is powerful once you acquire a taste for it.
And then use params to key the encryptor and decryptor:
CFB_Mode< AES >::Encryption enc;
enc.SetKey( key, key.size(), params );
// CFB mode must not use padding. Specifying
// a scheme will result in an exception
StringSource ss1( plain, true,
new StreamTransformationFilter( enc,
new StringSink( cipher )
) // StreamTransformationFilter
); // StringSource
I believe your calls would look something like this (if I am parsing the OpenSSL correctly):
const byte* ptr = reinterpret_cast<const byte*>(sharedSecret.c_str());
AlgorithmParameters params =
MakeParameters(Name::FeedbackSize(), 1 /*8-bits*/)
(Name::IV(), ConstByteArrayParameter(ptr, 16));
CFB_Mode< AES >::Encryption enc;
enc.SetKey( ptr, 16, params );
In your production code you should use unique key and iv. So do something like this using HKDF:
std::string seed(AES_BLOCK_SIZE, '0');
std::generate(seed, seed + AES_BLOCK_SIZE,
std::bind(&RandomGenerator::GetInt, &m_RNG, 0, 255));
SecByteBlock sharedSecret(32);
const byte usage[] = "Key and IV v1";
HKDF<SHA256> hkdf;
hkdf.DeriveKey(sharedSecret, 32, &seed[0], 16, usage, COUNTOF(usage), nullptr, 0);
AlgorithmParameters params =
MakeParameters(Name::FeedbackSize(), 1 /*8-bits*/)
(Name::IV(), ConstByteArrayParameter(sharedSecret+16, 16));
CFB_Mode< AES >::Encryption enc;
enc.SetKey(sharedSecret+0, 0, params);
In the code above, sharedSecret is twice as large as it needs to be. You derive the key and iv from the seed using HDKF. sharedSecret+0 is the 16-byte key, and sharedSecret+16 is the 16-byte iv.

Related

How to generate a secure random STRING (Key and IV) for AES-256-CBC WinApi ? [C/C++]

I need to generate (in C/C++) a secure random string (32byte) to use as Key and another (16byte) to use as IV for AES-256-CBC encryption using WinApi. The problem is that I need to save the generated string in a text file in order to manually test the decryption using OpenSSL in terminal.
What can I use to generate the secure random string other than CryptGenRandom? The problem of CryptGenRandom is that it generates a random byte sequence that I can't save/use as OpenSSL input because it's not an ASCII text:
openssl aes-256-cbc -d -K "..." -iv ".." -in encrypted.txt
Is there an alternative?
This is my working code:
// handles for csp and key
HCRYPTPROV hProv = NULL;
HCRYPTKEY hKey = NULL;
BYTE *szKey = (BYTE*)calloc(DEFAULT_AES_KEY_SIZE + 1, sizeof(BYTE));
BYTE *szIV = (BYTE*)calloc(DEFAULT_IV_SIZE + 1, sizeof(BYTE));
char* ciphertext= 0;
DWORD dwPlainSize = lstrlenA(*plaintext), dwBufSize = 0;
AES256KEYBLOB AESBlob;
memset(&AESBlob, 0, sizeof(AESBlob));
// initalize key and plaintext
StrCpyA((LPSTR)szKey, "00112233445566778899001122334455");
StrCpyA((LPSTR)szIV, "4455667788990011");
// generate key & IV
//if (!CryptGenRandom(hProv, DEFAULT_AES_KEY_SIZE, szKey)) {goto error;}
//if (!CryptGenRandom(hProv, DEFAULT_IV_SIZE, szIV)) {goto error;}
// blob data for CryptImportKey() function (include key and version and so on...)
AESBlob.bhHdr.bType = PLAINTEXTKEYBLOB;
AESBlob.bhHdr.bVersion = CUR_BLOB_VERSION;
AESBlob.bhHdr.reserved = 0;
AESBlob.bhHdr.aiKeyAlg = CALG_AES_256;
AESBlob.dwKeySize = DEFAULT_AES_KEY_SIZE;
StrCpyA((LPSTR)AESBlob.szBytes, (LPCSTR)szKey);
// create a cryptographic service provider (CSP)
if (!CryptAcquireContextA(&hProv, NULL, MS_ENH_RSA_AES_PROV_A, PROV_RSA_AES, CRYPT_VERIFYCONTEXT)) {goto error;}
// populate crypto provider (CSP)
if (!CryptImportKey(hProv, (BYTE*)&AESBlob, sizeof(AES256KEYBLOB), NULL, CRYPT_EXPORTABLE, &hKey)) { goto error; }
if (!CryptSetKeyParam(hKey, KP_IV, szIV, 0)) { goto error; }
// ciphertext allocation
dwBufSize = BUFFER_FOR_PLAINTEXT + dwPlainSize;
ciphertext = (char*)calloc(dwBufSize, sizeof(char));
memcpy_s(ciphertext, dwBufSize, *plaintext, dwPlainSize);
// encryption
if (!CryptEncrypt(hKey, NULL, TRUE, 0, (BYTE*)ciphertext, &dwPlainSize, dwBufSize) ) { goto error; }
The key and IV are given to OpenSSL as hexadecimal. There's no need to generate visible ASCII characters only. You could have figured that out yourself just by pretending that the generated key and IV was "Hello". You get an error message that's pretty helpful.
$> openssl aes-256-cbc -d -K Hello -iv Hello
hex string is too short, padding with zero bytes to length
non-hex digit
invalid hex iv value
And hey, look at your code,
// initalize key and plaintext
StrCpyA((LPSTR)szKey, "00112233445566778899001122334455");
StrCpyA((LPSTR)szIV, "4455667788990011");
These string are not only ASCII text, they happen to be hex as well. It looks to as if you just need to convert hex to bytes in your code or convert bytes to a hex string if you have the bytes in code and want to generate the command line.

Properly Decrypt AES in GCM mode in Crypto++

I've been trying to encrypt and decrypt a file using AES in GCM mode using Crypto++. What this code is supposed to do is, given a password, hash it using PBKDF2< HMAC< SHA256>>, then encrypt and decrypt a file using the password hash as the key. After searching all over on Stack Overflow I've gotten this far:
using namespace Cryptopp;
const std::string password = "password";
const int iterations = 1000000;
const std::string fileName = "test.txt";
SecByteBlock derived(32);
SecByteBlock salt(16);
const int TAG_SIZE = AES::BLOCKSIZE;
AutoSeededRandomPool rng;
rng.GenerateBlock(salt, 16);
// KDF function
PKCS5_PBKDF2_HMAC<SHA256> kdf;
kdf.DeriveKey(
derived.data(),
derived.size(),
0,
(byte*)password.data(),
password.size(),
salt.data(),
salt.size(),
iterations);
// Key the cipher
GCM<AES>::Encryption encryptor;
encryptor.SetKeyWithIV(derived.data(), 16, derived.data() + 16, 16);
FileSource(fileName.c_str(), true,
new AuthenticatedEncryptionFilter(encryptor,
new FileSink(fileName.c_str()), false, TAG_SIZE));
// Key the cipher
GCM<AES>::Decryption decryptor;
decryptor.SetKeyWithIV(derived.data(), 16, derived.data() + 16, 16);
AuthenticatedDecryptionFilter decryptionFilter(decryptor,
new FileSink(fileName.c_str()), 16, TAG_SIZE);
FileSource(fileName.c_str(), true, new Redirector(decryptionFilter));
If the use of half of the derived hash from PBKDF2 as the key and half as the IV seems weird, this code is largely copied from How to use a custom key in Crypto++. Is this good practice in cryptography? Or should I generate a separate IV every time I encrypt?
Crypto++ throws a HashVerificationFailed exception, meaning the data was changed since encryption. So obviously I'm doing something wrong. What's wrong with my code?

OpenSSL AES_cfb128_encrypt public/private key C++

I have very basic encrypt/decrypt application that uses constant key. How to make this application to work with public/private key? Is it enough to generate keys with openssl and use them in my code variable ckey?
Can I somehow generate keys with my library?
#include "stdafx.h"
#include <openssl/aes.h>
#include <algorithm>
#include <iostream>
int _tmain(int argc, _TCHAR* argv[])
{
int bytes_read, bytes_written;
unsigned char indata[AES_BLOCK_SIZE + 1];
unsigned char outdata[AES_BLOCK_SIZE + 1];
std::fill(indata, indata + AES_BLOCK_SIZE, 0);
std::fill(outdata, outdata + AES_BLOCK_SIZE, 0);
/* ckey and ivec are the two 128-bits keys necesary to
en- and recrypt your data. Note that ckey can be
192 or 256 bits as well */
unsigned char ckey[] = "thiskeyisverybad";
const char ivecstr[AES_BLOCK_SIZE] = "goodbyworldkey\0";
unsigned char ivec[] = "dontusethisinput";
/* data structure that contains the key itself */
AES_KEY key;
/* set the encryption key */
AES_set_encrypt_key(ckey, 128, &key);
/* set where on the 128 bit encrypted block to begin encryption*/
int num = 0;
FILE* ifp;
FILE* oefp;
FILE* odfp;
ifp = fopen("infile.txt", "r");
if (ifp == NULL) perror("Error opening file");
oefp = fopen("outEncryptfile.txt", "w");
if (oefp == NULL) perror("Error opening file");
odfp = fopen("outDecryptfile.txt", "w");
if (odfp == NULL) perror("Error opening file");
int b = 0;
int w = 0;
memcpy(ivec, ivecstr, AES_BLOCK_SIZE);
while (1)
{
std::fill(indata, indata + AES_BLOCK_SIZE, 0);
bytes_read = fread(indata, 1, AES_BLOCK_SIZE, ifp);
b = b + bytes_read;
indata[AES_BLOCK_SIZE] = 0;
//std::cout << "original data:\t" << indata << std::endl;
std::cout << indata;
AES_cfb128_encrypt(indata, outdata, bytes_read, &key, ivec, &num,AES_ENCRYPT);
bytes_written = fwrite(outdata, 1, bytes_read, oefp);
w = w + bytes_written;
if (bytes_read < AES_BLOCK_SIZE)
break;
}
fclose(oefp);
oefp = fopen("outEncryptfile.txt", "r");
if (oefp == NULL) perror("Error opening file");
b = 0;
memcpy(ivec, ivecstr, AES_BLOCK_SIZE);
while (1)
{
bytes_read = fread(indata, 1, AES_BLOCK_SIZE, oefp);
b = b + bytes_read;
indata[AES_BLOCK_SIZE] = 0;
std::cout << "original data:\t" << indata << std::endl;
AES_cfb128_encrypt(indata, outdata, bytes_read, &key, ivec, &num, AES_DECRYPT);
std::cout << "decrypted data:\t" << outdata << std::endl;
bytes_written = fwrite(outdata, 1, bytes_read, odfp);
if (bytes_read < AES_BLOCK_SIZE)
break;
}
fclose(odfp);
return 0;
}
I have very basic encrypt/decrypt application that uses constant key. How to make this application to work with public/private key? Is it enough to generate keys with openssl and use them in my code variable ckey?
You can't. Shared key and private key cryptography are sufficiently different to ensure you cannot do it. Or maybe more correctly, you can't do it without a major redesign and rewrite.
OpenSSL provides two (maybe three) high level primitives of interest for your issue. Here's the documentation on them:
EVP Symmetric Encryption and Decryption
EVP Asymmetric Encryption and Decryption
The "maybe three" is:
EVP Authenticated Encryption and Decryption
Here are the common API calls when using (1) EVP Symmetric Encryption and (2) EVP Asymmetric Encryption from above:
EVP Symmetric Encryption
EVP_CIPHER_CTX_new
EVP_EncryptInit_ex
EVP_EncryptUpdate
EVP_EncryptFinal_ex
EVP Asymmetric Encryption
EVP_CIPHER_CTX_new
EVP_SealInit
EVP_SealUpdate
EVP_SealFinal
EVP_CIPHER_CTX_free
With all that said, its not really a design problem in OpenSSL. The APIs are well defined for operation at hand - symmetric encryption, authenticated encryption, asymmetric encryption, signing, verifying, hashing, mac'ing, etc. It would be difficult to shoehorn everything into one set of API calls.
The code you provided, using AES_KEY, AES_set_encrypt_key, and friends, is even harder to work with. Its a specialized software-only AES implementation that you get if you configure with no-asm. It also has some landmines, like being non-portable in some cases. For example, I seem to recall special care has to be taken on some big-endian platforms because you need to byte-swap the key.
Yu might also want to look at how IPsec and TLS do things. They break workflows up into two parts: (1) key exchange (or key transport) and (2) bulk encryption. The key exchange portion happens using public/private key cryptography. and establishes a shared secret. Once the shared secret is established, symmetric ciphers are keyed and bulk encryption takes place.
IPsec has a more defensive security posture. TLS runs a bit fast and loose for my taste. I only use TLS when requirements tell me to do so (like interop'ing with existing systems). Otherwise, I prefer in-app VPNs or IPsec-like schemes.

Using the CryptoPP vectors in the GCM sample code

I have downloaded the CryptoPP library and I am able to run the sample codes and get results (for CCM and GCM modes).
The next step for me is to try out the test vectors for each of these modes. From my understanding im suppose to try out the different keys, IVs and plaintexts as specified in the test vectors. Then I have to verify that the expected results are also specified in each vector.
What I can seem to understand is how to input these keys and IVs for the vectors. From the code as shown below, it seems to be using a random key.
Preferably I would like to input the keys and IVs from command prompt and then run the test code. Just setting the vectors from the code in Visual Studio would do though.
Please find the sample code and one of the vectors below:
Sample Code:
AutoSeededRandomPool prng;
SecByteBlock key( AES::DEFAULT_KEYLENGTH );
prng.GenerateBlock( key, key.size() );
byte iv[ AES::BLOCKSIZE * 16 ];
prng.GenerateBlock( iv, sizeof(iv) );
const int TAG_SIZE = 12;
// Plain text
string pdata="Authenticated Encryption";
// Encrypted, with Tag
string cipher, encoded;
// Recovered plain text
string rpdata;
/*********************************\
\*********************************/
try
{
GCM< AES >::Encryption e;
e.SetKeyWithIV( key, key.size(), iv, sizeof(iv) );
StringSource( pdata, true,
new AuthenticatedEncryptionFilter( e,
new StringSink( cipher ), false, TAG_SIZE
) // AuthenticatedEncryptionFilter
); // StringSource
}
catch( CryptoPP::Exception& e )
{
cerr << e.what() << endl;
exit(1);
}
/*********************************\
\*********************************/
try
{
GCM< AES >::Decryption d;
d.SetKeyWithIV( key, key.size(), iv, sizeof(iv) );
AuthenticatedDecryptionFilter df( d,
new StringSink( rpdata ),
DEFAULT_FLAGS, TAG_SIZE
); // AuthenticatedDecryptionFilter
// The StringSource dtor will be called immediately
// after construction below. This will cause the
// destruction of objects it owns. To stop the
// behavior so we can get the decoding result from
// the DecryptionFilter, we must use a redirector
// or manually Put(...) into the filter without
// using a StringSource.
StringSource( cipher, true,
new Redirector( df /*, PASS_EVERYTHING */ )
); // StringSource
// If the object does not throw, here's the only
// opportunity to check the data's integrity
if( true == df.GetLastResult() ) {
cout << "recovered text: " << rpdata << endl;
}
}
catch( CryptoPP::Exception& e )
{
cerr << e.what() << endl;
exit(1);
}
One of the vectors:
GCM Test Case #14 (AES-256)
Variable Value
-------------------------------------------------
K : 00000000000000000000000000000000
: 00000000000000000000000000000000
P : 00000000000000000000000000000000
IV : 000000000000000000000000
H : dc95c078a2408989ad48a21492842087
Y_0 : 00000000000000000000000000000001
E(K,Y_0) : 530f8afbc74536b9a963b4f1c4cb738b
Y_1 : 00000000000000000000000000000002
E(K,Y_1) : cea7403d4d606b6e074ec5d3baf39d18
X_1 : fd6ab7586e556dba06d69cfe6223b262
len(A)||len(C) : 00000000000000000000000000000080
GHASH(H,A,C) : 83de425c5edc5d498f382c441041ca92
C : cea7403d4d606b6e074ec5d3baf39d18
T : d0d1c8a799996bf0265b98b5d48ab919
I have downloaded the CryptoPP library and I am able to run the sample codes and get results (for CCM and GCM modes).
Crypto++ does not use the examples from its wiki when running its self tests. The self test code is much more hairier.
What I can seem to understand is how to input these keys and IVs for the vectors. From the code as shown below, it seems to be using a random key.
The Crypto++ test vectors are located in <crypto++ dir>/TestVectors. I don't believe the vector you show in your question is from Crypto++. For example, here's from <crypto++ dir>/TestVectors/gcm.txt:
AlgorithmType: AuthenticatedSymmetricCipher
Name: AES/GCM
Source: aes-modes-src-07-10-08/Testvals/gcm.1, Basic Tests for GCM (compiled by B. R. Gladman)
Key: 00000000000000000000000000000000
IV: 000000000000000000000000
MAC: 00000000000000000000000000000000
Test: NotVerify
Key: 00000000000000000000000000000000
IV: 000000000000000000000000
MAC: 58e2fccefa7e3061367f1d57a4e7455a
Test: Encrypt
Key: 00000000000000000000000000000000
IV: 000000000000000000000000
Plaintext: 00000000000000000000000000000000
Ciphertext: 0388dace60b6a392f328c2b971b2fe78
MAC: ab6e47d42cec13bdf53a67b21257bddf
Test: Encrypt
...
You can see how the Crypto++ test suite consumes it when you use the cryptest.exe v command. The source files that execute the self tests are validat1.cpp, validat2.cpp and validat3.cpp. The GCM testing starts in validat1.cpp on line 95:
pass=ValidateGCM() && pass;
Here's ValidateGCM around line 1395:
bool ValidateGCM()
{
cout << "\nAES/GCM validation suite running...\n";
cout << "\n2K tables:";
bool pass = RunTestDataFile("TestVectors/gcm.txt", MakeParameters(Name::TableSize(), (int)2048));
cout << "\n64K tables:";
return RunTestDataFile("TestVectors/gcm.txt", MakeParameters(Name::TableSize(), (int)64*1024)) && pass;
}
Its a real pain to untangle RunTestDataFile, TestDataFile and TestAuthenticatedSymmetricCipher (and friends). They are implemented in datatest.cpp. The pain point is TestAuthenticatedSymmetricCipher around line 450 of datatest.cpp.
I usually go to the applicable standard, pull the test vectors, and then write my own self tests. In the case of deterministic encryption like AES/GCM, you can write a Known Answer Test (KAT). For non-deterministic tests, you will need to write a Pairwise Consistency Test (PCT). Essentially, you verify you can round trip data from a public/private key pair operation, like a DH or RSA key.

Simple AES encryption using WinAPI

I need to do simple single-block AES encryption / decryption in my Qt / C++ application. This is a "keep the honest people honest" implementation, so just a basic encrypt(key, data) is necessary--I'm not worried about initialization vectors, etc. My input and key will always be exactly 16 bytes.
I'd really like to avoid another dependency to compile / link / ship with my application, so I'm trying to use what's available on each platform. On the Mac, this was a one-liner to CCCrypt. On Windows, I'm getting lost in the API from WinCrypt.h. Their example of encrypting a file is almost 600 lines long. Seriously?
I'm looking at CryptEncrypt, but I'm falling down the rabbit hole of dependencies you have to create before you can call that.
Can anyone provide a simple example of doing AES encryption using the Windows API? Surely there's a way to do this in a line or two. Assume you already have a 128-bit key and 128-bits of data to encrypt.
Here's the best I've been able to come up with. Suggestions for improvement are welcome!
static void encrypt(const QByteArray &data,
const QByteArray &key,
QByteArray *encrypted) {
// Create the crypto provider context.
HCRYPTPROV hProvider = NULL;
if (!CryptAcquireContext(&hProvider,
NULL, // pszContainer = no named container
NULL, // pszProvider = default provider
PROV_RSA_AES,
CRYPT_VERIFYCONTEXT)) {
throw std::runtime_error("Unable to create crypto provider context.");
}
// Construct the blob necessary for the key generation.
AesBlob128 aes_blob;
aes_blob.header.bType = PLAINTEXTKEYBLOB;
aes_blob.header.bVersion = CUR_BLOB_VERSION;
aes_blob.header.reserved = 0;
aes_blob.header.aiKeyAlg = CALG_AES_128;
aes_blob.key_length = kAesBytes128;
memcpy(aes_blob.key_bytes, key.constData(), kAesBytes128);
// Create the crypto key struct that Windows needs.
HCRYPTKEY hKey = NULL;
if (!CryptImportKey(hProvider,
reinterpret_cast<BYTE*>(&aes_blob),
sizeof(AesBlob128),
NULL, // hPubKey = not encrypted
0, // dwFlags
&hKey)) {
throw std::runtime_error("Unable to create crypto key.");
}
// The CryptEncrypt method uses the *same* buffer for both the input and
// output (!), so we copy the data to be encrypted into the output array.
// Also, for some reason, the AES-128 block cipher on Windows requires twice
// the block size in the output buffer. So we resize it to that length and
// then chop off the excess after we are done.
encrypted->clear();
encrypted->append(data);
encrypted->resize(kAesBytes128 * 2);
// This acts as both the length of bytes to be encoded (on input) and the
// number of bytes used in the resulting encrypted data (on output).
DWORD length = kAesBytes128;
if (!CryptEncrypt(hKey,
NULL, // hHash = no hash
true, // Final
0, // dwFlags
reinterpret_cast<BYTE*>(encrypted->data()),
&length,
encrypted->length())) {
throw std::runtime_error("Encryption failed");
}
// See comment above.
encrypted->chop(length - kAesBytes128);
CryptDestroyKey(hKey);
CryptReleaseContext(hProvider, 0);
}