Unable to do RSA Encryption/Decryption using Crypto++ (isValidCoding is false) - c++

I am using Crypto++ to encrypt an array of bytes using RSA. I have followed Crypto++ wiki's samples with no luck getting them to work. Encryption and Decryption in all the samples are done within a single process but I am trying to decrypt the content which is already encrypted in another process.
Here is my code:
class FixedRNG : public CryptoPP::RandomNumberGenerator
{
public:
FixedRNG(CryptoPP::BufferedTransformation &source) : m_source(source) {}
void GenerateBlock(byte *output, size_t size)
{
m_source.Get(output, size);
}
private:
CryptoPP::BufferedTransformation &m_source;
};
uint16_t Encrypt()
{
byte *oaepSeed = new byte[2048];
for (int i = 0; i < 2048; i++)
{
oaepSeed[i] = (byte)i;
}
CryptoPP::ByteQueue bq;
bq.Put(oaepSeed, 2048);
FixedRNG prng(bq);
Integer n("Value of N"),
e("11H"),
d("Value of D");
RSA::PrivateKey privKey;
privKey.Initialize(n, e, d);
RSA::PublicKey pubKey(privKey);
CryptoPP::RSAES_OAEP_SHA_Encryptor encryptor( pubKey );
assert( 0 != encryptor.FixedMaxPlaintextLength() );
byte blockSize = encryptor.FixedMaxPlaintextLength();
int divisionCount = fileSize / blockSize;
int proccessedBytes = 0;
// Create cipher text space
uint16_t cipherSize = encryptor.CiphertextLength( blockSize );
assert( 0 != cipherSize );
encryptor.Encrypt(prng, (byte*)plaintext, blockSize, (byte*)output);
return cipherSize;
}
void Decrypt(uint16_t cipherSize)
{
byte *oaepSeed = new byte[2048];
for (int i = 0; i < 2048; i++)
{
oaepSeed[i] = (byte)i;
}
CryptoPP::ByteQueue bq;
bq.Put(oaepSeed, 2048);
FixedRNG prng(bq);
Integer n("Value of N"),
e("11H"),
d("Value of D");
RSA::PrivateKey privKey;
privKey.Initialize(n, e, d);
//RSA::PublicKey pubKey(privKey);
CryptoPP::RSAES_OAEP_SHA_Decryptor decryptor( privKey );
byte blockSize = decryptor.FixedMaxPlaintextLength();
assert(blockSize != 0);
size_t maxPlainTextSize = decryptor.MaxPlaintextLength( cipherSize );
assert( 0 != maxPlainTextSize );
void* subBuffer = malloc(maxPlainTextSize);
CryptoPP::DecodingResult result = decryptor.Decrypt(prng, (byte*)cipherText, cipherSize, (byte*)subBuffer);
assert( result.isValidCoding );
assert( result.messageLength <= maxPlainTextSize );
}
Unfortunately, value of isValidCoding is false. I think I am misunderstanding something about RSA encryption/decryption!!
Note that, privKey and pubKey have been validated using KEY.Validate(prng, 3).
I have also tried to use RAW RSA instead of OAEP and SHA with no luck. I have tried to debug through crypto++ code, what I am suspicious about is prng variable. I think there is something wrong with it. I have also used AutoSeededRandomPool instead of FixedRNG but it didn't help. Worth to know that, if I copy the decryption code right after encryption code and execute it in Encrypt() method, everything is fine and isValidCoding is true!!

