AesUtils工具类
import org.apache.commons.codec.binary.Base64;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
public class AesUtils {
private static final String AES_ALGORITHM = "AES";
private static final String PADDING_MODE = "AES/ECB/PKCS5Padding";
private AesUtils() {
}
public static String encrypt(String key, String text) throws Exception {
SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), AES_ALGORITHM);
Cipher cipher = Cipher.getInstance(PADDING_MODE);
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
byte[] bytes = cipher.doFinal(text.getBytes(StandardCharsets.UTF_8));
return Base64.encodeBase64String(bytes);
}
public static String decrypt(String keySec, String base64Data) throws Exception {
KeyGenerator kgen = KeyGenerator.getInstance(AES_ALGORITHM);
SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG" );
secureRandom.setSeed(keySec.getBytes());
kgen.init(128, secureRandom);
SecretKey secretKey = kgen.generateKey();
byte[] enCodeFormat = secretKey.getEncoded();
SecretKeySpec keySpec = new SecretKeySpec(enCodeFormat, AES_ALGORITHM);
Cipher cipher = Cipher.getInstance(AES_ALGORITHM);// 创建密码器
cipher.init(Cipher.DECRYPT_MODE, keySpec);// 初始化
byte[] result = cipher.doFinal(Base64.decodeBase64(base64Data));
return new String(result);
}