This commit is contained in:
ran.shang
2025-12-29 16:06:48 +08:00
parent b853edcfde
commit ee95dfa2c2
1600 changed files with 6997 additions and 7445 deletions

View File

@@ -0,0 +1,50 @@
package com.senmesh.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);
}
}