您的位置:首页 > 编程语言 > Java开发

java对象序列化、gzip压缩解压缩、加密解密

2017-06-12 14:52 447 查看
有时在应用中需要将java对象序列化存储起来,有的需要压缩,有的需要加密

EncryptUtil.java

Java代码


package org.test.demo;

import java.io.UnsupportedEncodingException;

import java.security.InvalidKeyException;

import java.security.NoSuchAlgorithmException;

import java.security.SecureRandom;

import javax.crypto.BadPaddingException;

import javax.crypto.Cipher;

import javax.crypto.IllegalBlockSizeException;

import javax.crypto.KeyGenerator;

import javax.crypto.NoSuchPaddingException;

import javax.crypto.SecretKey;

import javax.crypto.spec.SecretKeySpec;

public class EncryptUtil {

private final static String ENCRYPTKEY="0123456789";

/**

*

* @Title: getEncryptKey

* @Description: 检验加密key

* @param encryptKey

* @return

* String

*

*/

private static String getEncryptKey(String encryptKey){

if(null==encryptKey || "".equals(encryptKey)) return ENCRYPTKEY;

return encryptKey;

}

/**

*

* @Title: encrypt

* @Description: 加密:普通java字串加密成16进制字串(String -> Byte -> HexStr)

* @param content 要加密处理的字串

* @param encryptKey 加密密钥

* @return

* String

*

*/

public static String encrypt(String content, String encryptKey){

byte[] encryptResult = encryptStrToByte(content, getEncryptKey(encryptKey));

return parseByte2HexStr(encryptResult);

}

/**

*

* @Title: decrypt

* @Description: 加密:16进制字串解密成普通java字串(HexStr -> Byte ->String)

* @param content 要解密处理的16进制字串

* @param encryptKey 解密密钥

* @return

* String

*

*/

public static String decrypt(String content, String encryptKey){

byte[] decryptFrom = parseHexStr2Byte(content);

byte[] decryptResult = decrypt(decryptFrom,getEncryptKey(encryptKey));

return new String(decryptResult);

}

/**

* 加密:字串 --> 二进制

* @param content 需要加密的内容

* @param password 加密密码

* @return

*/

private static byte[] encryptStrToByte(String content, String password) {

try {

KeyGenerator kgen = KeyGenerator.getInstance("AES");

kgen.init(128, new SecureRandom(password.getBytes()));

SecretKey secretKey = kgen.generateKey();

byte[] enCodeFormat = secretKey.getEncoded();

SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");

Cipher cipher = Cipher.getInstance("AES");// 创建密码器

byte[] byteContent = content.getBytes("utf-8");

cipher.init(Cipher.ENCRYPT_MODE, key);// 初始化

byte[] result = cipher.doFinal(byteContent);

return result; // 加密

} catch (NoSuchAlgorithmException e) {

e.printStackTrace();

} catch (NoSuchPaddingException e) {

e.printStackTrace();

} catch (InvalidKeyException e) {

e.printStackTrace();

} catch (UnsupportedEncodingException e) {

e.printStackTrace();

} catch (IllegalBlockSizeException e) {

e.printStackTrace();

} catch (BadPaddingException e) {

e.printStackTrace();

}

return null;

}

/**解密

* @param content 待解密内容

* @param password 解密密钥

* @return

*/

private static byte[] decrypt(byte[] content, String password) {

try {

KeyGenerator kgen = KeyGenerator.getInstance("AES");

kgen.init(128, new SecureRandom(password.getBytes()));

SecretKey secretKey = kgen.generateKey();

byte[] enCodeFormat = secretKey.getEncoded();

SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");

Cipher cipher = Cipher.getInstance("AES");// 创建密码器

cipher.init(Cipher.DECRYPT_MODE, key);// 初始化

byte[] result = cipher.doFinal(content);

return result; // 加密

} catch (NoSuchAlgorithmException e) {

e.printStackTrace();

} catch (NoSuchPaddingException e) {

e.printStackTrace();

} catch (InvalidKeyException e) {

e.printStackTrace();

} catch (IllegalBlockSizeException e) {

e.printStackTrace();

} catch (BadPaddingException e) {

e.printStackTrace();

}

return null;

}

/**将二进制转换成16进制

* @param buf

* @return

*/

private static String parseByte2HexStr(byte buf[]) {

StringBuffer sb = new StringBuffer();

for (int i = 0; i < buf.length; i++) {

String hex = Integer.toHexString(buf[i] & 0xFF);

if (hex.length() == 1) {

hex = '0' + hex;

}

sb.append(hex.toUpperCase());

}

return sb.toString();

}

/**

* 将16进制转换为二进制

*

* @param hexStr

* @return

*/

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;

}

}

