I came across the CryptoAPI from the Microsoft MSDN to encrypt communication between my Clients and my Server for a basic Networking Application. (Just to learn about securing network communications).
I decide to use AES 256bit cypher in CBC for packets encryption and RSA 2048bit for sending / receiving the AES symmetric key.
I have read many examples, even succeed writing few snippets using this lib such as:
- Encrypting / Decrypting Unicode String using AES
- Encrypting / Decrypting Streams using AES
those two snippets works fine and are quite easy to write.
Now I want to Encrypt / Decrypt on the fly any static bytes array (which comes from my server or client) but I can't get it work for some reason which are probably really stupid.
I'm not even sure if using CryptoAPI is the way to go for such needs.
This is my attempt which fails with the error : 234 (ERROR_MORE_DATA)
function AES(const data : Pointer; var dest : TBytesArray; bufferSize : DWORD; Key : String; doCrypt : Boolean) : Boolean;
var AES : HCRYPTPROV;
hKEY : HCRYPTKEY;
begin
CryptAcquireContext(@AES, nil, nil, PROV_RSA_AES, 0);
try
hKey := AES_DeriveKeyFromPassword(AES, key);
try
SetLength(dest, bufferSize);
Move(data^, dest[0], bufferSize);
if NOT CryptEncrypt(hKey, 0, true, 0, @dest[0], @bufferSize, bufferSize) then showmessage(inttostr(getlasterror()));
finally
CryptDestroyKey(hKey);
end;
finally
CryptReleaseContext(AES, 0);
end;
end;
I'm sure I'm doing something wrong somewhere, but I don't understand why.
When I change the Final to false the error doesn't came up but I don't know why I would need to use this flag (else than true) since I just want to encrypt packets by packets.
Notice:
The data parameter could contain static byte array (Network arrival / sent buffers)
Generally : buffer : array[0..1023] of byte
I copy this static bytes array to a dynamic one which is the destination one to be encrypted / decrypted.
So the exact question is:
How could I encrypt / decrypt on the fly data for Winsock communication without using third part components / packages just the CryptoAPI?