When handling sensitive data like encryption keys, passwords, or authentication tokens, avoid using standard string types that can be easily copied and may persist in memory. Instead, use specialized secure data structures that prevent accidental copying and provide controlled memory management.
Key practices:
std::string
with custom classes that are not copy-constructible and handle their own memory locking/unlockingfill()
and clear()
operationsmlock()
/VirtualLock()
to prevent sensitive data from being paged to diskExample of problematic code:
// BAD: std::string can be easily copied accidentally
std::string encryption_key = user_input;
storage_options.encryption_key = encryption_key; // Creates copy
Example of secure handling:
// GOOD: Explicit clearing of temporary sensitive data
auto user_key = entry.second.GetValue<string>();
storage_options.encryption_key = user_key;
// Clear the user key from memory
fill(user_key.begin(), user_key.end(), '\0');
user_key.clear();
This approach prevents sensitive data from accidentally persisting in memory through unintended copies and reduces the attack surface for memory-based exploits.
Enter the URL of a public GitHub repository