使用AES加解密,加密时里面包含偏移量
package com.citicsc.finance.agent.util;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import org.springframework.util.Base64Utils;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class AESUtil {
private static final String KEY_ALGORITHM = "AES";
private static final String DEFAULT_CIPHER_ALGORITHM = "AES/CBC/PKCS5Padding";//默认的加密算法
private static int offset = 16;
public static void main(String[] args) {
System.out.println(AESUtil.encrypt("147258", "cmx.algo.PF.2014", "ItAqS_lIqUiD_pRo"));
System.out.println(AESUtil.decrypt("WuQ8bQB0GjNbMbjXWPRibw==", "cmx.algo.PF.2014", "ItAqS_lIqUiD_pRo"));
}
public static String encrypt(String content, String secretKey, String ivKey) {
try {
//构造密钥
SecretKeySpec skey = new SecretKeySpec(secretKey.getBytes(), KEY_ALGORITHM);
//创建初始向量iv用于指定密钥偏移量(可自行指定但必须为128位),因为AES是分组加密,下一组的iv就用上一组加密的密文来充当
IvParameterSpec iv = new IvParameterSpec(ivKey.getBytes(), 0, offset);
//创建AES加密器
Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);
byte[] byteContent = content.getBytes();
//使用加密器的加密模式
cipher.init(Cipher.ENCRYPT_MODE, skey, iv);
// 加密
byte[] result = cipher.doFinal(byteContent);
//使用BASE64对加密后的二进制数组进行编码
return Base64Utils.encodeToString(result);
} catch (Exception ex) {
log.error("encrypt", ex);
throw new RuntimeException(ex);
}
}
/**
* AES 解密操作
*
* @param content
* @param password
* @return
*/
public static String decrypt(String content, String secretKey, String ivKey) {
try {
SecretKeySpec skey = new SecretKeySpec(secretKey.getBytes(), KEY_ALGORITHM);
IvParameterSpec iv = new IvParameterSpec(ivKey.getBytes(), 0, offset);
Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);
//解密时使用加密器的解密模式
cipher.init(Cipher.DECRYPT_MODE, skey, iv);// 初始化
byte[] result = cipher.doFinal(Base64Utils.decode(content.getBytes()));
return new String(result); // 解密
} catch (Exception ex) {
log.error("decrypt", ex);
throw new RuntimeException(ex);
}
}
}