Reputation: 49
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);
Upvotes: 4
Views: 2203
Reputation: 182779
protectedBlock[0] = (LPTSTR)"Test String";
This is wrong for two reasons:
By using the string literal "Test String"
in your code, you make that a string literal that is part of your program. You will have to assemble the string in memory some other way.
A LPSTR
is a long pointer to a string. So you put in the protected block a pointer to a string. Then, by protecting the block, you protected that pointer. But the pointer wasn't what you wanted to protect, you wanted to protect the string itself. So you need to put the string data itself into the protected block, not a pointer to it.
Upvotes: 0
Reputation: 1404
Which "memory". CPU registers, ram, cache memory, a swap disk etc. What you are asking is a complicated issue that you could probably write a book on.
In truth its probably only feasable (and thats debatable) in assembly where you can be sure the compiler isnt doing some type of optimisation you don't know about. Even this doesnt always stop cpu registers / cache etc.
The real question you should ask yourself is who or what you are trying to protect it from.
Something here to get you started on a small amount of the issues you have to address.
I would look first at maybe encrypting variables in memory (which in itself can be a large topic).
Google and some reading is your friend here.
Upvotes: 1