Reputation: 1035
I got a string variable (contains passphrase) and would like to overwrite it's value with a sequence of '0' before the variable is released. I tought about doing something like:
void overwrite(std::string &toOverwrite){
if(toOverwrite.empty())
return;
else{
std::string removeString;
size_t length = toOverwrite.size();
for(int i = 0; i < length; i++){
removeString += "0";
}
toOverwrite = removeString;
}
}
But somehow this doesn't feel right.
toOverwrite = removeString
really replace toOverwrite
or just make that the "pointer" of toOverwrite
will point to removeString
?Maybe I should use the std::string::replace
method or change the datatype to char* / byte[]?
Upvotes: 0
Views: 744
Reputation: 9354
Chances are that will just swap and free pointers, leaving the passphrase somewhere in memory which is no longer pointed to. If you want to overwrite the string data, do:
std::fill(toOverwrite.begin(), toOverwrite.end(), '0');
And you don't need a test for an empty string either.
Upvotes: 2