init
This commit is contained in:
50
src/main/java/com/newyetai/common/util/AESUtils.java
Normal file
50
src/main/java/com/newyetai/common/util/AESUtils.java
Normal file
@@ -0,0 +1,50 @@
|
||||
package com.newyetai.common.util;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.Security;
|
||||
|
||||
import javax.crypto.Cipher;
|
||||
import javax.crypto.SecretKey;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
|
||||
import org.springframework.util.Base64Utils;
|
||||
|
||||
|
||||
/**
|
||||
* @author sr on 2024-02-22
|
||||
*/
|
||||
public class AESUtils {
|
||||
|
||||
public static final String TRANSFORM_ECB_5 = "AES/ECB/PKCS5Padding";
|
||||
public static final String TRANSFORM_ECB_7 = "AES/ECB/PKCS7Padding";
|
||||
public static final String TRANSFORM_ECB = "AES/ECB/NoPadding";
|
||||
|
||||
static {
|
||||
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
|
||||
}
|
||||
|
||||
public static Cipher getCipher(String transform) throws Exception {
|
||||
if (TRANSFORM_ECB_7.equals(transform)) {
|
||||
return Cipher.getInstance(transform, "BC");
|
||||
} else {
|
||||
return Cipher.getInstance(transform);
|
||||
}
|
||||
}
|
||||
|
||||
public static String encrypt(String input, String key, String transform) throws Exception {
|
||||
Cipher cipher = getCipher(transform);
|
||||
SecretKey keySpec = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "AES");
|
||||
cipher.init(Cipher.ENCRYPT_MODE, keySpec);
|
||||
return Base64Utils.encodeToString(cipher.doFinal(input.getBytes(StandardCharsets.UTF_8)));
|
||||
}
|
||||
|
||||
public static String decrypt(String input, String key, String transform)
|
||||
throws Exception {
|
||||
Cipher cipher = getCipher(transform);
|
||||
SecretKey keySpec = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "AES");
|
||||
cipher.init(Cipher.DECRYPT_MODE, keySpec);
|
||||
return new String(cipher.doFinal(Base64Utils.decode(input.getBytes(StandardCharsets.UTF_8))),
|
||||
StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user