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.
这篇关于如何编写密码安全的类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何编写密码安全的类?
基础教程推荐
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- CString 到 char* 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
