如何写一个密码安全类? [英] How-to write a password-safe class?

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

问题描述

这个问题遵循@sharptooth在这个相关问题



可以调整 std :: string 密码安全?



如果没有,那么写一个密码处理类的指导原则是什么(因此一个类需要非常小心它写入内存并清除)

$ p

解决方案

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

  template< class T> class SecureAllocator:public std :: allocator< T> 
{
public:
template< class U> struct rebind {typedef SecureAllocator< U>其他; };

SecureAllocator()throw(){}
SecureAllocator(const SecureAllocator&)throw(){}
template< class U> SecureAllocator(const SecureAllocator&)throw(){}

void deallocate(pointer p,size_type n)
{
std :: fill_n(volatile char * )p,n * sizeof(T),0);
std :: allocator< T> :: deallocate(p,n);
}
};

此分配器在取消分配之前将内存置零。现在你的typedef:

  typedef std :: basic_string< char,std :: char_traits< char>,SecureAllocator< char>安全字符但是有一个小问题,std :: string可以使用小字符串优化和存储一些数据在内部。本身,没有动态分配。所以你必须明确清除它在销毁或分配在堆与我们的自定义分配器:

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

}

这保证所有数据在取消分配之前被清零, strong>包括字符串的大小,例如


This question follows a suggestion made by @sharptooth in this related question.

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;

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.

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