如何清除(用随机字节覆盖)std :: string内部缓冲区? [英] How to cleanse (overwrite with random bytes) std::string internal buffer?
问题描述
考虑一个场景,其中 std :: string
用于存储一个秘密。一旦消耗掉它并且不再需要它,最好将其清理,即覆盖包含它的内存,从而隐藏 secret 。
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 overwrite the memory that contained it, thus hiding the secret.
std :: string
提供函数 const char * data()
返回指向的指针(因为C + +11)连续记忆。
std::string
provides a function const char* data()
returning a pointer to (since C++11) continous memory.
现在,由于内存是连续的,并且由于作用域结束,变量将在清除后立即销毁,这样可以安全:
Now, since the memory is continous and the variable will be destroyed right after the cleanse due to scope end, would it be safe to:
char* modifiable = const_cast<char*>(secretString.data());
OpenSSL_cleanse(modifiable, secretString.size());
根据此处引用的标准:
$ 5.2.11 / 7-注意:根据对象的类型,由
const_cast $ c产生的指针,左值或指向数据成员的指针的写操作$ c>丢弃
const限定符
68 可能会产生不确定的行为(7.1.5.1)。
$5.2.11/7 - Note: Depending on the type of the object, a write operation through the pointer, lvalue or pointer to data member resulting from a
const_cast
that casts away aconst-qualifier
68 may produce undefined behavior (7.1.5.1).
否则可能会有所建议,但是上面的条件(连续的,将要删除的)是否安全?
That would advise otherwise, but do the conditions above (continuous, to-be-just-removed) make it safe?
推荐答案
这可能是安全的。
但是,由于 C ++ 11
,因此 std ::字符串
必须实现为连续数据,以便您可以使用其第一个元素& secretString [0]
的地址安全地访问其内部数组。 / p>
However, since C++11
, a std::string
must be implemented as contiguous data so you can safely access its internal array using the address of its first element &secretString[0]
.
if(!secretString.empty()) // avoid UB
{
char* modifiable = &secretString[0];
OpenSSL_cleanse(modifiable, secretString.size());
}
这篇关于如何清除(用随机字节覆盖)std :: string内部缓冲区?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!