Skip to content

Instantly share code, notes, and snippets.

@overheadhunter
Last active October 5, 2022 11:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save overheadhunter/f3969950c0fdbaecaa77c857b2246cc5 to your computer and use it in GitHub Desktop.
Save overheadhunter/f3969950c0fdbaecaa77c857b2246cc5 to your computer and use it in GitHub Desktop.
Example reproducing the issue described in https://bugs.openjdk.org/browse/JDK-8280703
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.ByteBuffer;
import java.security.GeneralSecurityException;
/**
* This demonstrates a memory allocation problem in com.sun.crypto.provider.CipherCore.
* <p>
* To reproduce the issue, run this class using:
* <code>-XX:+FlightRecorder -XX:StartFlightRecording=dumponexit=true,filename=decryptAlloc.jfr</code>
*/
public class DecryptAlloc {
public static void main(String[] args) throws GeneralSecurityException {
var cipher = Cipher.getInstance("AES/CTR/NoPadding");
var key = new SecretKeySpec(new byte[32], "AES");
var iv = new IvParameterSpec(new byte[16]);
// encryption runs fine:
cipher.init(Cipher.ENCRYPT_MODE, key, iv);
ByteBuffer cleartext = ByteBuffer.allocate(4096);
ByteBuffer ciphertext = ByteBuffer.allocate(cipher.getOutputSize(4096));
for (int i = 0; i < 1_000_000; i++) {
cleartext.clear();
ciphertext.clear();
cipher.doFinal(cleartext, ciphertext);
}
// decryption causes lots of allocations:
cipher.init(Cipher.DECRYPT_MODE, key, iv);
for (int i = 0; i < 1_000_000; i++) {
cleartext.clear();
ciphertext.clear();
cipher.doFinal(ciphertext, cleartext);
}
// "Blackhole.consume()" for dummies:
System.out.println(cleartext);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment