package com.gec.it.excel.util; 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.io.UnsupportedEncodingException; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; /** * @Author Miracle xyt * @Date 2023/8/11 13:33 * @Version 1.0 */ public class AESUtils { private static final String KEY_ALGORITHM = "AES"; private static final String CHARSET = "UTF-8"; private static final String DEFAULT_CIPHER_ALGORITHM = "AES/ECB/PKCS5Padding";// 默认的加密算法 private static final String SECURERANDOM = "SHA1PRNG"; // 指定算法, 避免系统不同产生问题 private static final String SECRET_KEY = "******";// 你的加密密钥 /** * AES 加密操作 * * @param content 待加密内容 * @return 返回Base64转码后的加密数据 */ public static String encode(String content) { try { // 创建密码器 Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM); byte[] byteContent = content.getBytes(CHARSET); // 初始化为加密模式的密码器 cipher.init(Cipher.ENCRYPT_MODE, getSecretKey()); // 加密 byte[] result = cipher.doFinal(byteContent); byte[] bytes = Base64.encodeBase64(result); //通过Base64转码返回 return new String(bytes); } catch (Exception ex) { // LogUtil.e(AESUtils.class, ex.getMessage()); } return null; } /** * AES 解密操作 * * @param content * @return */ public static String decode(String content) { try { //实例化 Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM); //使用密钥初始化,设置为解密模式 cipher.init(Cipher.DECRYPT_MODE, getSecretKey()); byte[] byteContent = content.getBytes(CHARSET); byte[] bytes = Base64.decodeBase64(byteContent); //执行操作 byte[] result = cipher.doFinal(bytes); return new String(result); } catch (Exception ex) { // LogUtil.e(AESUtils.class, ex.getMessage()); } return null; } /** * 生成加密秘钥 * * @return */ public static SecretKeySpec getSecretKey() { //返回生成指定算法密钥生成器的 KeyGenerator 对象 KeyGenerator kg = null; try { kg = KeyGenerator.getInstance(KEY_ALGORITHM); SecureRandom random = SecureRandom.getInstance(SECURERANDOM); random.setSeed(SECRET_KEY.getBytes(CHARSET)); //AES 要求密钥长度为 128 kg.init(128, random); //生成一个密钥 SecretKey secretKey = kg.generateKey(); return new SecretKeySpec(secretKey.getEncoded(), KEY_ALGORITHM);// 转换为AES专用密钥 } catch (NoSuchAlgorithmException ex) { // LogUtil.e(AESUtils.class, ex.getMessage()); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return null; } }
示例:
package com.gec.it.excel.util; /** * @Author Miracle xyt * @Date 2023/8/11 13:35 * @Version 1.0 */ public class Aestest { public static void main(String[] args) { //加密,得到加密密码 String decode2 = AESUtils.encode("TQ8A+q#5n"); System.out.println("加密密码:" + decode2); //解密,得到解密密码 String decode = AESUtils.decode("VOL/i4+Kq7/swd5IMEwAlQ=="); System.out.println("解密密码:" + decode); } }