c++ - 如何编写密码安全类?

标签 c++ string memory

这个问题遵循@sharptooth 在this related question 中提出的建议。 .

可以调整 std::string 使其成为密码安全的吗?

如果不是,编写密码处理类的指导方针是什么(因此该类非常关心它写入内存的内容并在销毁之前将其清除)?

最佳答案

是的,首先定义一个自定义分配器:

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);
    }
};

此分配器在解除分配之前将内存归零。现在你输入def:

typedef std::basic_string<char, std::char_traits<char>, SecureAllocator<char>> SecureString;

不过有个小问题,std::string 可能会使用小字符串优化,并在自身内部存储一些数据,无需动态分配。因此,您必须在销毁时明确清除它或使用我们的自定义分配器在堆上分配:

int main(int, char**)
{
    using boost::shared_ptr;
    using boost::allocate_shared;
    shared_ptr<SecureString> str = allocate_shared<SecureString>(SecureAllocator<SecureString>(), "aaa");

}

这保证了所有数据在释放之前都归零,例如包括字符串的大小。

关于c++ - 如何编写密码安全类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3785582/

相关文章:

memory - 如何在 spartan 3e fpga 中流式传输小视频?

c++ - C++编译器如何保证常量成员变量的线程安全?

c++ - 在启用基于它的构造函数时是否总是需要复制类模板参数?

c++ - "most people seriously overuse casts"怎么办?

c++ - 用OpenGL绘制球体

python - str.format 和 string.Formatter.format 之间的区别

javascript - 使用javascript删除字符串中最后出现的逗号

java - 将字符数组列表转换为字符串的最佳方法

c++ - 返回指向同一个变量的指针会泄漏内存吗?

c# - 以编程方式查找对象使用的内存