Securely resizing and deletion of std::string

I have a class that contains a a string. Currently, it's an std::wstring but does not have to be. I had read here that std::string should not be used but I am wondering if something like this would work:

if (aString.length() == aString.capacity() )
{
    std::wstring oldString = aString;
    aString = wstring(aString);
    aString.reserve(PREALLOCATION_AMOUNT);
    SecureZeroMemory((PVOID)oldString.c_str(),oldString.size());
    oldString.clear();
}

would this basically equate to a secure realloc of the string buffer? If not is there a better solution?

Answers


It's not guaranteed that c_str() will point to the original buffer and not make a copy. That's probably the way it works, but there's no way to be sure without looking at your specific implementation of basic_string.

There are enough potential problems with making std::wstring secure that I'd avoid it entirely and find a secure string class or write my own.


I don't know if this would actually work, but perhaps you could try this:

#include <algorithm>
#include <string>

// ...

std::string password = "sekrit";
std::fill(password.begin(), password.end(), 0);

Of course, this assumes that your string is never resized. If it is, you will lose access to the memory where the beginning of the string WAS stored. As has been pointed out by others, it's probably a bad idea.


Need Your Help

Boost shared_memory_object problem with types different from char

c++ boost concurrency shared-memory interprocess

I have a problem with boost shared_memory_object and mapped_region. I want to write a set of objects (structures) in the memory object. If the structure contains just a char, everything is ok; if I...

getattr() versus dict lookup, which is faster?

python performance getattr dynamic-attributes

A somewhat noobish, best practice question. I dynamically look up object attribute values using object.__dict__[some_key] as a matter of habit. Now I am wondering which is better/faster: my current...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.