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:
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);
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:
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 << "After decryption: " << (char*)protectedBlock[0] << endl;
//OUTPUT: Test String
SecureZeroMemory(protectedBlock, blockSize);
LocalFree(protectedBlock);