import org.apache.commons.codec.binary.Base64;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import java.security.Security;
public class AesUtil {
/**
* AES的密钥长度
*/
private static final Integer SECRET_KEY_LENGTH = 128;
private static final String SECRET = "AES";
public static final String KEY = "dASpzH8OitFO9AhcD7uRkw";
private static final String CIPHER_ALGORITHM = "AES/ECB/PKCS7Padding";
static {
Security.addProvider(new BouncyCastleProvider());
}
// 生成AES密钥
public static String generateKey() throws Exception {
KeyGenerator keyGen = KeyGenerator.getInstance("AES");
keyGen.init(SECRET_KEY_LENGTH, new SecureRandom());
return Base64.encodeBase64String(keyGen.generateKey().getEncoded());
}
/**
* AES加密ECB模式PKCS7Padding填充方式
* @param str 字符串
* @param key 密钥
* @return 加密字符串
* @throws Exception 异常信息
*/
public static String encrypt(String str, String key) throws Exception {
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
byte[] keyBytes = key.getBytes(StandardCharsets.UTF_8);
cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(keyBytes, SECRET));
byte[] doFinal = cipher.doFinal(str.getBytes(StandardCharsets.UTF_8));
return new String(Base64.encodeBase64String(doFinal));
}
/**
* AES解密ECB模式PKCS7Padding填充方式
* @param str 字符串
* @param key 密钥
* @return 解密字符串
* @throws Exception 异常信息
*/
public static String decrypt(String str, String key) throws Exception {
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
byte[] keyBytes = key.getBytes(StandardCharsets.UTF_8);
cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(keyBytes, SECRET));
byte[] doFinal = cipher.doFinal(Base64.decodeBase64(str));
return new String(doFinal);
}
public static void main(String[] args) throws Exception {
String str = "a1234567";
System.out.println("字符串:" + str);
String encryptStr = AesUtil.encrypt(str, KEY);
System.out.println("加密后字符串:" + encryptStr);
String decryptStr = AesUtil.decrypt(encryptStr, KEY);
System.out.println("解密后字符串:" + decryptStr);
}
}
java实现AES/ECB/PKCS7Padding加密和解密
最新推荐文章于 2025-03-26 16:28:12 发布