This is probably not be correct:
byte blockSize = encryptor.FixedMaxPlaintextLength();
...
encryptor.Encrypt(prng, (byte*)plaintext, blockSize, (byte*)output);
return cipherSize;
Try:
size_t maxLength = encryptor.FixedMaxPlaintextLength();
size_t cipherLength = encryptor.CiphertextLength( blockSize );
...
SecureByteBlock secBlock(cipherLength);
cipherLength = encryptor.Encrypt(prng, (byte*)plaintext, blockSize, secBlock);
secBlock.resize(cipherLength);
FixedMaxPlaintextLength returns a size_t, not a byte.
You should probably be calling CiphertextLength on plaintext.
I'm not really sure how you are just returning an uint_t from encrypt().
You might do better by starting fresh, and using an example from the Crypto++ as a starting point. I'm not sure this design is worth pursuing.
If you start over, then Shoup's Elliptic Curve Integrated Encryption Scheme (ECIES) would be a good choice since it combines public key with symmetric ciphers and authentication tags.

Related

Issues reimplementing some C# encryption stuff in C++ using cryptopp

So I have this piece of C# code:
void Decrypt(Stream input, Stream output, string password, int bufferSize) {
using (var algorithm = Aes.Create()) {
var IV = new byte[16];
input.Read(IV, 0, 16);
algorithm.IV = IV;
var key = new Rfc2898DeriveBytes(password, algorithm.IV, 100);
algorithm.Key = key.GetBytes(16);
using(var decryptor = algorithm.CreateDecryptor())
using(var cryptoStream = new CryptoStream(input, decryptor, CryptoStreamMode.Read)) {
CopyStream(cryptoStream, output, bufferSize);
}
}
}
and I am trying to translate this into C++ with CryptoPP.
So this is what I have written:
void decrypt(std::ifstream& in_file, std::ofstream& out_file, std::string_view password, size_t bufSize) {
using namespace CryptoPP;
// Get IV
byte iv[16];
in_file.read(reinterpret_cast<char*>(iv), sizeof(iv));
// Read cypher
std::string cypher;
while (in_file && cypher.size() != bufSize) {
char c;
in_file.read(&c, 1);
cypher.push_back(c);
}
// Get key
byte key[16];
PKCS5_PBKDF2_HMAC<SHA1> pbkdf2;
pbkdf2.DeriveKey(key, sizeof(key), 0, reinterpret_cast<const byte*>(password.data()), password.size(), iv, sizeof(iv), 100);
// Decrypt
CTR_Mode<AES>::Decryption decrypt(key, sizeof(key), iv);
std::string output;
StringSource(cypher, true, new StreamTransformationFilter(decrypt, new StringSink(output)));
// Write output to file
out_file.write(output.data(), output.size());
}
However, from this function, I am only getting back trash data. What could I be doing wrong?
Thanks
Tuxifan!
So I found the solution! First of all, as #mbd mentioned, C# uses CBC by default. Additionally, I need to cut away the rest of the data like this:
while ((cipher.size() % 16) != 0) {
cipher.pop_back();
}

AES IV into file with FileSource and FileSink

