如何编写密码安全的类?

How-to write a password-safe class?(如何编写密码安全的类?)
本文介绍了如何编写密码安全的类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

限时送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.

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

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

OpenGL transforming objects with multiple rotations of Different axis(OpenGL 变换不同轴多次旋转的对象)
GLFW first responder error(GLFW 第一响应者错误)
SOIL not linking correctly(SOIL 连接不正确)
Core profile vs version string? Only getting GLSL 1.3/OGL 3.0 in mesa 10.0.1(核心配置文件与版本字符串?在 mesa 10.0.1 中只获得 GLSL 1.3/OGL 3.0)
What is the range of OpenGL texture ID?(OpenGL 纹理 ID 的范围是多少?)
How taxing are OpenGL glDrawElements() calls compared to basic logic code?(与基本逻辑代码相比,OpenGL glDrawElements() 调用的繁重程度如何?)