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

来源:互联网 发布:伊迪芬奇的秘密知乎 编辑:程序博客网 时间:2024/06/06 15:46

有时在应用中需要将java对象序列化存储起来,有的需要压缩,有的需要加密

 

EncryptUtil.java

Java代码  收藏代码
  1. package org.test.demo;  
  2.   
  3. import java.io.UnsupportedEncodingException;  
  4. import java.security.InvalidKeyException;  
  5. import java.security.NoSuchAlgorithmException;  
  6. import java.security.SecureRandom;  
  7. import javax.crypto.BadPaddingException;  
  8. import javax.crypto.Cipher;  
  9. import javax.crypto.IllegalBlockSizeException;  
  10. import javax.crypto.KeyGenerator;  
  11. import javax.crypto.NoSuchPaddingException;  
  12. import javax.crypto.SecretKey;  
  13. import javax.crypto.spec.SecretKeySpec;  
  14.   
  15. public class EncryptUtil {  
  16.     private final static String ENCRYPTKEY="0123456789";  
  17.     /** 
  18.      *  
  19.       * @Title: getEncryptKey 
  20.       * @Description: 检验加密key  
  21.       * @param encryptKey 
  22.       * @return 
  23.       * String 
  24.       * 
  25.      */  
  26.     private static String getEncryptKey(String encryptKey){  
  27.         if(null==encryptKey || "".equals(encryptKey)) return ENCRYPTKEY;  
  28.         return encryptKey;  
  29.     }  
  30.       
  31.     /** 
  32.      *  
  33.       * @Title: encrypt 
  34.       * @Description: 加密:普通java字串加密成16进制字串(String -> Byte -> HexStr) 
  35.       * @param content 要加密处理的字串 
  36.       * @param encryptKey 加密密钥 
  37.       * @return 
  38.       * String 
  39.       * 
  40.      */  
  41.     public static String encrypt(String content, String encryptKey){  
  42.         byte[] encryptResult = encryptStrToByte(content, getEncryptKey(encryptKey));  
  43.         return parseByte2HexStr(encryptResult);  
  44.     }  
  45.     /** 
  46.      *  
  47.       * @Title: decrypt 
  48.       * @Description: 加密:16进制字串解密成普通java字串(HexStr -> Byte ->String)  
  49.       * @param content 要解密处理的16进制字串 
  50.       * @param encryptKey 解密密钥 
  51.       * @return 
  52.       * String 
  53.       * 
  54.      */  
  55.     public static String decrypt(String content, String encryptKey){  
  56.         byte[] decryptFrom = parseHexStr2Byte(content);  
  57.         byte[] decryptResult = decrypt(decryptFrom,getEncryptKey(encryptKey));  
  58.         return new String(decryptResult);  
  59.     }  
  60.     /** 
  61.     * 加密:字串 --> 二进制 
  62.     * @param content 需要加密的内容 
  63.     * @param password 加密密码 
  64.     * @return 
  65.     */  
  66.     private static byte[] encryptStrToByte(String content, String password) {  
  67.         try {  
  68.             KeyGenerator kgen = KeyGenerator.getInstance("AES");  
  69.             kgen.init(128new SecureRandom(password.getBytes()));  
  70.             SecretKey secretKey = kgen.generateKey();  
  71.             byte[] enCodeFormat = secretKey.getEncoded();  
  72.             SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");  
  73.             Cipher cipher = Cipher.getInstance("AES");// 创建密码器  
  74.             byte[] byteContent = content.getBytes("utf-8");  
  75.             cipher.init(Cipher.ENCRYPT_MODE, key);// 初始化  
  76.             byte[] result = cipher.doFinal(byteContent);  
  77.             return result; // 加密  
  78.         } catch (NoSuchAlgorithmException e) {  
  79.             e.printStackTrace();  
  80.         } catch (NoSuchPaddingException e) {  
  81.             e.printStackTrace();  
  82.         } catch (InvalidKeyException e) {  
  83.             e.printStackTrace();  
  84.         } catch (UnsupportedEncodingException e) {  
  85.             e.printStackTrace();  
  86.         } catch (IllegalBlockSizeException e) {  
  87.             e.printStackTrace();  
  88.         } catch (BadPaddingException e) {  
  89.             e.printStackTrace();  
  90.         }  
  91.         return null;  
  92.     }  
  93.       
  94.     /**解密 
  95.     * @param content 待解密内容 
  96.     * @param password 解密密钥 
  97.     * @return 
  98.     */  
  99.     private static byte[] decrypt(byte[] content, String password) {  
  100.         try {  
  101.             KeyGenerator kgen = KeyGenerator.getInstance("AES");  
  102.             kgen.init(128new SecureRandom(password.getBytes()));  
  103.             SecretKey secretKey = kgen.generateKey();  
  104.             byte[] enCodeFormat = secretKey.getEncoded();  
  105.             SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");  
  106.             Cipher cipher = Cipher.getInstance("AES");// 创建密码器  
  107.             cipher.init(Cipher.DECRYPT_MODE, key);// 初始化  
  108.             byte[] result = cipher.doFinal(content);  
  109.             return result; // 加密  
  110.         } catch (NoSuchAlgorithmException e) {  
  111.             e.printStackTrace();  
  112.         } catch (NoSuchPaddingException e) {  
  113.             e.printStackTrace();  
  114.         } catch (InvalidKeyException e) {  
  115.             e.printStackTrace();  
  116.         } catch (IllegalBlockSizeException e) {  
  117.             e.printStackTrace();  
  118.         } catch (BadPaddingException e) {  
  119.             e.printStackTrace();  
  120.         }  
  121.         return null;  
  122.     }  
  123.       
  124.     /**将二进制转换成16进制 
  125.     * @param buf 
  126.     * @return 
  127.     */  
  128.     private static String parseByte2HexStr(byte buf[]) {  
  129.         StringBuffer sb = new StringBuffer();  
  130.         for (int i = 0; i < buf.length; i++) {  
  131.             String hex = Integer.toHexString(buf[i] & 0xFF);  
  132.             if (hex.length() == 1) {  
  133.                 hex = '0' + hex;  
  134.             }  
  135.             sb.append(hex.toUpperCase());  
  136.         }  
  137.         return sb.toString();  
  138.     }  
  139.   
  140.     /** 
  141.      * 将16进制转换为二进制 
  142.      *  
  143.      * @param hexStr 
  144.      * @return 
  145.      */  
  146.     private static byte[] parseHexStr2Byte(String hexStr) {  
  147.         if (hexStr.length() < 1)  
  148.             return null;  
  149.         byte[] result = new byte[hexStr.length() / 2];  
  150.         for (int i = 0; i < hexStr.length() / 2; i++) {  
  151.             int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);  
  152.             int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2),  
  153.                     16);  
  154.             result[i] = (byte) (high * 16 + low);  
  155.         }  
  156.         return result;  
  157.     }  
  158.       
  159. }  

 

