Golang加密接口和易失性内存

How do I securely manage cryptographic secrets stored in/behind interfaces?

My problem is as follows:

I have a long running application which does encryption using an implementation of the cipher.AEAD interface. The only way to get an instance of the interface (chacha20poly1305) is though the method:

func New([]byte) (cipher.AEAD, error)

I create and use the instance for some time, then "delete" the instance and wishes to make sure that the key cannot be recovered hereafter. For this reason I want to avoid the key material being swapped to disk.

Using reflection and unsafe, I can:

  1. Obtain the size and a pointer to the underlying memory
  2. Do mlock (to avoid the content being swapped to disk)
  3. Use the instance
  4. Do a "memset" (to remove the key material)
  5. Use munlock

There is one problem though, the instances may be allocated all over the heap. Assuming I need more than "ulimit -l" of these, I will likely run out, even though the instances are only 32 bytes each.

Is there some way around this? Ideally a way to have a smaller "secure mlocked heap" where only these structs are allocated. Alternatively some way to cast memory (say allocated using https://github.com/awnumar/memguard) to a specific implementation (not exposed) of the interface, then setup the struct manually (rather than with New([]byte) -> cipher.AEAD)