I have the need to crypt big files (multi GB) with crypto++. I managed to find an example on the documentation that helped me create the 2 followings functions :
bool AESEncryptFile(const std::string& clearfile, const std::string& encfile, const std::string& key) {
try {
byte iv[CryptoPP::AES::BLOCKSIZE] = {};
CryptoPP::CBC_Mode<CryptoPP::AES>::Encryption encryptor;
encryptor.SetKeyWithIV((unsigned char*)key.c_str(), CryptoPP::AES::DEFAULT_KEYLENGTH, iv);
CryptoPP::StreamTransformationFilter filter(encryptor);
CryptoPP::FileSource source(clearfile.c_str(), false);
CryptoPP::FileSink sink(encfile.c_str());
source.Attach(new CryptoPP::Redirector(filter));
filter.Attach(new CryptoPP::Redirector(sink));
const CryptoPP::word64 BLOCK_SIZE = 4096;
CryptoPP::word64 processed = 0;
while (!EndOfFile(source) && !source.SourceExhausted()) {
source.Pump(BLOCK_SIZE);
filter.Flush(false);
processed += BLOCK_SIZE;
}
filter.MessageEnd();
return true;
} catch (const CryptoPP::Exception& ex) {
return false;
}
}
bool AESDecryptFile(const std::string& encfile, const std::string& clearfile, const std::string& key) {
try {
byte iv[CryptoPP::AES::BLOCKSIZE] = {};
CryptoPP::CBC_Mode<CryptoPP::AES>::Decryption decryptor;
decryptor.SetKeyWithIV((unsigned char*)key.c_str(), CryptoPP::AES::DEFAULT_KEYLENGTH, iv);
CryptoPP::StreamTransformationFilter filter(decryptor);
CryptoPP::FileSource source(encfile.c_str(), false);
CryptoPP::FileSink sink(clearfile.c_str());
source.Attach(new CryptoPP::Redirector(filter));
filter.Attach(new CryptoPP::Redirector(sink));
const CryptoPP::word64 BLOCK_SIZE = 4096;
CryptoPP::word64 processed = 0;
while (!EndOfFile(source) && !source.SourceExhausted()) {
source.Pump(BLOCK_SIZE);
filter.Flush(false);
processed += BLOCK_SIZE;
}
.
filter.MessageEnd();
return true;
} catch (const CryptoPP::Exception& ex) {
return false;
}
}
This is working great. On 8 GB files i'm using very little memory.
But as you can see the IV is (empty for now) hardcoded and i would like to :
While encrypting , put it a the end of the file.
While decrypting : get the IV from the file to init the decryptor.
Is there a way to do that with crypto++ or should i handle it manually after/before the enc/decryption process ?
Thanks to all the differents comments here is what i managed to do. As suggested by #Sam Mason i put the iv at the beginning of the file :
So before starting to encrypt i 'm putting the iv at the beginning of the file:
CryptoPP::ArraySource(iv, sizeof(iv), true,
new CryptoPP::Redirector(sink)
);
// Encrypt
And then when decrypting i'm getting the IV back like this :
unsigned char iv[CryptoPP::AES::BLOCKSIZE];
CryptoPP::ArraySink ivSink(iv, sizeof(iv));
source.Attach(new CryptoPP::Redirector(ivSink));
source.Pump(CryptoPP::AES::BLOCKSIZE);
// Decrypt
Note for future reader : Don't use an empty IV like show in my OP , instead generate one randomly , for example :
CryptoPP::AutoSeededRandomPool prng;
unsigned char iv[CryptoPP::AES::BLOCKSIZE];
prng.GenerateBlock(iv, sizeof(iv));

How to decrypt c++ the aes Rijndael CBC using kotlin properly?

