如何编写密码安全的类?

时间:2023-05-10
本文介绍了如何编写密码安全的类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

限时送ChatGPT账号..

这个问题遵循@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.

这篇关于如何编写密码安全的类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一篇:C++ 构造“placement new"的用途是什么? 下一篇:当它绑定到调用函数中的 const 引用时,它的返回值的生命周期如何扩展到调用函数的范围?

相关文章