考虑一个场景,其中std::string
用于存储a secret。一旦它被消耗并且不再需要,最好清理它,即覆盖包含它的内存,从而隐藏它secret.
std::string
提供一个函数const char* data()
返回指向 (C++11 起)连续内存的指针。
现在,由于记忆是连续的and由于范围结束,变量将在清理后立即被销毁,是否安全:
char* modifiable = const_cast<char*>(secretString.data());
OpenSSL_cleanse(modifiable, secretString.size());
根据此处引用的标准:
$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 a const-qualifier
68 may produce undefined behavior (7.1.5.1).
否则的话,但是上述条件(连续的、即将被移除的)是否使其安全?
该标准明确规定您不得写入const char*
由返回data()
,所以不要这样做。
有一些完全安全的方法来获取可修改的指针:
if (secretString.size())
OpenSSL_cleanse(&secretString.front(), secretString.size());
或者,如果字符串可能已经收缩,并且您想确保擦除其整个容量:
if (secretString.capacity()) {
secretString.resize(secretString.capacity());
OpenSSL_cleanse(&secretString.front(), secretString.size());
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)