最近写了一些关于AES对称加密的东西
第一种
package com.company.AES;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
/**
* AES对称加密和解密
*/
public class AESKeyPairUtils {
/**
* 加密算法
*/
private static final String KEY_ALGORITHM = "AES";
/**
* 签名算法
*/
public static final String SIGN_ALGORITHMS = "SHA1PRNG";
/**
* 加密
*
* @param encodeRules 加密规则
* @param content 加密内容
* @return 加密后的字符串
*/
public static String AESEncode(String encodeRules, String content) {
try {
// 1.构造密钥生成器,指定为AES算法,不区分大小写
KeyGenerator keygen = KeyGenerator.getInstance(KEY_ALGORITHM);
// 2.根据ecnodeRules规则初始化密钥生成器
SecureRandom secureRandom = SecureRandom.getInstance(SIGN_ALGORITHMS);
secureRandom.setSeed(encodeRules.getBytes());
//生成一个128位的随机源,根据传入的字节数组
keygen.init(128, secureRandom);
// 3.产生原始对称密钥
SecretKey originalKey = keygen.generateKey();
// 4.获得原始对称密钥的字节数组
byte[] raw = originalKey.getEncoded();
// 5.根据字节数组生成AES密钥
SecretKey key = new SecretKeySpec(raw, KEY_ALGORITHM);
// 6.根据指定算法AES自成密码器
Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);
// 7.初始化密码器,第一个参数为加密(Encrypt_mode)或者解密解密(Decrypt_mode)操作,第二个参数为使用的KEY
cipher.init(Cipher.ENCRYPT_MODE, key);
// 8.获取加密内容的字节数组(这里要设置为utf-8)不然内容中如果有中文和英文混合中文就会解密为乱码
byte[] byteEncode = content.getBytes(StandardCharsets.UTF_8);
// 9.根据密码器的初始化方式--加密:将数据加密
byte[] byteAES = cipher.doFinal(byteEncode);
// 10.将加密后的数据转换为字符串
// 这里用Base64Encoder中会找不到包
// 解决办法:
// 在项目的Build path中先移除JRE System Library,再添加库JRE System Library,重新编译后就一切正常了。
String AESEncode = new BASE64Encoder().encode(byteAES);
// 11.将字符串返回
return AESEncode;
} catch (Exception e) {
}
// 如果有错就返加null
return null;
}
/**
* 解密
*
* @param encodeRules 解密规则
* @param content 解密内容
* @return 解密后的内容
*/
public static String AESDecode(String encodeRules, String content) {
try {
// 1.构造密钥生成器,指定为AES算法,不区分大小写
KeyGenerator keygen = KeyGenerator.getInstance(KEY_ALGORITHM);
// 2.根据ecnodeRules规则初始化密钥生成器
SecureRandom secureRandom = SecureRandom.getInstance(SIGN_ALGORITHMS);
secureRandom.setSeed(encodeRules.getBytes());
// 生成一个128位的随机源,根据传入的字节数组
keygen.init(128, secureRandom);
// 3.产生原始对称密钥
SecretKey originalKey = keygen.generateKey();
// 4.获得原始对称密钥的字节数组
byte[] raw = originalKey.getEncoded();
// 5.根据字节数组生成AES密钥
SecretKey key = new SecretKeySpec(raw, KEY_ALGORITHM);
// 6.根据指定算法AES自成密码器
Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);
// 7.初始化密码器,第一个参数为加密(Encrypt_mode)或者解密(Decrypt_mode)操作,第二个参数为使用的KEY
cipher.init(Cipher.DECRYPT_MODE, key);
// 8.将加密并编码后的内容解码成字节数组
byte[] byteContent = new BASE64Decoder().decodeBuffer(content);
/*
* 解密
*/
byte[] byteDecode = cipher.doFinal(byteContent);
String AESDecode = new String(byteDecode, StandardCharsets.UTF_8);
return AESDecode;
} catch (Exception e) {
}
return null;
}
public static void main(String[] args) {
/*
* 加密
*/
String secret = "www";
// String data = secret + "_" + "123";
String data = secret + "_" + "1234567890";
String id="12";
String encode = AESEncode(secret, data);
System.out.println("根据输入的规则" + secret + "加密后的密文是:" + encode);
System.out.println("最终数据:"+encode+"_"+id);
/*
* 解密
*/
System.out.println("根据输入的规则" + secret + "解密后的明文是:" + AESDecode(secret, encode));
}
}
使用BASE64Decoder进行加密,在进行编译的时候发现在java9中rt.jar那个包已经被删除了,因此这个方法可能太老了,在未来不会被使用,项目上线有潜在风险。
第二种方案
package com.company.AES;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import java.util.Base64;
public class AESKeyPairUtilsV2 {
/**
* 加密算法
*/
private static final String KEY_ALGORITHM = "AES";
/**
* 签名算法
*/
public static final String SIGN_ALGORITHMS = "SHA1PRNG";
/**
* 加密
*
* @param encodeRules 加密规则
* @param content 加密内容
* @return 加密后的字符串
*/
public static String AESEncode(String encodeRules, String content) {
try {
// 1.构造密钥生成器,指定为AES算法,不区分大小写
KeyGenerator keygen = KeyGenerator.getInstance(KEY_ALGORITHM);
// 2.根据ecnodeRules规则初始化密钥生成器
SecureRandom secureRandom = SecureRandom.getInstance(SIGN_ALGORITHMS);
secureRandom.setSeed(encodeRules.getBytes());
//生成一个128位的随机源,根据传入的字节数组
keygen.init(128, secureRandom);
// 3.产生原始对称密钥
SecretKey originalKey = keygen.generateKey();
// 4.获得原始对称密钥的字节数组
byte[] raw = originalKey.getEncoded();
// 5.根据字节数组生成AES密钥
SecretKey key = new SecretKeySpec(raw, KEY_ALGORITHM);
// 6.根据指定算法AES自成密码器
Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);
// 7.初始化密码器,第一个参数为加密(Encrypt_mode)或者解密解密(Decrypt_mode)操作,第二个参数为使用的KEY
cipher.init(Cipher.ENCRYPT_MODE, key);
// 8.获取加密内容的字节数组(这里要设置为utf-8)不然内容中如果有中文和英文混合中文就会解密为乱码
byte[] byteEncode = content.getBytes(StandardCharsets.UTF_8);
// 9.根据密码器的初始化方式--加密:将数据加密
byte[] byteAES = cipher.doFinal(byteEncode);
// 10.将加密后的数据转换为字符串
Base64.Encoder encoder = Base64.getEncoder();
String AESEncode = encoder.encodeToString(byteAES);
// 11.将字符串返回
return AESEncode;
} catch (Exception e) {
}
// 如果有错就返加null
return null;
}
/**
* 解密
*
* @param encodeRules 解密规则
* @param content 解密内容
* @return 解密后的内容
*/
public static String AESDecode(String encodeRules, String content) {
try {
// 1.构造密钥生成器,指定为AES算法,不区分大小写
KeyGenerator keygen = KeyGenerator.getInstance(KEY_ALGORITHM);
// 2.根据ecnodeRules规则初始化密钥生成器
SecureRandom secureRandom = SecureRandom.getInstance(SIGN_ALGORITHMS);
secureRandom.setSeed(encodeRules.getBytes());
// 生成一个128位的随机源,根据传入的字节数组
keygen.init(128, secureRandom);
// 3.产生原始对称密钥
SecretKey originalKey = keygen.generateKey();
// 4.获得原始对称密钥的字节数组
byte[] raw = originalKey.getEncoded();
// 5.根据字节数组生成AES密钥
SecretKey key = new SecretKeySpec(raw, KEY_ALGORITHM);
// 6.根据指定算法AES自成密码器
Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);
// 7.初始化密码器,第一个参数为加密(Encrypt_mode)或者解密(Decrypt_mode)操作,第二个参数为使用的KEY
cipher.init(Cipher.DECRYPT_MODE, key);
// 8.将加密并编码后的内容解码成字节数组
Base64.Decoder decoder = Base64.getDecoder();
byte[] byteContent = decoder.decode(content);
/*
* 解密
*/
byte[] byteDecode = cipher.doFinal(byteContent);
String AESDecode = new String(byteDecode, StandardCharsets.UTF_8);
return AESDecode;
} catch (Exception e) {
}
return null;
}
public static void main(String[] args) {
/*
* 加密
*/
String secret = "bsdfsfsffsfsf=sadmasdy424234";
// String data = secret + "_" + "123";
String data = secret + "_" + "12345678902424";
String id = "12";
String encode = AESEncode(secret, data);
System.out.println("根据输入的规则" + secret + "加密后的密文是:" + encode);
System.out.println("最终数据:" + encode + "_" + id);
/*
* 解密
*/
System.out.println("根据输入的规则" + secret + "解密后的明文是:" + AESDecode(secret, encode));
}
}
这种方法是解决了Base64Encoder不存在的潜在风险,但是有时会出现解密失败的问题,但是我还没遇到。
第三种方法
package com.company.AES;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.security.SecureRandom;
import java.util.Base64;
/**
* AES加密解密
*/
public class SecurityUtil {
private static final String ENCODING = "UTF-8";
/**
* 加密算法
*/
private static final String KEY_ALGORITHM = "AES";
/**
* 签名算法
*/
private static final String SIGN_ALGORITHMS = "SHA1PRNG";
/**
* AES加密
*
* @param content 明文
* @return 密文
*/
public static String encryptAES(String content, String password) {
byte[] encryptResult = encrypt(content, password);
// 二进制转换为十六进制
String encryptResultStr = parseByte2HexStr(encryptResult);
// BASE64位加密
encryptResultStr = encryptByBase64(encryptResultStr);
return encryptResultStr;
}
/**
* AES解密
*
* @param encryptResultStr 密文
* @return 明文
*/
public static String decryptAES(String encryptResultStr, String password) {
try {
// BASE64位解密
String decrpt = ebotongDecrypto(encryptResultStr);
// 十六进制转换为二进制
byte[] decryptFrom = parseHexStr2Byte(decrpt);
// 解密字节
byte[] decryptResult = decrypt(decryptFrom, password);
return new String(decryptResult, ENCODING);
} catch (Exception e) {
return null;
}
}
/**
* 加密字符串
*/
private static String encryptByBase64(String str) {
try {
Base64.Encoder encoder = Base64.getEncoder();
if (str != null && str.length() > 0) {
try {
byte[] encodeByte = str.getBytes(ENCODING);
return encoder.encodeToString(encodeByte);
} catch (Exception e) {
e.printStackTrace();
}
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 解密字符串
*/
private static String ebotongDecrypto(String str) {
Base64.Decoder decoder = Base64.getDecoder();
try {
byte[] bytes = str.getBytes(ENCODING);
byte[] decode = decoder.decode(bytes);
return new String(decode);
} catch (IOException e) {
return null;
}
}
/**
* 加密
*
* @param content 需要加密的内容
* @param password 加密密码
*/
private static byte[] encrypt(String content, String password) {
try {
KeyGenerator kgen = KeyGenerator.getInstance(KEY_ALGORITHM);
// 防止linux下 随机生成key。用其他方式在Windows上正常,但Linux上会有问题
SecureRandom secureRandom = SecureRandom.getInstance(SIGN_ALGORITHMS);
secureRandom.setSeed(password.getBytes());
kgen.init(128, secureRandom);
SecretKey secretKey = kgen.generateKey();
byte[] enCodeFormat = secretKey.getEncoded();
SecretKeySpec key = new SecretKeySpec(enCodeFormat, KEY_ALGORITHM);
// 创建密码器
Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);
byte[] byteContent = content.getBytes(ENCODING);
// 初始化
cipher.init(Cipher.ENCRYPT_MODE, key);
// 加密
return cipher.doFinal(byteContent);
} catch (Exception e) {
// log.error()
}
return null;
}
/**
* 解密
*
* @param content 待解密内容
* @param password 解密密钥
*/
private static byte[] decrypt(byte[] content, String password) {
try {
KeyGenerator kgen = KeyGenerator.getInstance(KEY_ALGORITHM);
// 防止linux下 随机生成key
SecureRandom secureRandom = SecureRandom.getInstance(SIGN_ALGORITHMS);
secureRandom.setSeed(password.getBytes());
kgen.init(128, secureRandom);
SecretKey secretKey = kgen.generateKey();
byte[] enCodeFormat = secretKey.getEncoded();
SecretKeySpec key = new SecretKeySpec(enCodeFormat, KEY_ALGORITHM);
Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);
// 创建密码器
cipher.init(Cipher.DECRYPT_MODE, key);
// 初始化加密
return cipher.doFinal(content);
} catch (Exception e) {
// log.error()
}
return null;
}
/**
* 将二进制转换成16进制
*/
private static String parseByte2HexStr(byte buf[]) {
StringBuilder sb = new StringBuilder();
for (byte b : buf) {
String hex = Integer.toHexString(b & 0xFF);
if (hex.length() == 1) {
hex = '0' + hex;
}
sb.append(hex.toUpperCase());
}
return sb.toString();
}
/**
* 将16进制转换为二进制
*/
private static byte[] parseHexStr2Byte(String hexStr) {
if (hexStr.length() < 1)
return null;
byte[] result = new byte[hexStr.length() / 2];
for (int i = 0; i < hexStr.length() / 2; i++) {
int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16);
result[i] = (byte) (high * 16 + low);
}
return result;
}
public static void main(String[] args) {
express();
}
/**
* 测试
*/
private static void express() {
System.out.println("加密解密试试:");
String content = "EXPRESSdsdjasdjahdjhajdha";
String password = "123hajsdhjahdjahd";
System.out.println("原内容为:" + content);
String encryContent = encryptAES(content, password);
System.out.println("加密后的内容为:" + encryContent);
String decryContent = decryptAES(encryContent, password);
System.out.println("解密后的内容为:" + decryContent);
}
}
这种方式能成功避免因为系统原因导致的SecureRandom问题(整了一个下午才发现这个地方出了问题,之前的写法是new SecureRandom(password.getBytes())),千万不能这么写。跨服务器就凉凉。同时解决了因为进制问题导致的错误。