corretto / amazon-corretto-crypto-provider

The Amazon Corretto Crypto Provider is a collection of high-performance cryptographic implementations exposed via standard JCA/JCE interfaces.
Apache License 2.0
238 stars 56 forks source link

Invert function overloading order for AES-GCM doFinal decryption #298

Closed geedo0 closed 1 year ago

geedo0 commented 1 year ago

Issue #, if available:

271

Description of changes: There are 3 overloaded methods for calling into a Cipher module which implement different ways of returning the output of the operation. From a memory management perspective these can be differentiated by whether or not the caller is responsible for allocating memory for the output.

Previously in our implementation, the top layer of the call stack is a method which allocates a buffer for the output and returns the result. For other interfaces in which the caller is responsible for allocating the output buffer we would allocate yet another buffer and copy it over to the buffer the caller gave us. This results in O(n) additional memory allocations and I/O.

This change inverts the call stack so that the top layer returns the result into an output buffer passed by the caller. That way, we only allocate a new output buffer when one is not provided. This gives us another 33% improvement in memory allocation from the benchmarks provided in issue #271.

n.b. Github is kinda inflexible about breaking up PRs so we scooped up the pre-requisite PR in this one. Once that's merged, I'll update this PR to omit the commit.

By submitting this pull request, I confirm that you can use, modify, copy, and redistribute this contribution, under the terms of your choice.

geedo0 commented 1 year ago

What's the advantage of overriding the methods that process ByteBuffer? Those methods are not abstract and JDK provides an implementation for them.

You'd have to ask the original author, I can only guess. Maybe there was some specific change in behavior we needed to enact? In particular, the input buffering and doFinal decryption is unique to our implementation. Could be worth investigating further to reduce our footprint.