How-to write a password-safe class?(如何编写密码安全的类?)
问题描述
这个问题遵循@sharptooth 在 这个相关问题.
This question follows a suggestion made by @sharptooth in this related question.
可以调整 std::string
使其成为密码安全的吗?
Can std::string
be tweaked so that it becomes password-safe ?
如果不是,那么编写密码处理类的指导方针是什么(因此一个类非常关心它写入内存的内容并在销毁之前清除它)?
If not, what would be the guidelines to write a password-handling class (thus a class that takes big care about what it writes to memory and clears it before destruction) ?
推荐答案
是的,先定义一个自定义分配器:
Yes, first define a custom allocator:
template <class T> class SecureAllocator : public std::allocator<T>
{
public:
template<class U> struct rebind { typedef SecureAllocator<U> other; };
SecureAllocator() throw() {}
SecureAllocator(const SecureAllocator&) throw() {}
template <class U> SecureAllocator(const SecureAllocator<U>&) throw() {}
void deallocate(pointer p, size_type n)
{
std::fill_n((volatile char*)p, n*sizeof(T), 0);
std::allocator<T>::deallocate(p, n);
}
};
这个分配器在释放之前将内存归零.现在你输入定义:
This allocator zeros the memory before deallocating. Now you typedef:
typedef std::basic_string<char, std::char_traits<char>, SecureAllocator<char>> SecureString;
不过有个小问题,std::string 可能会使用小字符串优化,在自身内部存储一些数据,没有动态分配.因此,您必须在销毁时明确清除它或使用我们的自定义分配器在堆上分配:
However there is a small problem, std::string may use small string optimization and store some data inside itself, without dynamic allocation. So you must explicitly clear it on destruction or allocate on the heap with our custom allocator:
int main(int, char**)
{
using boost::shared_ptr;
using boost::allocate_shared;
shared_ptr<SecureString> str = allocate_shared<SecureString>(SecureAllocator<SecureString>(), "aaa");
}
这保证在释放之前所有数据都归零,例如包括字符串的大小.
This guarantees that all the data is zeroed before deallocation, including the size of the string, for example.
这篇关于如何编写密码安全的类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何编写密码安全的类?


基础教程推荐
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 从 std::cin 读取密码 2021-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01