GZipUtils.java

Java代码  收藏代码
  1.       
  2. package org.test.demo;  
  3.   
  4. import java.io.ByteArrayInputStream;    
  5. import java.io.ByteArrayOutputStream;    
  6. import java.io.File;    
  7. import java.io.FileInputStream;    
  8. import java.io.FileOutputStream;    
  9. import java.io.IOException;  
  10. import java.io.InputStream;    
  11. import java.io.OutputStream;    
  12. import java.util.zip.GZIPInputStream;    
  13. import java.util.zip.GZIPOutputStream;    
  14.     
  15. /**  
  16.  * GZIP工具  
  17.  *   
  18.  */    
  19. public abstract class GZipUtils {    
  20.     
  21.     public static final int BUFFER = 1024;    
  22.     public static final String EXT = ".gz";    
  23.     
  24.     /**  
  25.      * 数据压缩  
  26.      *   
  27.      * @param data  
  28.      * @return  
  29.      * @throws IOException  
  30.      * @throws Exception  
  31.      */    
  32.     public static byte[] compress(byte[] data) throws IOException {    
  33.         ByteArrayInputStream bais = new ByteArrayInputStream(data);    
  34.         ByteArrayOutputStream baos = new ByteArrayOutputStream();    
  35.     
  36.         // 压缩    
  37.         compress(bais, baos);    
  38.     
  39.         byte[] output = baos.toByteArray();    
  40.     
  41.         baos.flush();    
  42.         baos.close();    
  43.     
  44.         bais.close();    
  45.     
  46.         return output;    
  47.     }    
  48.     
  49.     /**  
  50.      * 文件压缩  
  51.      *   
  52.      * @param file  
  53.      * @throws Exception  
  54.      */    
  55.     public static void compress(File file) throws Exception {    
  56.         compress(file, true);    
  57.     }    
  58.     
  59.     /**  
  60.      * 文件压缩  
  61.      *   
  62.      * @param file  
  63.      * @param delete  
  64.      *            是否删除原始文件  
  65.      * @throws Exception  
  66.      */    
  67.     public static void compress(File file, boolean delete) throws Exception {    
  68.         FileInputStream fis = new FileInputStream(file);    
  69.         FileOutputStream fos = new FileOutputStream(file.getPath() + EXT);    
  70.     
  71.         compress(fis, fos);    
  72.     
  73.         fis.close();    
  74.         fos.flush();    
  75.         fos.close();    
  76.     
  77.         if (delete) {    
  78.             file.delete();    
  79.         }    
  80.     }    
  81.     
  82.     /**  
  83.      * 数据压缩  
  84.      *   
  85.      * @param is  
  86.      * @param os  
  87.      * @throws IOException  
  88.      * @throws Exception  
  89.      */    
  90.     public static void compress(InputStream is, OutputStream os) throws IOException    
  91.              {    
  92.     
  93.         GZIPOutputStream gos = new GZIPOutputStream(os);    
  94.     
  95.         int count;    
  96.         byte data[] = new byte[BUFFER];    
  97.         while ((count = is.read(data, 0, BUFFER)) != -1) {    
  98.             gos.write(data, 0, count);    
  99.         }    
  100.     
  101.         gos.finish();    
  102.     
  103.         gos.flush();    
  104.         gos.close();    
  105.     }    
  106.     
  107.     /**  
  108.      * 文件压缩  
  109.      *   
  110.      * @param path  
  111.      * @throws Exception  
  112.      */    
  113.     public static void compress(String path) throws Exception {    
  114.         compress(path, true);    
  115.     }    
  116.     
  117.     /**  
  118.      * 文件压缩  
  119.      *   
  120.      * @param path  
  121.      * @param delete  
  122.      *            是否删除原始文件  
  123.      * @throws Exception  
  124.      */    
  125.     public static void compress(String path, boolean delete) throws Exception {    
  126.         File file = new File(path);    
  127.         compress(file, delete);    
  128.     }    
  129.     
  130.     /**  
  131.      * 数据解压缩  
  132.      *   
  133.      * @param data  
  134.      * @return  
  135.      * @throws IOException  
  136.      * @throws Exception  
  137.      */    
  138.     public static byte[] decompress(byte[] data) throws IOException {    
  139.         ByteArrayInputStream bais = new ByteArrayInputStream(data);    
  140.         ByteArrayOutputStream baos = new ByteArrayOutputStream();    
  141.     
  142.         // 解压缩    
  143.     
  144.         decompress(bais, baos);    
  145.     
  146.         data = baos.toByteArray();    
  147.     
  148.         baos.flush();    
  149.         baos.close();    
  150.     
  151.         bais.close();    
  152.     
  153.         return data;    
  154.     }    
  155.     
  156.     /**  
  157.      * 文件解压缩  
  158.      *   
  159.      * @param file  
  160.      * @throws Exception  
  161.      */    
  162.     public static void decompress(File file) throws Exception {    
  163.         decompress(file, true);    
  164.     }    
  165.     
  166.     /**  
  167.      * 文件解压缩  
  168.      *   
  169.      * @param file  
  170.      * @param delete  
  171.      *            是否删除原始文件  
  172.      * @throws Exception  
  173.      */    
  174.     public static void decompress(File file, boolean delete) throws Exception {    
  175.         FileInputStream fis = new FileInputStream(file);    
  176.         FileOutputStream fos = new FileOutputStream(file.getPath().replace(EXT,    
  177.                 ""));    
  178.         decompress(fis, fos);    
  179.         fis.close();    
  180.         fos.flush();    
  181.         fos.close();    
  182.     
  183.         if (delete) {    
  184.             file.delete();    
  185.         }    
  186.     }    
  187.     
  188.     /**  
  189.      * 数据解压缩  
  190.      *   
  191.      * @param is  
  192.      * @param os  
  193.      * @throws IOException  
  194.      * @throws Exception  
  195.      */    
  196.     public static void decompress(InputStream is, OutputStream os) throws IOException    
  197.              {    
  198.     
  199.         GZIPInputStream gis = new GZIPInputStream(is);    
  200.     
  201.         int count;    
  202.         byte data[] = new byte[BUFFER];    
  203.         while ((count = gis.read(data, 0, BUFFER)) != -1) {    
  204.             os.write(data, 0, count);    
  205.         }    
  206.     
  207.         gis.close();    
  208.     }    
  209.     
  210.     /**  
  211.      * 文件解压缩  
  212.      *   
  213.      * @param path  
  214.      * @throws Exception  
  215.      */    
  216.     public static void decompress(String path) throws Exception {    
  217.         decompress(path, true);    
  218.     }    
  219.     
  220.     /**  
  221.      * 文件解压缩  
  222.      *   
  223.      * @param path  
  224.      * @param delete  
  225.      *            是否删除原始文件  
  226.      * @throws Exception  
  227.      */    
  228.     public static void decompress(String path, boolean delete) throws Exception {    
  229.         File file = new File(path);    
  230.         decompress(file, delete);    
  231.     }    
  232.     
  233. }    

 

