AES加密算法的详细介绍与实现
①:https://blog.csdn.net/qq_28205153/article/details/55798628
②:https://blog.csdn.net/xy371661665/article/details/86423762
128位分组加密和解密数据demo
public class SymmetricEncoder {
/*
* 加密
*/
public static String AESEncode(String encodeRules,String content){
try {
//1.构造密钥生成器,指定为AES算法,不区分大小写
KeyGenerator keygen=KeyGenerator.getInstance("AES");
//2.根据ecnodeRules规则初始化密钥生成器
//生成一个128位的随机源,根据传入的字节数组
keygen.init(128, new SecureRandom(encodeRules.getBytes()));
//3.产生原始对称密钥
SecretKey original_key=keygen.generateKey();
//4.获得原始对称密钥的字节数组
byte [] raw=original_key.getEncoded();
//5.根据字节数组生成AES密钥
SecretKey key=new SecretKeySpec(raw, "AES");
//6.根据指定算法AES自成密码器
Cipher cipher=Cipher.getInstance("AES");
//7.初始化密码器,第一个参数为加密(Encrypt_mode)或者解密解密(Decrypt_mode)操作,第二个参数为使用的KEY
cipher.init(Cipher.ENCRYPT_MODE, key);
//8.获取加密内容的字节数组(这里要设置为utf-8)不然内容中如果有中文和英文混合中文就会解密为乱码
byte [] byte_encode=content.getBytes("utf-8");
//9.根据密码器的初始化方式--加密:将数据加密
byte [] byte_AES=cipher.doFinal(byte_encode);
//10.将加密后的数据转换为字符串
//这里用Base64Encoder中会找不到包
//解决办法:
//在项目的Build path中先移除JRE System Library,再添加库JRE System Library,重新编译后就一切正常了。
String AES_encode=new String(new BASE64Encoder().encode(byte_AES));
//11.将字符串返回
return AES_encode;
} catch (Exception e) {
e.printStackTrace();
}
//如果有错就返回null
return null;
}
/*
* 解密
*/
public static String AESDncode(String encodeRules,String content){
try {
//1.构造密钥生成器,指定为AES算法,不区分大小写
KeyGenerator keygen=KeyGenerator.getInstance("AES");
//2.根据ecnodeRules规则初始化密钥生成器
//生成一个128位的随机源,根据传入的字节数组
keygen.init(128, new SecureRandom(encodeRules.getBytes()));
//3.产生原始对称密钥
SecretKey original_key=keygen.generateKey();
//4.获得原始对称密钥的字节数组
byte [] raw=original_key.getEncoded();
//5.根据字节数组生成AES密钥
SecretKey key=new SecretKeySpec(raw, "AES");
//6.根据指定算法AES自成密码器
Cipher cipher=Cipher.getInstance("AES");
//7.初始化密码器,第一个参数为加密(Encrypt_mode)或者解密(Decrypt_mode)操作,第二个参数为使用的KEY
cipher.init(Cipher.DECRYPT_MODE, key);
//8.将加密并编码后的内容解码成字节数组
byte [] byte_content= new BASE64Decoder().decodeBuffer(content);
/*
* 解密
*/
byte [] byte_decode=cipher.doFinal(byte_content);
String AES_decode=new String(byte_decode,"utf-8");
return AES_decode;
} catch (Exception e) {
e.printStackTrace();
}
//如果有错就返回null
return null;
}
public static void main(String[] args) {
SymmetricEncoder se=new SymmetricEncoder();
Scanner scanner=new Scanner(System.in);
/*
* 加密
*/
System.out.println("使用AES对称加密,请输入加密的规则");
String encodeRules=scanner.next();
System.out.println("请输入要加密的内容:");
String content = scanner.next();
System.out.println("根据输入的规则"+encodeRules+"加密后的密文是:"+AESEncode(encodeRules, content));
/*
* 解密
*/
System.out.println("使用AES对称解密,请输入加密的规则:(须与加密相同)");
encodeRules=scanner.next();
System.out.println("请输入要解密的内容(密文):");
content = scanner.next();
System.out.println("根据输入的规则"+encodeRules+"解密后的明文是:"+AESDncode(encodeRules, content));
}
}
CBC/PKCS5Padding加密解密demo
关于对于密钥和IV的位数大小设置
AES的CBC加密模式下的128位、192位、256位加密的密钥长度区别,16位密钥=128位,24位密钥=192位,32位密钥=256位。
public class SecureService {
private static String SECRET_KEY = "*****";//32位
private static String iv = "*****";//偏移量字符串16位 当模式是CBC的时候必须设置偏移量
private static String Algorithm = "AES";
private static String AlgorithmProvider = "AES/CBC/PKCS5Padding"; //算法/模式/补码方式
//加密
public String AESEncryption(String content) throws Exception {
byte[] bytes = SECRET_KEY.getBytes("utf-8");
//String AESContent = byteToHexString(encrypt(content, bytes));//标注这一行可以和下一行互换
String AESContent = Hex.encodeHexString(encrypt(content, bytes));
return AESContent;
}
//解密
public String AESDecryption(String content) throws Exception {
byte[] bytes = SECRET_KEY.getBytes("utf-8");
String AESContent = new String(decrypt(content, bytes));
return AESContent;
}
public static String byteToHexString(byte[] src) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < src.length; i++) {
int v = src[i] & 0xff;
String hv = Integer.toHexString(v);
if (hv.length() < 2) {
sb.append("0");
}
sb.append(hv);
}
return sb.toString();
}
public static byte[] encrypt(String src, byte[] key) throws Exception {
SecretKey secretKey = new SecretKeySpec(key, Algorithm);
IvParameterSpec ivParameterSpec = getIv();
Cipher cipher = Cipher.getInstance(AlgorithmProvider);
cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivParameterSpec);
byte[] cipherBytes = cipher.doFinal(src.getBytes(Charset.forName("utf-8")));
return cipherBytes;
}
public static IvParameterSpec getIv() throws Exception {
IvParameterSpec ivParameterSpec = new IvParameterSpec(iv.getBytes("utf-8"));
return ivParameterSpec;
}
public static byte[] decrypt(String src, byte[] key) throws Exception {
SecretKey secretKey = new SecretKeySpec(key, Algorithm);
IvParameterSpec ivParameterSpec = getIv();
Cipher cipher = Cipher.getInstance(AlgorithmProvider);
cipher.init(Cipher.DECRYPT_MODE, secretKey, ivParameterSpec);
//byte[] hexBytes = hexStringToBytes(src);
//byte[] plainBytes = cipher.doFinal(hexBytes);//标注这两行和下一行互换
byte[] plainBytes = cipher.doFinal(Hex.decodeHex(src));
return plainBytes;
}
public static byte[] hexStringToBytes(String hexString) {
hexString = hexString.toUpperCase();
int length = hexString.length() / 2;
char[] hexChars = hexString.toCharArray();
byte[] b = new byte[length];
for (int i = 0; i < length; i++) {
int pos = i * 2;
b[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
}
return b;
}
private static byte charToByte(char c) {
return (byte) iv.indexOf(c);
}
}
对加密算法的使用
//解密
String dec = secureService.AESDecrypt(params);
//String类型,基本类型与此类似
JSONObject jsonObject = JSONObject.parseObject(dec);
String val = jsonObject.getString("变量名");
//实体类
Z z = JSONObject.parseObject(dec,Z.class);
//遇到过一次但不知道怎么描述
JSONObject jsonObject = JSONObject.parseObject(dec);
String val = jsonObject.getJSONObject("变量名1").getString("变量名2");
//分隔线,别的代码块,上面是解密代码块,下面是加密代码块
//实体类
String str = JSON.toJSONString(z);
//List类型
String str = JSONArray.toJSONString(list);
//加密
String enc = secureService.AESEncryption(str);