FreeRDP
TestCryptoProtectMemory.c
1 
2 #include <winpr/crt.h>
3 #include <winpr/print.h>
4 #include <winpr/crypto.h>
5 #include <winpr/ssl.h>
6 #include <winpr/wlog.h>
7 
8 static const char* SECRET_PASSWORD_TEST = "MySecretPassword123!";
9 
10 int TestCryptoProtectMemory(int argc, char* argv[])
11 {
12  UINT32 cbPlainText = 0;
13  UINT32 cbCipherText = 0;
14  const char* pPlainText = NULL;
15  BYTE* pCipherText = NULL;
16 
17  WINPR_UNUSED(argc);
18  WINPR_UNUSED(argv);
19 
20  pPlainText = SECRET_PASSWORD_TEST;
21  cbPlainText = strlen(pPlainText) + 1;
22  cbCipherText = cbPlainText +
23  (CRYPTPROTECTMEMORY_BLOCK_SIZE - (cbPlainText % CRYPTPROTECTMEMORY_BLOCK_SIZE));
24  printf("cbPlainText: %" PRIu32 " cbCipherText: %" PRIu32 "\n", cbPlainText, cbCipherText);
25  pCipherText = (BYTE*)malloc(cbCipherText);
26  if (!pCipherText)
27  {
28  printf("Unable to allocate memory\n");
29  return -1;
30  }
31  CopyMemory(pCipherText, pPlainText, cbPlainText);
32  ZeroMemory(&pCipherText[cbPlainText], (cbCipherText - cbPlainText));
33  winpr_InitializeSSL(WINPR_SSL_INIT_DEFAULT);
34 
35  if (!CryptProtectMemory(pCipherText, cbCipherText, CRYPTPROTECTMEMORY_SAME_PROCESS))
36  {
37  printf("CryptProtectMemory failure\n");
38  return -1;
39  }
40 
41  printf("PlainText: %s (cbPlainText = %" PRIu32 ", cbCipherText = %" PRIu32 ")\n", pPlainText,
42  cbPlainText, cbCipherText);
43  winpr_HexDump("crypto.test", WLOG_DEBUG, pCipherText, cbCipherText);
44 
45  if (!CryptUnprotectMemory(pCipherText, cbCipherText, CRYPTPROTECTMEMORY_SAME_PROCESS))
46  {
47  printf("CryptUnprotectMemory failure\n");
48  return -1;
49  }
50 
51  printf("Decrypted CipherText: %s\n", pCipherText);
52  SecureZeroMemory(pCipherText, cbCipherText);
53  free(pCipherText);
54  return 0;
55 }