SerializeUtil.java

Java代码  收藏代码
  1.       
  2. package org.test.demo;  
  3.   
  4. import java.io.BufferedInputStream;  
  5. import java.io.ByteArrayInputStream;  
  6. import java.io.ByteArrayOutputStream;  
  7. import java.io.IOException;  
  8. import java.io.ObjectInputStream;  
  9. import java.io.ObjectOutputStream;  
  10. import java.io.UnsupportedEncodingException;  
  11. import java.util.Map;  
  12.   
  13. /** 
  14.  * 于对java数据进行序列化和反序列化处理 
  15.  * @author:  
  16.  * @update: 2012-4-12 上午8:34:47 
  17.  */  
  18.   
  19. public class SerializeUtil {  
  20.       
  21.     public final static String CHARSET_ISO88591="iso-8859-1";  
  22.     /** 
  23.       * @Title: serialize 
  24.       * @Description: java对象序列化 <br> 
  25.       * eg:<br> 
  26.       *   Map<String,String> map = new HashMap<String,String>();<br> 
  27.       *   map.put("test","序列化");<br> 
  28.       *   String serializedMapStr=SerializeUtil.serialize(map); 
  29.       * @param original 要进行序列化的java对象 
  30.       * @return String 序列化的后的值 
  31.       * @throws IOException 
  32.       *  
  33.       *  
  34.       */  
  35.     public static String serialize(Object original) throws IOException {  
  36.         if(null==original) return null;  
  37.         ByteArrayOutputStream baos = new ByteArrayOutputStream();    
  38.         ObjectOutputStream oos = new ObjectOutputStream(baos);    
  39.         oos.writeObject(original);    
  40.         byte[] str = baos.toByteArray();  
  41.         oos.close();  
  42.         baos.close();  
  43.         return new String(str,CHARSET_ISO88591);  
  44.     }  
  45.       
  46.     /** 
  47.       * @Title: deserialize 
  48.       * @Description: 序列化的String对象的反序列化<br> 
  49.       * 需要自己进行强制转换得到最终类型<br>  
  50.       * eg:<br> 
  51.       *   Map newmap = (Map)SerializeUtil.deserialize(serializedMapStr);  
  52.       * @param serializedstr 经序列化处理过的信息 
  53.       * @return Object 反序列化后生成的Object。<br> 
  54.       * @throws IOException 
  55.       * @throws UnsupportedEncodingException 
  56.       * @throws ClassNotFoundException 
  57.       *  
  58.       *  
  59.       */  
  60.     public static Object deserialize(String serializedstr) throws UnsupportedEncodingException, IOException, ClassNotFoundException{  
  61.         if(null==serializedstr)return null;  
  62.         BufferedInputStream bis=new BufferedInputStream(new ByteArrayInputStream(serializedstr.getBytes(CHARSET_ISO88591)));  
  63.         ObjectInputStream ois = new ObjectInputStream(bis);  
  64.         Object obj = ois.readObject();  
  65.         ois.close();  
  66.         bis.close();  
  67.         return obj;  
  68.     }  
  69.       
  70.     public static byte[] objectToByteArray(Object original) throws IOException {  
  71.         if (null == original)  
  72.             return null;  
  73.         ByteArrayOutputStream bout = new ByteArrayOutputStream();  
  74.         try (ObjectOutputStream oout = new ObjectOutputStream(bout);) {  
  75.             oout.writeObject(original);  
  76.         }  
  77.         return bout.toByteArray();  
  78.     }  
  79.       
  80.       
  81.     @SuppressWarnings("unchecked")  
  82.     public static Map<String, Object> byteArrayToObject(byte[] bytearry) throws IOException, ClassNotFoundException {  
  83.         if (bytearry.length==0return null;  
  84.         return (Map<String, Object>)new ObjectInputStream(new ByteArrayInputStream(bytearry)).readObject();  
  85.     }  
  86. }  

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

 

测试类:

Java代码  收藏代码
  1. package org.util.test;  
  2.   
  3. import java.util.Map;  
  4. import java.util.HashMap;  
  5. import javax.servlet.http.Cookie;  
  6. import junit.framework.TestCase;  
  7. import java.util.String;  
  8.   
  9. import org.test.demo.EncryptUtil;  
  10. import org.test.demo.GZipUtils;  
  11. import org.test.demo.SerializeUtil;  
  12.   
  13. public class MainTest extends TestCase{  
  14.     public void testToCookie() throws Exception{  
  15.             Map<String,Human> map = new HashMap<String,Human>();  
  16.               
  17.             map.put("test""test");  
  18.             map.put("test2"123);  
  19.             map.put("test3"new Cookie("cookie","cookievalue"));  
  20.   
  21.             String datatemp = new String(GZipUtils.compress(SerializeUtil.objectToByteArray(map)),SerializeUtil.CHARSET_ISO88591);  
  22.             String str = EncryptUtil.encrypt(datatemp, "123");  
  23.             System.out.println("加密后:"+str);  
  24.             String str2 = EncryptUtil.decrypt(str, "123");  
  25.             System.out.println("解密后"+SerializeUtil.byteArrayToObject(GZipUtils.decompress(str2.getBytes(SerializeUtil.CHARSET_ISO88591))));  
  26.           
  27.   
  28.     }  
  29.   
  30. }  
原创粉丝点击