You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

145 lines
5.8 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

package com.dsideal.newUniversityExamination.selectcourse.bean;
import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
/**
* @program: dsideal_yy
* @description: 对文本进行加密
* @author: Mr.zms
* @create: 2019-09-02 15:26
**/
public class SecurityAES {
/** AES加密时的秘钥 */
private final static String AES_KEY = "this_is_my_key";
/** AES专用秘钥 */
private static SecretKeySpec key = null;
/* key因为在没改变AES_KEY时是不变的所以进行一次初始化操作 */
static {
// 创建AES的秘钥生成器
KeyGenerator kgen = null;
try {
kgen = KeyGenerator.getInstance("AES");
// 利用AES_KEY的随机数初始化刚刚创建的秘钥生成器
kgen.init(128, new SecureRandom(AES_KEY.getBytes()));
// 生成一个秘钥
SecretKey secretKey = kgen.generateKey();
// 获取二进制的秘钥
byte[] enCodeFormat = secretKey.getEncoded();
// 根据二进制秘钥获取AES专用秘钥
key = new SecretKeySpec(enCodeFormat, "AES");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
}
/**
* 加密文本
* @author LiQuanhui
* @date 2017年11月27日 下午3:30:51
* @param content 明文
* @return 加密后16进制的字符串
*/
public static String encrypt(String content) {
try {
// 创建AES密码器
Cipher cipher = Cipher.getInstance("AES");
// 将文本进行utf-8的编码
byte[] byteContent = content.getBytes(StandardCharsets.UTF_8);
// 初始化AES密码器为加密器
cipher.init(Cipher.ENCRYPT_MODE, key);
// 进行AES加密
byte[] result = cipher.doFinal(byteContent);
// 将byte数组转为十六进制的字符串
// 因为result存储的是字节直接new string(result)会按照ASCII表输出这会导致乱码在传给解码器解码的时候重新转为字节的时候就会对不上了
// 因为我要进行前后端的传输所以这样传给前端前端不能识别于是对byte进行转码成16进制的字符串
return parseByte2HexStr(result);
} catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException e) {
e.printStackTrace();
}
return null;
}
/**
* 解码文本
* @author LiQuanhui
* @date 2017年11月27日 下午5:23:38
* @param encryptContent 密文16进制
* @return 明文
*/
public static String decrypt(String encryptContent) {
try {
// 将十六进制的加密文本转换为byte数组
byte[] content = parseHexStr2Byte(encryptContent);
// 创建AES密码器
Cipher cipher = Cipher.getInstance("AES");
// 初始化AES密码器为解密器 // 初始化
cipher.init(Cipher.DECRYPT_MODE, key);
// 进行AES解密
assert content != null;
byte[] result = cipher.doFinal(content);
// 将二进制转为字符串
return new String(result);
} catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException e) {
e.printStackTrace();
}
return null;
}
/**
* 将byte数组转换成16进制的字符串
* @return 16进制的字符串
*/
private static String parseByte2HexStr(byte[] buf) {
StringBuilder sb = new StringBuilder();
for (byte b : buf) {
//将每个字节都转成16进制的
String hex = Integer.toHexString(b & 0xFF);
if (hex.length() == 1) {
//为保证格式统一用两位16进制的表示一个字节
hex = '0' + hex;
}
sb.append(hex.toUpperCase());
}
return sb.toString();
}
/**
* 将16进制的字符串转换为byte数组
* @return byte数组
*/
private static byte[] parseHexStr2Byte(String hexStr) {
if (hexStr.length() < 1)
{
return null;
}
//两个16进制表示一个字节所以字节数组大小为hexStr.length() / 2
byte[] result = new byte[hexStr.length() / 2];
for (int i = 0; i < hexStr.length() / 2; i++) {
//每次获取16进制字符串中的两个转成10进制0-255
int num = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 2), 16);
//将10进制强转为byte
result[i] = (byte) num;
}
return result;
}
// 测试
public static void main(String[] args) throws Exception {
String content = "{\"chemistry\":1,\"politics\":0,\"biology\":1,\"identity_id\":6,\"level\":1,\"geography\":0,\"physics\":1,\"apply_id\":2021,\"history\":0,\"plan_id\":7,\"person_id\":86424663}\n" +
"{\"chemistry\":0,\"politics\":0,\"biology\":1,\"identity_id\":6,\"level\":2,\"geography\":0,\"physics\":1,\"apply_id\":2022,\"history\":1,\"plan_id\":7,\"person_id\":86424663}\n";
// 加密
System.out.println("加密前:" + content);
String encryptResult = encrypt(content);
System.out.println("加密后:" + encryptResult);
// 解密
String decryptResult = decrypt(encryptResult);
System.out.println("解密后:" + decryptResult);
}
}