The CryptProtectMemory function encrypts memory to prevent others from viewing sensitive information in your process. For example, use the CryptProtectMemory function to encrypt memory that contains a password. Encrypting the password prevents others from viewing it when the process is paged out to the swap file. Otherwise, the password is in plaintext and viewable by others.
DPAPI_IMP BOOL CryptProtectMemory( LPVOID pDataIn, DWORD cbDataIn, DWORD dwFlags );
A pointer to the block of memory to encrypt. The cbData parameter specifies the number of bytes that will be encrypted. If the data contained in the memory space is smaller than the number of bytes specified, data outside of the intended block will be encrypted. If it is larger than cbData bytes, then only the first cbData bytes will be encrypted.
Number of bytes of memory pointed to by the pData parameter to encrypt. The number of bytes must be a multiple of the CRYPTPROTECTMEMORY_BLOCK_SIZE constant defined in Wincrypt.h.
This parameter can be one of the following flags. You must specify the same flag when encrypting and decrypting the memory.
If the function succeeds, the function returns TRUE.
If the function fails, it returns FALSE. For extended error information, call GetLastError.
Using CryptProtectMemory and CryptUnprotectMemory for password encryption is not secure because the data exists as plaintext in memory before it is encrypted and at any time the caller decrypts it for use.
Typically, you use the CryptProtectMemory function to encrypt sensitive information that you are going to decrypt while your process is running. Do not use this function to save data that you want to decrypt later; you will not be able to decrypt the data if the computer is restarted. To save encrypted data to a file to decrypt later, use the CryptProtectData function.
Call the CryptUnprotectMemory function to decrypt memory encrypted with the CryptProtectMemory function. When you have finished using the sensitive information, clear it from memory by calling the SecureZeroMemory function.
Use the CRYPTPROTECTMEMORY_CROSS_PROCESS or CRYPTPROTECTMEMORY_SAME_LOGON flag if you use RPC or LRPC to pass encrypted data to another process. The receiving process must specify the same flag to decrypt the data. Also, use these flags if you use shared memory.
If the client uses the CRYPTPROTECTMEMORY_SAME_LOGON flag, the server must impersonate the client (RpcImpersonateClient) before decrypting the memory.
The following example calls the CryptProtectMemory function to encrypt data that is in memory.
#include <windows.h> #include <stdio.h> #include <Wincrypt.h>
|Minimum supported client||Windows Vista [desktop apps | UWP apps]|
|Minimum supported server||Windows Server 2003 [desktop apps | UWP apps]|