How to cleanse (overwrite with random bytes) std::string internal buffer?

后端 未结 2 945
情书的邮戳
情书的邮戳 2021-02-12 05:39

Consider a scenario, where std::string is used to store a secret. Once it is consumed and is no longer needed, it would be good to cleanse it, i.e overwrit

2条回答
  •  醉梦人生
    2021-02-12 06:33

    The standard explicitly says you must not write to the const char* returned by data(), so don't do that.

    There are perfectly safe ways to get a modifiable pointer instead:

    if (secretString.size())
      OpenSSL_cleanse(&secretString.front(), secretString.size());
    

    Or if the string might have been shrunk already and you want to ensure its entire capacity is wiped:

    if (secretString.capacity()) {
      secretString.resize(secretString.capacity());
      OpenSSL_cleanse(&secretString.front(), secretString.size());
    }
    

提交回复
热议问题