java ASE加密 代碼如下
import org.apache.commons.codec.binary.Base64;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
/**
* aes加密工具類
*
* @author chengh
* @date 2021/07/14
*/
public class AesEncryptUtils {
/**
* 參數分别代表 算法名稱/加密模式/資料填充方式
*/
private static final String ALGORITHMS = "AES/CBC/PKCS5Padding";
/**
* 初始化向量(根據需求調整向量的值, 也可以将向量添加到入參變量中)
*/
private static final byte[] SIV = new byte[16];
/**
* 加密
*
* @param content 加密的字元串
* @param encryptKey key值
* @return 加密後的内容
* @throws Exception 異常
*/
public static String encrypt(String content, String encryptKey) throws Exception {
KeyGenerator.getInstance("AES").init(128);
Cipher cipher = Cipher.getInstance(ALGORITHMS);
// 加密向量
IvParameterSpec iv = new IvParameterSpec(SIV);
cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(encryptKey.getBytes(), "AES"), iv);
byte[] b = cipher.doFinal(content.getBytes(StandardCharsets.UTF_8));
// 采用base64算法進行轉碼,避免出現中文亂碼
return Base64.encodeBase64String(b);
}
/**
* 解密
*
* @param encryptStr 解密的字元串
* @param decryptKey 解密的key值
* @return 解密後的内容
* @throws Exception 異常
*/
public static String decrypt(String encryptStr, String decryptKey) throws Exception {
KeyGenerator.getInstance("AES").init(128);
Cipher cipher = Cipher.getInstance(ALGORITHMS);
// 加密向量
IvParameterSpec iv = new IvParameterSpec(SIV);
cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(decryptKey.getBytes(), "AES"), iv);
// 采用base64算法進行轉碼,避免出現中文亂碼
byte[] encryptBytes = Base64.decodeBase64(encryptStr);
byte[] decryptBytes = cipher.doFinal(encryptBytes);
return new String(decryptBytes);
}
}