废话不多说,直接上代码,复制粘贴即可用
package com.xx.xx.utils;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Base64Utils;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
/**
* 加密工具类
*
* @author yuan
*/
public class CipherUtil {
private static final Logger LOGGER = LoggerFactory.getLogger(CipherUtil.class);
protected static final String SECRET_KEY = "sdlfjo234L32fv0o9iNG0LL!!*&1%$#@";
/**
* 对称加密
*/
private static Aes aes;
/**
* 获取对称加密算法
*
* @return 加密算法
*/
public static Aes aes() {
if (null == aes) {
aes = new Aes();
}
return aes;
}
/**
* AES加密工具类
*
* @author yuan
*/
public static class Aes {
private static final String KEY_ALGORITHM = "AES";
/**
* 默认的加密算法
*/
private static final String DEFAULT_CIPHER_ALGORITHM = "AES/ECB/PKCS5Padding";
/**
* 密码器
*/
private static Cipher cipher;
private Cipher getCipher() throws NoSuchPaddingException, NoSuchAlgorithmException {
if (null == cipher) {
cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);
}
return cipher;
}
/**
* AES 加密操作
*
* @param content 待加密内容
* @return 返回Base64转码后的加密数据
*/
public synchronized String encrypt(String content) {
try {
// 创建密码器
Cipher cipher = getCipher();
byte[] byteContent = content.getBytes(StandardCharsets.UTF_8);
// 初始化为加密模式
cipher.init(Cipher.ENCRYPT_MODE, getSecretKey(SECRET_KEY));
// 加密
byte[] result = cipher.doFinal(byteContent);
//base64编码
return byte2Base64(result);
} catch (Exception ex) {
LOGGER.error("数据加密失败,content={},stack info={}", content, ExceptionUtils.getFullStackTrace(ex));
throw new ArithmeticException("数据加密失败");
}
}
/**
* AES 解密操作
*
* @param content 解密内容
* @return 解密内容
*/
public synchronized String decrypt(final String content) {
try {
//实例化
Cipher cipher = getCipher();
//初始化为解密模式
cipher.init(Cipher.DECRYPT_MODE, getSecretKey(SECRET_KEY));
//解密
byte[] result = cipher.doFinal(base642Byte(content));
return new String(result, StandardCharsets.UTF_8);
} catch (Exception ex) {
LOGGER.error("数据解密失败,content={},stack info={}", content, ExceptionUtils.getFullStackTrace(ex));
throw new ArithmeticException("数据解密失败");
}
}
/**
* 生成加密秘钥
*
* @return 密钥
*/
public SecretKeySpec getSecretKey(final String key) {
try {
//示例化密钥生成器
KeyGenerator kg = KeyGenerator.getInstance(KEY_ALGORITHM);
// 指定算法名称,不同的系统上生成的key是相同的。
SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
random.setSeed(key.getBytes(StandardCharsets.UTF_8));
//AES 要求密钥长度为 128
kg.init(128, random);
//生成一个密钥
SecretKey secretKey = kg.generateKey();
// 转换为AES专用密钥
return new SecretKeySpec(secretKey.getEncoded(), KEY_ALGORITHM);
} catch (NoSuchAlgorithmException ex) {
LOGGER.error("数据密钥生成失败,stack info=" + ExceptionUtils.getFullStackTrace(ex));
throw new ArithmeticException("数据密钥生成失败");
}
}
}
/**
* 字节数组转Base64编码
*
* @param bytes 内容字节码
* @return base64编码
*/
public static String byte2Base64(byte[] bytes) {
return Base64Utils.encodeToUrlSafeString(bytes);
}
/**
* Base64编码转字节数组
*
* @param base64Key base64编码
* @return 字节数组
* @throws IOException 异常
*/
public static byte[] base642Byte(String base64Key) throws IOException {
return Base64Utils.decodeFromUrlSafeString(base64Key);
}
public static void main(String[] args) {
String content = "D:\\attachment\\file.docx";
System.out.println("原文=" + content);
String s1 = CipherUtil.aes().encrypt(content);
System.out.println("加密结果=" + s1);
System.out.println("解密结果=" + CipherUtil.aes().decrypt(s1));
}
}