Md5 hashed value (salt+password)
hashed: "89d1ed22aac58f5bbea53b2fde81a946" (String)(32 characters)
Original string value
orginal: "test" (String)
Encryption Key & IV (Bytes)
Key: "encryptionkeyhere" (String)
16 bit key: 646C646873766D666C766D000000000 (Bytes)(Converted to 16 Bytes)
16 bit IV: 00000000000000000000000000000000 (Bytes)
Encrypted hex value
084987B6C979950A11EBE33A5499B091D127CD208E95BAE5C6B5DE5FAE65AFB68EB5C083BB808FDFD98C16694E6FCA9F2E15DF5A63FBD7E4E7EFFB242D0D56B1A3C35F76F977A70F5A9A1EAD0FC3A9E61242CBA0AF848FFC5C8C4342F4011E0436D81F6B064E086C802E175F662C43A798ADC38D25684E99E926ED30B900FF89CA66760B7DBDFBF3087378620A69981FB87346512DC6596E7420763C238EC7E2015941F3E613070E737A0D191F4730C3CF70C270B5FA13E44407B7D6D7567B6126241777D80874320B969B8818371CEC91DF97AA42ABE5BCF015D9B17BDC18F2F3E1E7E25794A97C44F760B68F1D24FD96036DFC92AF400D53D1292C1FBDD0296AFE28401D48B2EA486C781B4729E55C8794505C7AC3AB2A35C7B893DE4128A3A59335BC76071E404A9B7D600C19CBB0CB640071C7AF9CB135FC46DD29080707ED30BC9CDA6AE65ACDD84CF52B299408D82333F1A8DBD1F58213671063D7C8C1BB9002563A04BD53B03D802888F299024AD8C9BE2A0749EF920362A4C86129401DB29C2D2A17A960C2038C0DC6CCD18F361A629BBDCA17BFF0EB1EB737AE9F00CAB8CFBE2050749E6F0D6EAB7DC849380E85BC55DA82AF7354D31D8431A47FB385CC5CA01FE1DE064AE3F2426A5135938AD923C4A28661CBDA7F1397326D7921158FB06A2B4A1C6F8D141B2749D8A8B20883A7A168D811057CDA88D595EEC694558C446673B708BABFFB5FA584B2AFE527A9C3B162BD38405FC08250AB5EF1D15C7ED94AB71796A5582E25ADFBF83D7BD146C9BF5FE68FA3ADEA4C0D77A4314D06336F6D503A8C097A0FD54051CDD49ED8ECA34E3150D61C01FBB53208C62D701BEFEB15419776B9FB18437FE2C1B4A9BABFDE3CE83457FF6F3F87F83B9B702450D0409886B9D9490BD665BB1CB3E5E460ACDD7BC51958A3870985D58E4585B
C++ Encryption Code
void CRijndael::Encrypt(char const* in, char* result, size_t n, int iMode)
{
if(false==m_bKeyInit)
throw exception(sm_szErrorMsg1);
//n should be > 0 and multiple of m_blockSize
if(0==n || n%m_blockSize!=0)
throw exception(sm_szErrorMsg2);
int i;
char const* pin;
char* presult;
if(CBC == iMode) //CBC mode, using the Chain
{
for(i=0,pin=in,presult=result; i<(int)( n/m_blockSize ); i++)
{
Xor(m_chain, pin);
EncryptBlock(m_chain, presult);
memcpy(m_chain, presult, m_blockSize);
pin += m_blockSize;
presult += m_blockSize;
}
}
else if(CFB == iMode) //CFB mode, using the Chain
{
for(i=0,pin=in,presult=result; i<(int)( n/m_blockSize ); i++)
{
EncryptBlock(m_chain, presult);
Xor(presult, pin);
memcpy(m_chain, presult, m_blockSize);
pin += m_blockSize;
presult += m_blockSize;
}
}
else //ECB mode, not using the Chain
{
for(i=0,pin=in,presult=result; i<(int)( n/m_blockSize ); i++)
{
EncryptBlock(pin, presult);
pin += m_blockSize;
presult += m_blockSize;
}
}
}
Java/Kotlin Aes Descryption Code
var key = buildKeyFromString(encryptionKey)
val iv = IvParameterSpec(key)
val secretKeySpec = SecretKeySpec(key, "AES")
val cipher = Cipher.getInstance("AES/CBC/NoPadding")
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, iv)
return cipher.doFinal(encryptedByte)
The problem now is when I decrypt using the kotlin code, the initial string is not encoded properly
Decrypted String value
String: "????58f5bbea53b2fde81a946" (String)(Wrong value)
Decrypted Hex value (32 bytes)
Hex: "5C55005916125F540D170E353866356262656135336232666465383161393436"
Exptected String value
Hashed: "89d1ed22aac58f5bbea53b2fde81a946" (String)(32 characters)
The cause of the problem is that different IVs are used for encryption and decryption: The encryption uses a zero vector (0x00000000000000000000000000000000) and the decryption uses the key as IV (0x646C646873766D666C766D0000000000).
By the way, the posted ciphertext is too long. Since the plaintext is 32 bytes in size and no padding is used, the ciphertext is also 32 bytes in size and just corresponds to the first 32 bytes of the posted ciphertext (0x084987B6C979950A11EBE33A5499B091D127CD208E95BAE5C6B5DE5FAE65AFB6).
I have use key variable for both IV and secretkeyspec. So I've changed the IV to 16 bytes 0.
var key = buildKeyFromString(encryptionKey)
var ivBytes = 16 bytes zero
val iv = IvParameterSpec(ivBytes )
val secretKeySpec = SecretKeySpec(key, "AES")
val cipher = Cipher.getInstance("AES/CBC/NoPadding")
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, iv)
return cipher.doFinal(encryptedByte)