GZipUtils.java

Java代码


package org.test.demo;

import java.io.ByteArrayInputStream;

import java.io.ByteArrayOutputStream;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.InputStream;

import java.io.OutputStream;

import java.util.zip.GZIPInputStream;

import java.util.zip.GZIPOutputStream;

/**

* GZIP工具

*

*/

public abstract class GZipUtils {

public static final int BUFFER = 1024;

public static final String EXT = ".gz";

/**

* 数据压缩

*

* @param data

* @return

* @throws IOException

* @throws Exception

*/

public static byte[] compress(byte[] data) throws IOException {

ByteArrayInputStream bais = new ByteArrayInputStream(data);

ByteArrayOutputStream baos = new ByteArrayOutputStream();

// 压缩

compress(bais, baos);

byte[] output = baos.toByteArray();

baos.flush();

baos.close();

bais.close();

return output;

}

/**

* 文件压缩

*

* @param file

* @throws Exception

*/

public static void compress(File file) throws Exception {

compress(file, true);

}

/**

* 文件压缩

*

* @param file

* @param delete

* 是否删除原始文件

* @throws Exception

*/

public static void compress(File file, boolean delete) throws Exception {

FileInputStream fis = new FileInputStream(file);

FileOutputStream fos = new FileOutputStream(file.getPath() + EXT);

compress(fis, fos);

fis.close();

fos.flush();

fos.close();

if (delete) {

file.delete();

}

}

/**

* 数据压缩

*

* @param is

* @param os

* @throws IOException

* @throws Exception

*/

public static void compress(InputStream is, OutputStream os) throws IOException

{

GZIPOutputStream gos = new GZIPOutputStream(os);

int count;

byte data[] = new byte[BUFFER];

while ((count = is.read(data, 0, BUFFER)) != -1) {

gos.write(data, 0, count);

}

gos.finish();

gos.flush();

gos.close();

}

/**

* 文件压缩

*

* @param path

* @throws Exception

*/

public static void compress(String path) throws Exception {

compress(path, true);

}

/**

* 文件压缩

*

* @param path

* @param delete

* 是否删除原始文件

* @throws Exception

*/

public static void compress(String path, boolean delete) throws Exception {

File file = new File(path);

compress(file, delete);

}

/**

* 数据解压缩

*

* @param data

* @return

* @throws IOException

* @throws Exception

*/

public static byte[] decompress(byte[] data) throws IOException {

ByteArrayInputStream bais = new ByteArrayInputStream(data);

ByteArrayOutputStream baos = new ByteArrayOutputStream();

// 解压缩

decompress(bais, baos);

data = baos.toByteArray();

baos.flush();

baos.close();

bais.close();

return data;

}

/**

* 文件解压缩

*

* @param file

* @throws Exception

*/

public static void decompress(File file) throws Exception {

decompress(file, true);

}

/**

* 文件解压缩

*

* @param file

* @param delete

* 是否删除原始文件

* @throws Exception

*/

public static void decompress(File file, boolean delete) throws Exception {

FileInputStream fis = new FileInputStream(file);

FileOutputStream fos = new FileOutputStream(file.getPath().replace(EXT,

""));

decompress(fis, fos);

fis.close();

fos.flush();

fos.close();

if (delete) {

file.delete();

}

}

/**

* 数据解压缩

*

* @param is

* @param os

* @throws IOException

* @throws Exception

*/

public static void decompress(InputStream is, OutputStream os) throws IOException

{

GZIPInputStream gis = new GZIPInputStream(is);

int count;

byte data[] = new byte[BUFFER];

while ((count = gis.read(data, 0, BUFFER)) != -1) {

os.write(data, 0, count);

}

gis.close();

}

/**

* 文件解压缩

*

* @param path

* @throws Exception

*/

public static void decompress(String path) throws Exception {

decompress(path, true);

}

/**

* 文件解压缩

*

* @param path

* @param delete

* 是否删除原始文件

* @throws Exception

*/

public static void decompress(String path, boolean delete) throws Exception {

File file = new File(path);

decompress(file, delete);

}

}

