samedi 7 décembre 2019

Can I use a custom allocator for std::array for secure cryptographic keys?

I know std::array is completely allocated in the stack, but this question is motivated by security concerns that require two things:

  1. The data in std::array will be zerod or randomized on destruction
  2. The data in std::array will be locked, such that it never goes to disk neither on crash or on swap memory

Usually, with std::vector, the solution is to create a custom allocator that does these things. However, for std::array, I don't see how to do this, and hence this question.

The best I could do is this:

template <typename T, typename Size>
struct SecureArray : public std::array<T, Size>
{
    virtual ~SecureArray()
    {
        std::vector<uint8_t> d = RandomBytes(Size); // generates Size random bytes
        std::memcpy(this->data(), d.data(), Size);
    }
}

But this obviously lacks memory locking and complicates the performance scheme of std::array that is to be gained by using std::array in the first place.

Is there any better solution?

Aucun commentaire:

Enregistrer un commentaire