perf[aes]: 提示Aes加密的性能

This commit is contained in:
godotg
2022-07-07 20:06:36 +08:00
parent e8b1d8f079
commit 22acf58aa8
2 changed files with 26 additions and 14 deletions
@@ -20,6 +20,7 @@ import io.netty.util.concurrent.FastThreadLocal;
import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
@@ -46,13 +47,6 @@ public abstract class AesUtils {
*/
private static final String ALGORITHM_STR = "AES/ECB/PKCS5Padding";
private static final FastThreadLocal<Cipher> LOCAL_CIPHER = new FastThreadLocal<Cipher>() {
@Override
protected Cipher initialValue() throws NoSuchPaddingException, NoSuchAlgorithmException {
return Cipher.getInstance(ALGORITHM_STR);
}
};
static {
try {
KEY = new SecretKeySpec(KEY_STR.getBytes(StringUtils.DEFAULT_CHARSET_NAME), ALGORITHM);
@@ -61,6 +55,24 @@ public abstract class AesUtils {
}
}
private static final FastThreadLocal<Cipher> LOCAL_ENCRYPT_CIPHER = new FastThreadLocal<Cipher>() {
@Override
protected Cipher initialValue() throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException {
var cipher = Cipher.getInstance(ALGORITHM_STR);
cipher.init(Cipher.ENCRYPT_MODE, KEY);
return cipher;
}
};
private static final FastThreadLocal<Cipher> LOCAL_DECRYPT_CIPHER = new FastThreadLocal<Cipher>() {
@Override
protected Cipher initialValue() throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException {
var cipher = Cipher.getInstance(ALGORITHM_STR);
cipher.init(Cipher.DECRYPT_MODE, KEY);
return cipher;
}
};
/**
* 对str进行AES加密
@@ -81,8 +93,7 @@ public abstract class AesUtils {
public static byte[] encrypt(byte[] bytes) {
try {
var cipher = LOCAL_CIPHER.get();
cipher.init(Cipher.ENCRYPT_MODE, KEY);
var cipher = LOCAL_ENCRYPT_CIPHER.get();
return cipher.doFinal(bytes);
} catch (Exception e) {
throw new RuntimeException(e);
@@ -108,8 +119,7 @@ public abstract class AesUtils {
public static byte[] decrypt(byte[] bytes) {
try {
var cipher = LOCAL_CIPHER.get();
cipher.init(Cipher.DECRYPT_MODE, KEY);
var cipher = LOCAL_DECRYPT_CIPHER.get();
return cipher.doFinal(bytes);
} catch (Exception e) {
throw new RuntimeException(e);
@@ -23,9 +23,11 @@ public class AesUtilsTest {
@Test
public void test() {
String passWord = "hello world";
String encodePassWorld = AesUtils.getEncryptString(passWord);
Assert.assertEquals(passWord, AesUtils.getDecryptString(encodePassWorld));
for (int i = 0; i < 10; i++) {
var passWord = "hello world";
var encodePassWorld = AesUtils.getEncryptString(passWord);
Assert.assertEquals(passWord, AesUtils.getDecryptString(encodePassWorld));
}
}
}