title: C++ Encrypt variables in memory
body: <p>EDIT: I've considered this more and decided it would be better and easier to just encrypt the variable in the memory and when I want to use it just decrypt it. I've tried using the following code: </p>
  
  <pre><code>DWORD blockSize = CRYPTPROTECTMEMORY_BLOCK_SIZE;
  int* protectedBlock = (int*)LocalAlloc(LPTR, (SIZE_T)blockSize);
  
  protectedBlock[0] = 1234;
  printf("Before encryption: %d\n", protectedBlock[0]);
  // OUTPUT: 1234
  
  CryptProtectMemory(protectedBlock, blockSize, CRYPTPROTECTMEMORY_SAME_PROCESS);
  printf("After encryption: %d\n", protectedBlock[0]);
  // OUTPUT: The encrypted string
  
  CryptUnprotectMemory(protectedBlock, blockSize, CRYPTPROTECTMEMORY_SAME_PROCESS);
  printf("After decryption: %d\n", protectedBlock[0]);
  //OUTPUT: 1234
  
  SecureZeroMemory(protectedBlock, blockSize);
  LocalFree(protectedBlock);
  </code></pre>
  
  <p>It works fine when I want to encrypt an integer, but when I try to use a string (LPCSTR) the string still stays in the memory. This is the code I use:</p>
  
  <pre><code>DWORD blockSize = CRYPTPROTECTMEMORY_BLOCK_SIZE;
  LPTSTR* protectedBlock = (LPTSTR*)LocalAlloc(LPTR, (SIZE_T)blockSize);
  
  protectedBlock[0] = (LPTSTR)"Test String";
  printf("Before encryption: %d\n", protectedBlock[0]);
  
  CryptProtectMemory(protectedBlock, blockSize, CRYPTPROTECTMEMORY_SAME_PROCESS);
  printf("After encryption: %d\n", protectedBlock[0]);
  // OUTPUT: The encrypted string
  
  CryptUnprotectMemory(protectedBlock, blockSize, CRYPTPROTECTMEMORY_SAME_PROCESS);
  cout &lt;&lt; "After decryption: " &lt;&lt; (char*)protectedBlock[0] &lt;&lt; endl;
  //OUTPUT: Test String
  
  SecureZeroMemory(protectedBlock, blockSize);
  LocalFree(protectedBlock);
  </code></pre>