Reputation: 2484
I am trying to make a simple application, which is able to encrypt and decrypt some simple data. CryptEncrypt
is working fine. The string to encrypt is: This is a sample string.
. The encrypted data for this string is: ¼╩b╒áó√ $~ë▀i▐└╕ ]Φwµσ╨|V╜▐µáïÅ╚
So far so good.
After i have the encrypted text, i copy it to another string. This string will be used at the decryption. For some reason only the half of the string wil be copied in the new buffer,a nd therefore it can't be decrypted.
No matter how i try. I'm assumeing that in the encrypted string there are some special characters, and therefore it won't copied as expected. For example if i use sprintf(teststring,"%s",Encryptedstring);
it will also copy only half of the string.
CryptEncrypt
encrypt the data in a hex form by default?Upvotes: 1
Views: 414
Reputation: 45704
You are making a basic mistake:
You are handing a c-string (I cannot say whether with or without the terminator) to CryptEncrypt
and somehow expect magically to get a valid c-string of the same length back.
Things just don't work that way, the output of any good encryption-function looks like a pseudo-random binary blob, maybe with embedded 0-bytes, maybe not, and unlikely to have a terminating 0-byte.
Case in point, the output you gave is considerably longer than the input (The last part is probably garbage picked up due to missing 0-terminator).
The solution: Properly handle arbitrary binary data as arbitrary binary data (memcpy
for copying).
If you want, you can encode it into some textual representation to get a string, but that's an extra step needing more space and certainly not the task of CryptEncrypt
.
Upvotes: 2
Reputation: 1210
My advice is that when you talk about encryption, do not talk in terms of strings. Your string is just a raw data block to an encryption function so deal with it accordingly. The problem with dealing the data as string is that string tends to terminate if a null character is found and there is every possibility that you will get null byte in encrypted block.
This is why string functions dont work with encrypted data. If you want to copy data from buffer to another buffer, use memcpy instead of sprintf or strcpy.
Upvotes: 2
Reputation: 1532
I guess that sprintf will stop the copy if it encounters a '\0' charcater. You should use memcpy
Upvotes: 0