Re: CryptDecrypt



"kert" <kaidokert@xxxxxxxxx> wrote in message
news:1170242651.697477.310820@xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

But first thing i am going to say is that you cannot keep encrypted
data in string datatypes, unless you BASE64encode them first or
something. Why ?
Because encrypted data will contain ALL possible octets ( bytes ) from
0-255 .. you see where this is going ?

Actually BSTRs can contain binary data; the SysAllocStringByteLen is
provided explicitly to support that. Other types of strings such as MFC's
CString can also. We must however be careful and it is very easy to overlook
something that is intended to be used only for non-binary data.

The use of strdup as used in the code is the type of mistake that would be a
definite problem.

C strings and also all wrappings of it, including bstr_t rely on 0
( zero ) being a string terminator. So it is very likely that your
str.length() call will not return the actual length of encrypted data.
To verify this print out the length that you got from CryptEncryptCall
and compare it to your str.length(). I am willing to bet that they are
different.

All the C/C++ code I find in the MSDN use char or BYTE for CryptDecrypt.

When I was looking for sample VB 6 code, I found a sample that used a BSTR
for either CryptDecrypt or CryptEncrypt; I forget which. It did it wrong, so
it is an easy mistake to make. I agree that it is best to avoid using a BSTR
in this manner, but it is possible if the person is careful.

A _bstr_t does not wrap C strings; it wraps BSTRs. The return value of
_bstr_t::length is the value that SysStringLen() returns; see the
documentation of that, which states explicitly that the BSTR can contain
embedded Null characters that SysStringLen() does not use to determining the
length.

choose something like
std::vector<BYTE> encryptedData;
to hold your encrypted data and use code like:
DWORD len2 = encryptedData.size();
if(!CryptDecrypt(hKey, 0, 1, 0, &encryptedData[0] , &len2))
to operate on it.

Just as the length of the vector must be set prior to calling CryptDecrypt,
the size of a BSTR must be set prior to the call. I don't see a way to do
that using the _bstr_t class but I assume it can be done less directly.


.



Relevant Pages