How to find private key in token by using X509 certificate modulus in C++

In c++ code using pkcs#11 we are trying to find the private key and install corresponding x509 certificate in the token. But unable to find the key pair in token using modulus. Below is my code sample.
//Install certificate
const char bytes[] = "-----BEGIN CERTIFICATE-----" "\n"
....
"-----END CERTIFICATE-----" "\n";
BIO *bio_mem = BIO_new(BIO_s_mem());
BIO_puts(bio_mem, bytes);
X509 * x509 = PEM_read_bio_X509(bio_mem, NULL, NULL, NULL);
//
BIO *bio_out = BIO_new_fp(stdout, BIO_NOCLOSE);
EVP_PKEY *pkey = X509_get_pubkey(x509);
RSA *rsa_key;
DSA *dsa_key;
char *rsa_e_dec, *rsa_n_hex, *dsa_p_hex,
*dsa_q_hex, *dsa_g_hex, *dsa_y_hex;
rsa_key = pkey->pkey.rsa;
//IFNULL_FAIL(rsa_e_dec, "unable to extract rsa exponent");
CK_BYTE_PTR modulus, exponent;
modulus = (unsigned char *)malloc(256);
int mo = BN_bn2bin(rsa_key->n, modulus);
//EVP_PKEY_free(pkey);
// CK_RV result;
CK_OBJECT_HANDLE hObject;
CK_OBJECT_HANDLE hObjects[100];
CK_OBJECT_HANDLE_PTR hObject_PTR = NULL;
CK_ULONG count;
vector<CK_OBJECT_HANDLE> *handles = new vector<CK_OBJECT_HANDLE>();
//Object class attribute
CK_OBJECT_CLASS classValue = CKO_PRIVATE_KEY;
CK_OBJECT_CLASS keytype = CKK_RSA;
CK_ATTRIBUTE privKeySearchTemplate[] = {
{ CKA_CLASS, &classValue,sizeof(classValue) },
{ CKA_KEY_TYPE, &keytype,sizeof(keytype) },
{ CKA_MODULUS, &modulus, sizeof(modulus) },
};
//
//{ CKA_PUBLIC_EXPONENT, exponent},
// Read label and ID from private key handle
CK_ATTRIBUTE privKeyAttrsToRead[] =
{ { CKA_LABEL, NULL_PTR, 0 },
{ CKA_ID, NULL_PTR, 0 },
};
//WriteToLog(modulus, modulus_len11);
// Find all objects with the template specified
result = m_pPKCS11->C_FindObjectsInit(m_SessionHandle, privKeySearchTemplate, 2);
do {
// Find the next object
result = m_pPKCS11->C_FindObjects(m_SessionHandle, &hObject, 1, &count);
if (count != 0)
handles->push_back(hObject);
} while (count != 0);
result = m_pPKCS11->C_FindObjectsFinal(m_SessionHandle);
There are several bugs here:
{ CKA_MODULUS, &modulus, sizeof(modulus) }
like always, sizeof(modulus) is size of your pointer which is 4 or 8 based on your system. This should be size of your modulus which in your case is mo. In addition, use correct type here:
CK_KEY_TYPE keytype = CKK_RSA;
Another bug is here:
m_pPKCS11->C_FindObjectsInit(m_SessionHandle, privKeySearchTemplate, 2);
You are searching a template with 3 attributes, but you have set number of attributes as 2. Normally you need to write code like this to prevent such bugs:
m_pPKCS11->C_FindObjectsInit(m_SessionHandle, privKeySearchTemplate, sizeof(privKeySearchTemplate) / sizeof(CK_ATTRIBUTE));
Finally, you need to allocate enough memory for your modulus before using BN_bn2bin, unless you like to get memory exceptions. Allocating 256 bytes may not be sufficient.

