How-to write a password-safe class?

前端 未结 1 1327
花落未央
花落未央 2020-12-01 18:13

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

Can std::string be tweaked so that it becomes password-safe ?

I

1条回答
  •  独厮守ぢ
    2020-12-01 19:08

    Yes, first define a custom allocator:

    template  class SecureAllocator : public std::allocator
    {
    public:
        template struct rebind { typedef SecureAllocator other; };
    
        SecureAllocator() throw() {}
        SecureAllocator(const SecureAllocator&) throw() {}
        template  SecureAllocator(const SecureAllocator&) throw() {}
    
        void deallocate(pointer p, size_type n)
        {
            std::fill_n((volatile char*)p, n*sizeof(T), 0);
            std::allocator::deallocate(p, n);
        }
    };
    

    This allocator zeros the memory before deallocating. Now you typedef:

    typedef std::basic_string, SecureAllocator> 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 str = allocate_shared(SecureAllocator(), "aaa");
    
    }
    

    This guarantees that all the data is zeroed before deallocation, including the size of the string, for example.

    0 讨论(0)
提交回复
热议问题