SerializeUtil.java

Java代码


package org.test.demo;

import java.io.BufferedInputStream;

import java.io.ByteArrayInputStream;

import java.io.ByteArrayOutputStream;

import java.io.IOException;

import java.io.ObjectInputStream;

import java.io.ObjectOutputStream;

import java.io.UnsupportedEncodingException;

import java.util.Map;

/**

* 于对java数据进行序列化和反序列化处理

* @author:

* @update: 2012-4-12 上午8:34:47

*/

public class SerializeUtil {

public final static String CHARSET_ISO88591="iso-8859-1";

/**

* @Title: serialize

* @Description: java对象序列化 <br>

* eg:<br>

* Map<String,String> map = new HashMap<String,String>();<br>

* map.put("test","序列化");<br>

* String serializedMapStr=SerializeUtil.serialize(map);

* @param original 要进行序列化的java对象

* @return String 序列化的后的值

* @throws IOException

*

*

*/

public static String serialize(Object original) throws IOException {

if(null==original) return null;

ByteArrayOutputStream baos = new ByteArrayOutputStream();

ObjectOutputStream oos = new ObjectOutputStream(baos);

oos.writeObject(original);

byte[] str = baos.toByteArray();

oos.close();

baos.close();

return new String(str,CHARSET_ISO88591);

}

/**

* @Title: deserialize

* @Description: 序列化的String对象的反序列化<br>

* 需要自己进行强制转换得到最终类型<br>

* eg:<br>

* Map newmap = (Map)SerializeUtil.deserialize(serializedMapStr);

* @param serializedstr 经序列化处理过的信息

* @return Object 反序列化后生成的Object。<br>

* @throws IOException

* @throws UnsupportedEncodingException

* @throws ClassNotFoundException

*

*

*/

public static Object deserialize(String serializedstr) throws UnsupportedEncodingException, IOException, ClassNotFoundException{

if(null==serializedstr)return null;

BufferedInputStream bis=new BufferedInputStream(new ByteArrayInputStream(serializedstr.getBytes(CHARSET_ISO88591)));

ObjectInputStream ois = new ObjectInputStream(bis);

Object obj = ois.readObject();

ois.close();

bis.close();

return obj;

}

public static byte[] objectToByteArray(Object original) throws IOException {

if (null == original)

return null;

ByteArrayOutputStream bout = new ByteArrayOutputStream();

try (ObjectOutputStream oout = new ObjectOutputStream(bout);) {

oout.writeObject(original);

}

return bout.toByteArray();

}

@SuppressWarnings("unchecked")

public static Map<String, Object> byteArrayToObject(byte[] bytearry) throws IOException, ClassNotFoundException {

if (bytearry.length==0) return null;

return (Map<String, Object>)new ObjectInputStream(new ByteArrayInputStream(bytearry)).readObject();

}

}

当然你序列化的类型不一定就是map,也可能是其他类型,这个要根据你的实际需要来改写SerializeUtil.java,直接返回Object类型

测试类:

Java代码


package org.util.test;

import java.util.Map;

import java.util.HashMap;

import javax.servlet.http.Cookie;

import junit.framework.TestCase;

import java.util.String;

import org.test.demo.EncryptUtil;

import org.test.demo.GZipUtils;

import org.test.demo.SerializeUtil;

public class MainTest extends TestCase{

public void testToCookie() throws Exception{

Map<String,Human> map = new HashMap<String,Human>();

map.put("test", "test");

map.put("test2", 123);

map.put("test3", new Cookie("cookie","cookievalue"));

String datatemp = new String(GZipUtils.compress(SerializeUtil.objectToByteArray(map)),SerializeUtil.CHARSET_ISO88591);

String str = EncryptUtil.encrypt(datatemp, "123");

System.out.println("加密后:"+str);

String str2 = EncryptUtil.decrypt(str, "123");

System.out.println("解密后"+SerializeUtil.byteArrayToObject(GZipUtils.decompress(str2.getBytes(SerializeUtil.CHARSET_ISO88591))));

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: