项目需求如下:需要将POJO转成json字串并且需要加密进行数据传输,服务是部署在linux下的集群环境
POJO转json字串
- 准备POJO对象
@Entity
@Table(name = "Demo_click")
public class DemoParam implements Serializable {
private Integer id;
private Integer sourceId;
private Integer cpaId;
private Long insertTime;
private String fromIp;
private String otherParamValue;
private String clientIp;
private String callback;
private Integer productId;
private String idfa;
省略 get/set
- Json字符串与POJO相互转换
package com.gc.wall.utils;
import org.codehaus.jackson.map.ObjectMapper;
public class JackSon {
public static ObjectMapper objectMapper;
/**
* Json字符串转对象
* 使用泛型方法,把json字符串转换为相应的JavaBean对象。
* (1)转换为普通JavaBean:readValue(json,Student.class)
* (2)转换为List,如List<Student>,将第二个参数传递为Student
* [].class.然后使用Arrays.asList();方法把得到的数组转换为特定类型的List
* @param jsonStr
* @param valueType
* @return
*/
public static <T> T jsonStrToBean(String jsonStr, Class<T> valueType) {
if (objectMapper == null) {
objectMapper = new ObjectMapper();
}
try {
return objectMapper.readValue(jsonStr, valueType);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
// 对象转Json字符串
* @Object bean
* @return
* @throws Exception
*/
public String beanToJsonStr(Object bean){
if (objectMapper == null) {
objectMapper = new ObjectMapper();
}
try {
return objectMapper.writeValueAsString(bean);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
- JsonUtil公共类
package com.gc.wall.utils;
import com.gc.wall.DemoParam ;
public class JsonUtil{
static JackSon jackSon;
static CasClickParam casClick;
static String jsonStr;
static {
jackSon = new JackSon();
}
public static String testBeanToJsonStr(DemoParam demo) {
jsonStr = jackSon.beanToJsonStr(demo);
return jsonStr;
}
public static DemoParam testJsonStrToBean(String jsonStr) {
casClick = jackSon.jsonStrToBean(jsonStr, DemoParam.class);
return casClick;
}
}
json字串AES加密
- 准备加密公共类AesUtil
package com.gc.wall.utils;
import com.gc.wall.exception.BadJoyClickException;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.Hex;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
public class AesUtil {
public static void main(String[] args) throws Exception {
// aes + base --> aes + base
String content = {"mac":"","idfa":"123","clientIp":"456",insertTime":null}";
System.out.println("加密内容:" + content);
String key = "qwertyuiopasdfghjklzxcvbnm2134567890";
System.out.println("加密密钥和解密密钥:" + key);
String encrypt = aesEncrypt(content, key);
System.out.println("加密后:" +encrypt);
String decrypt = aesDecrypt(encrypt, key);
System.out.println("解密后:" + decrypt);
}
//**
* 编码
* @param bstr
* @return String
*/
public static String Base64encode(byte[] bstr) {
return Base64.encodeBase64String(bstr);
}
//**
* 解码
* @param str
* @return string
*/
public static byte[] Base64decode(String str) {
return Base64.decodeBase64(str);
}
//*
* AES加密
* @param content 待加密的内容
* @param encryptKey 加密密钥
* @return 加密后的byte[]
* @throws Exception
*/
public static byte[] aesEncryptToBytes(String content, String encryptKey) throws Exception {
KeyGenerator kgen = KeyGenerator.getInstance("AES");
/*防止linux下 随机生成key*/
SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
random.setSeed(encryptKey.getBytes());
kgen.init(128, random);
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(kgen.generateKey().getEncoded(), "AES"));
return cipher.doFinal(content.getBytes("UTF-8"));
}
//**
* AES加密为base 64 code
* @param content 待加密的内容
* @param encryptKey 加密密钥
* @return 加密后的base 64 code
* @throws Exception
*/
public static String aesEncrypt(String content, String encryptKey) throws Exception {
return Base64encode(aesEncryptToBytes(content, encryptKey));
}
//**
* AES解密
* @param encryptBytes 待解密的byte[]
* @param decryptKey 解密密钥
* @return 解密后的String
* @throws Exception
*/
public static String aesDecryptByBytes(byte[] encryptBytes, String decryptKey) {
byte[] decryptBytes = new byte[0];
try {
KeyGenerator kgen = KeyGenerator.getInstance("AES");
/*防止linux下 随机生成key*/
SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
random.setSeed(decryptKey.getBytes());
kgen.init(128, random);
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(kgen.generateKey().getEncoded(), "AES"));
decryptBytes = cipher.doFinal(encryptBytes);
return new String(decryptBytes,"UTF-8");
} catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException | UnsupportedEncodingException e) {
throw new BadJoyClickException(e.getMessage(),e);
}
}
//**
* 将base 64 code AES解密
* @param encryptStr 待解密的base 64 code
* @param decryptKey 解密密钥
* @return 解密后的string
* @throws Exception
*/
public static String aesDecrypt(String encryptStr, String decryptKey){
return aesDecryptByBytes(Base64decode(encryptStr), decryptKey);
}
- 上文中的 BadJoyClickException自定义异常类
package com.gc.wall.exception;
public class BadJoyClickException extends RuntimeException{
public BadJoyClickException(String message){
super(message);
}
public BadJoyClickException(String message, Throwable cause) {
super(message, cause);
}
}
POJO转json字串后加密
package com.gc.wall.utils;
public class CallAdvUtils {
public static String setDemoParam(DemoParam demo){
try{
String content=JsonUtil.testBeanToJsonStr(demo);
Properties props = PropertiesLoaderUtils.loadAllProperties("cas.properties");
String key = props.getProperty("aesKey").trim() ;
String encrypt = AesUtil.aesEncrypt(content, key);
return encrypt;
}catch (Exception e){
e.printStackTrace();
return null;
}
}
}
可以将密钥key放入properties文件中
解密后还原成POJO
public DemoParam getDemoParam(String str) throws Exception {
DemoParam demo= null;
try{
Properties props = PropertiesLoaderUtils.loadAllProperties("cas.properties");
String key = props.getProperty("aesKey").trim() ;
/*通过浏览器传输可能加密串里面会有空格,这里需要将空格替换*/
str=str.replace(" ", "+");
String jsonStr= AesUtil.aesDecrypt(str0, key);
casClick=JsonUtil.testJsonStrToBean(jsonStr);
}catch (BadJoyClickException e) {
logger.error("解密失败");
}
}