import org.apache.commons.codec.binary.Base64;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
/**
* @author liuzhongxu
* @date 2019/4/16
*/
public class AESUtil {
/**
* 算法名称
*/
public static final String KEY_ALGORITHM = "AES";
/**
* 算法名称 / 加密模式 / 填充方式
*/
public static final String CIPHER_ALGORITHM = "AES/CBC/PKCS5Padding";
/**
* 编码
*/
public static final String CHARSET_NAME = "UTF-8";
/**
*
* 生成密钥 key 对象
* @param keyStr 密钥字符串
* @return 密钥对象
* @throws InvalidKeyException
* @throws NoSuchAlgorithmException
* @throws InvalidKeySpecException
* @throws Exception
*/
private static SecretKey keyGenerator(String keyStr) throws Exception {SecretKeySpec secretKey = new SecretKeySpec(keyStr.getBytes(CHARSET_NAME), KEY_ALGORITHM);
return secretKey;
}
/**
* 加密数据
* @param data 待加密数据
* @param key 密钥
* @return 加密后的数据
*/
public static String encrypt(String data, String key) throws Exception {Key secretKey = keyGenerator(key);
IvParameterSpec iv = new IvParameterSpec(key.getBytes(CHARSET_NAME));
// 实例化 Cipher 对象,它用于完成实际的加密操作
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
// 初始化 Cipher 对象,设置为加密模式
cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv);
byte[] results = cipher.doFinal(data.getBytes(CHARSET_NAME));
// 执行加密操作。加密后的结果通常都会用 Base64 编码进行传输
return Base64.encodeBase64String(results);
}
/**
* 解密数据
* @param data 待解密数据
* @param key 密钥
* @return 解密后的数据
*/
public static String decrypt(String data, String key) throws Exception {Key secretKey = keyGenerator(key);
IvParameterSpec iv = new IvParameterSpec(key.getBytes(CHARSET_NAME));
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
// 初始化 Cipher 对象,设置为解密模式
cipher.init(Cipher.DECRYPT_MODE, secretKey, iv);
// 执行解密操作
return new String(cipher.doFinal(Base64.decodeBase64(data)));
}
public static void main(String[] args) throws Exception {
String source = "工作模式 -->>ECB:电子密码本模式、CBC:加密分组链接模式、CFB:加密反馈模式、OFB:输出反馈模式";
System.out.println("原文:" + source);
String key = "A1B2C3D4A1B2C3D4";
String encryptData = encrypt(source, key);
System.out.println("加密后:" + encryptData);
String decryptData = decrypt(encryptData, key);
System.out.println("解密后:" + decryptData);
}
}
/**
* 计算签名
*/
private static String calculateSign(String source, String accessSecret) throws InvalidKeyException {
try {
//HmacSHA256 加密
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(new SecretKeySpec(accessSecret.getBytes("UTF-8"), "HmacSHA256"));
byte[] signData = mac.doFinal(source.getBytes("UTF-8"));
//bas64 加密
return Base64.getEncoder().encodeToString(signData);
} catch (NoSuchAlgorithmException e) {throw new RuntimeException("HMAC-SHA1 not supported.");
} catch (UnsupportedEncodingException e) {throw new RuntimeException("UTF-8 not supported.");
}
}