0

I am trying to use BCryptEncrypt to encrypt some basic plain text and I would like to save it in a Notepad; but I want to actually print and see the encrypted text in the console. What is the correct format for wprintf?

Here's part of my code:

 // BCryptEncrypt

    LPCWSTR textToEncrypt = L"Encrypt me.";
    DWORD numberOfBytes = (DWORD)((wcslen(textToEncrypt)+1) * sizeof(WCHAR));
    ULONG sizeCiphertext;
    PBYTE cipherText = NULL;

// Get the size for cyphertext 

    status = BCryptEncrypt(hKey, (PUCHAR)textToEncrypt, numberOfBytes, NULL, NULL, 0, NULL, 0, &sizeCiphertext, BCRYPT_BLOCK_PADDING);

    if (!NT_SUCCESS(status))
    {
        wprintf(L"Error 0x%x returned by function BCryptEncrypt 1.\n", status);
        
    }

cipherText = (PBYTE)HeapAlloc(GetProcessHeap(), 0, sizeCiphertext);

    if (cipherText == NULL)
    {
        wprintf(L"Memory allocation failed.\n");
        
    }

    status = BCryptEncrypt(hKey, (PUCHAR)textToEncrypt, numberOfBytes, NULL, NULL, 0, cipherText, sizeCiphertext, &sizeCiphertext, BCRYPT_BLOCK_PADDING);

    if (!NT_SUCCESS(status))
    {
        wprintf(L"Error 0x%x returned by function BCryptEncrypt 2.\n", status);
        

    }

    wprintf(L"Plain text: %s \n", textToEncrypt);

//No idea if this is OK
wprintf(L"Ciphertext: %hs \n", cipherText);
Sergio Calderon
  • 837
  • 1
  • 13
  • 32
  • 1
    Encrypted data is *binary* data. It's not a printable string. – Andrew Henle Feb 13 '23 at 21:32
  • 1
    But can I write it in a file passing it as second parameter of `WriteFile`? – Sergio Calderon Feb 13 '23 at 21:34
  • You can save arbitrary data into a file. You would need a hex editor to turn those bytes into a human-readable representation. Alternatively, you could just convert the data into hex representation, and dump those characters to the console. – IInspectable Feb 13 '23 at 23:33
  • This thread may help. https://learn.microsoft.com/en-us/answers/questions/1166002/error-encrypting-with-calg-aes-256?orderby=helpful#answers. But it uses CryptEncrypt(). Microsoft has deprecated it. – Torrecto - MSFT Feb 15 '23 at 06:40

0 Answers0