How to encrypt and decrypt a const char* in WinRT

I have been trying to write encrypt and decrypt functions whose signatures require the input and the output strings to be void* type only. The code works fine if the inputs can be specified as IBuffer^ but in the other case the source string and the encrypted->decrypted string do not match.
CodeIBuffer^ byteArrayToIBufferPtr(byte *source, int size)
{
Platform::ArrayReference<uint8> blobArray(source, size);
IBuffer ^buffer = CryptographicBuffer::CreateFromByteArray(blobArray);
return buffer;
}
byte* IBufferPtrToByteArray(IBuffer ^buffer)
{
Array<unsigned char,1U> ^platArray = ref new Array<unsigned char,1U>(256);
CryptographicBuffer::CopyToByteArray(buffer,&platArray);
byte *dest = platArray->Data;
return dest;
}
int DataEncryption::encryptData(EncryptionAlgorithm algo, int keySize, void* srcData, const unsigned int srcSize,
void*& encData, unsigned int& encSize)
{
LOG_D(TAG, "encryptData()");
if(srcData == nullptr)
{
LOG_E(TAG,"");
return DataEncryption::RESULT_EMPTY_DATA_ERROR;
}
if(srcSize == 0)
{
LOG_E(TAG,"");
return DataEncryption::RESULT_SIZE_ZERO_ERROR;
}
IBuffer^ encrypted;
IBuffer^ buffer;
IBuffer^ iv = nullptr;
String^ algName;
bool cbc = false;
switch (algo)
{
case DataEncryption::ENC_DEFAULT:
algName = "AES_CBC";
cbc = true;
break;
default:
break;
}
// Open the algorithm provider for the algorithm specified on input.
SymmetricKeyAlgorithmProvider^ Algorithm = SymmetricKeyAlgorithmProvider::OpenAlgorithm(algName);
// Generate a symmetric key.
IBuffer^ keymaterial = CryptographicBuffer::GenerateRandom((keySize + 7) / 8);
CryptographicKey^ key;
try
{
key = Algorithm->CreateSymmetricKey(keymaterial);
}
catch(InvalidArgumentException^ e)
{
LOG_E(TAG,"encryptData(): Could not create key.");
return DataEncryption::RESULT_ERROR;
}
// CBC mode needs Initialization vector, here just random data.
// IV property will be set on "Encrypted".
if (cbc)
iv = CryptographicBuffer::GenerateRandom(Algorithm->BlockLength);
// Set the data to encrypt.
IBuffer ^srcDataBuffer = byteArrayToIBufferPtr(static_cast<byte*>(srcData),256);
// Encrypt and create an authenticated tag.
encrypted = CryptographicEngine::Encrypt(key, srcDataBuffer, iv);
//encData = encrypted;
byte *bb = IBufferPtrToByteArray(encrypted);
encData = IBufferPtrToByteArray(encrypted);
encSize = encrypted->Length;
return DataEncryption::RESULT_SUCCESS;
}
int DataEncryption::decryptData(EncryptionAlgorithm algo, int keySize, void* encData, const unsigned int encSize,
void*& decData, unsigned int& decSize)
{
LOG_D(TAG, "decryptData()");
if(encData == nullptr)
{
LOG_E(TAG,"");
return DataEncryption::RESULT_EMPTY_DATA_ERROR;
}
if(encSize == 0)
{
LOG_E(TAG,"");
return DataEncryption::RESULT_SIZE_ZERO_ERROR;
}
IBuffer^ encrypted;
IBuffer^ decrypted;
IBuffer^ iv = nullptr;
String^ algName;
bool cbc = false;
switch (algo)
{
case DataEncryption::ENC_DEFAULT:
algName = "AES_CBC";
cbc = true;
break;
default:
break;
}
// Open the algorithm provider for the algorithm specified on input.
SymmetricKeyAlgorithmProvider^ Algorithm = SymmetricKeyAlgorithmProvider::OpenAlgorithm(algName);
// Generate a symmetric key.
IBuffer^ keymaterial = CryptographicBuffer::GenerateRandom((keySize + 7) / 8);
CryptographicKey^ key;
try
{
key = Algorithm->CreateSymmetricKey(keymaterial);
}
catch(InvalidArgumentException^ e)
{
LOG_E(TAG,"encryptData(): Could not create key.");
return DataEncryption::RESULT_ERROR;
}
// CBC mode needs Initialization vector, here just random data.
// IV property will be set on "Encrypted".
if (cbc)
iv = CryptographicBuffer::GenerateRandom(Algorithm->BlockLength);
// Set the data to decrypt.
byte *cc = static_cast<byte*>(encData);
IBuffer ^encDataBuffer = byteArrayToIBufferPtr(cc,256);
// Decrypt and verify the authenticated tag.
decrypted = CryptographicEngine::Decrypt(key, encDataBuffer, iv);
byte *bb = IBufferPtrToByteArray(decrypted);
decData = IBufferPtrToByteArray(decrypted);
decSize = decrypted->Length;
return DataEncryption::RESULT_SUCCESS;
}
I'm guessing that the problem is with this function:
byte* IBufferPtrToByteArray(IBuffer ^buffer)
{
Array<unsigned char,1U> ^platArray = ref new Array<unsigned char,1U>(256);
CryptographicBuffer::CopyToByteArray(buffer,&platArray);
byte *dest = platArray->Data;
return dest;
}
What you're doing there is allocating a new Platform::Array<byte>^ with 1 reference, then getting a pointer to its internally-managed storage, then returning that pointer-- at which point the Array is being dereferenced and is thus deallocating its underlying storage. Thus the pointer you return refers to freed memory. The next allocation is likely to overwrite those bytes.
What you'll need to do is take the return-by-reference Array<byte>^ from CopyToByteArray() (which creates a new Array, presumably wrapping the bytes of the input IBuffer^, and returns it) and copy that array's contents.
Your end result will function similarly to this snippet from the Readium SDK project, which takes a std::string instance, hashes it using SHA-1, and copies the hash data into a member variable uint8_t _key[KeySize]:
using namespace ::Platform;
using namespace ::Windows::Foundation::Cryptography;
using namespace ::Windows::Foundation::Cryptography::Core;
auto byteArray = ArrayReference<byte>(reinterpret_cast<byte*>(const_cast<char*>(str.data())), str.length());
auto inBuf = CryptographicBuffer::CreateFromByteArray(byteArray);
auto keyBuf = HashAlgorithmProvider::OpenAlgorithm(HashAlgorithmNames::Sha1)->HashData(inBuf);
Array<byte>^ outArray = nullptr;
CryptographicBuffer::CopyToByteArray(keyBuf, &outArray);
memcpy_s(_key, KeySize, outArray->Data, outArray->Length);
The steps:
Create an ArrayReference<byte> corresponding to the bytes in the std::string (no copying).
Pass that to CryptographicBuffer::CreateFromByteArray() to get your IBuffer^. Still no copying of data.
Call your hash/encryption function, passing the IBuffer^ you just made. You get another IBuffer^ in return, which may or may not be using the exact same storage (that's really up to the implementation of the algorithm, I think).
Create a variable of type Array<byte>^. Don't allocate an object, you're going to be given one by reference.
Pass the address of that object into CryptographicBuffer::CopyToByteArray() to receive a copy of your key data.
While that Array^ remains valid, copy its bytes into your native array.