ektrah/libsodium-core

Add overloads that write to buffer instead of allocating a new array

Closed this issue · 2 comments

Currently, encryption/hashing functions allocate new byte arrays with internally-specified lengths. To reduce the number of GC allocations, I would like to be able to pass in my own buffer (and offset) for these functions to write to. This would also more closely represent the usage of the libsodium C functions.

I will use SecretAeadChaCha20Poly1305 as an example:

byte[] Encrypt(byte[] message, byte[] nonce, byte[] key, byte[] additionalData = null)
This currently allocates a new byte array, stores the encrypted bits in that new array, and then returns the new array to the user.

int Encrypt(byte[] buffer, int offset, byte[] message, byte[] nonce, byte[] key, byte[] additionalData = null)
This is the additional overload I would like to add to the API. No (managed) array is allocated, but instead is provided by the user with an offset parameter. The encrypted bits are stored in the buffer, starting at the byte at offset, and the function returns the number of bytes written to the buffer.

There has been work in progress to support Span/Memory instead of raw bytes, which should solve the issue of allocations, but looks like progress stopped at some point. Might have to pick that up soon, as it's kinda crucial for a library like this to let consumers take control of memory allocations. It's definitely on the roadmap, but I cannot promise anything, yet.

Non-allocating overloads would be a very nice enhancement. However, since libsodium-core is now in maintenance mode, I don't think this is worth the effort. Going forward, it is recommended to use one of the alternative libsodium bindings.