Skip to content

Commit

Permalink
chore(perf): Store Cipher instance in ThreadLocal.
Browse files Browse the repository at this point in the history
  • Loading branch information
nstdio committed Apr 3, 2022
1 parent f27ef14 commit 1e1a5a1
Showing 1 changed file with 16 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@
import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.CipherOutputStream;
import javax.crypto.NoSuchPaddingException;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
Expand Down Expand Up @@ -49,6 +48,7 @@ class EncryptedStreamFactory implements StreamFactory {
private final String transformation;
private final String algorithm;
private final String provider;
private final ThreadLocal<Cipher> threadLocalCipher;

public EncryptedStreamFactory(StreamFactory delegate, Key publicKey, Key privateKey, String transformation, String provider) {
this.delegate = delegate;
Expand All @@ -57,19 +57,33 @@ public EncryptedStreamFactory(StreamFactory delegate, Key publicKey, Key private
this.transformation = transformation;
this.algorithm = algo(transformation);
this.provider = provider;
this.threadLocalCipher = new ThreadLocal<>();
}

private static String algo(String transformation) {
int i = transformation.indexOf('/');
return i == -1 ? transformation : transformation.substring(0, i);
}

private Cipher cipher() throws NoSuchPaddingException, NoSuchAlgorithmException, NoSuchProviderException {
@SneakyThrows
private Cipher createCipher() {
return hasProvider()
? Cipher.getInstance(transformation, provider)
: Cipher.getInstance(transformation);
}

private Cipher cipher() {
var thCipher = threadLocalCipher;

if (thCipher.get() == null) {
var cipher = createCipher();
thCipher.set(cipher);
return cipher;
}

return thCipher.get();
}

private boolean hasProvider() {
return provider != null;
}
Expand Down

0 comments on commit 1e1a5a1

Please sign in to comment.