1

From a security standpoint, it's better to zero out a password once it's no longer in use by a program.

In other words, I'd like to have some kind of secure string instead of std::string that would zero out the memory area where the old C-style string was stored upon destruction or upon assigning it a new value.

Implementing such a string by myself is not a problem, but it would take quite some time to implement all the extensive features of std::string that I would like to have.

Are there any ready-made solutions for this?


I previously asked this question on Stack Overflow.

1 Answer 1

0

I found a solution in this answer.

CryptoPP::AllocatorWithCleanup is a custom allocator provided by the Crypto++ library. It zeroes out the allocated memory upon deallocation.
Deallocation occurs when a string is destroyed or when its buffer overflows, resulting in the creation of a new buffer of larger size while the old buffer is freed (may be other scenarios).
However, it may not trigger when using clear() or resize() operations.

My solution, based on that answer:

SecureString.h

#pragma once

#include <string>
#include <cryptopp/secblock.h>

template <typename CharType, typename TraitsType = std::char_traits<CharType>>
using BasicSecureString = std::basic_string<CharType, TraitsType, CryptoPP::AllocatorWithCleanup<CharType>>;

using SecureString = BasicSecureString<char>;

CMAkeLists.txt

target_link_libraries(${EXECUTABLE_NAME} cryptopp)

How to install the library on Ubuntu-based distributions:

sudo apt install libcrypto++-dev

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.