首页 > 代码库 > Java的压缩、解压及压缩加密、解密解压 例子

Java的压缩、解压及压缩加密、解密解压 例子

           为了节约带宽、加快传送速度,http协议支持gzip的压缩,但如果我们的app与后台不是通过http协议通讯的,那么压缩、解压这个流程需要自己写。下面给出compress和decompress的代码:

   public static byte[] compress(byte[] data) throws Exception {   
       ByteArrayOutputStream baos = new ByteArrayOutputStream();   
       // 压缩  
       GZIPOutputStream gos = new GZIPOutputStream(baos);   
       gos.write(data, 0, data.length);   
       gos.finish();   
       baos.flush();  
       baos.close();   
       return <span style="font-family: Arial, Helvetica, sans-serif;">baos.toByteArray()</span><span style="font-family: Arial, Helvetica, sans-serif;">;  </span>   } 

   public static byte[] decompress(byte[] data) throws Exception {   
   	GZIPInputStream  bis = new GZIPInputStream(new ByteInputStream(data, data.length));
   	ByteArrayOutputStream bos=new ByteArrayOutputStream();
   	byte[] buf=new byte[20480];
   	int len=0;
   	while ((len=bis.read(buf))>0){
   		bos.write(buf, 0, len);
   	}
   	bis.close();
   	bos.close();
   	return <span style="font-family: Arial, Helvetica, sans-serif;">bos.toByteArray()</span><span style="font-family: Arial, Helvetica, sans-serif;">;   	</span>   }  


           尽快压缩后的数据不可视,但有心人很容易通过拦截数据包很快猜想到这是gzip压缩格式并给出解压程式,对于游戏领域、金融领域的应用,通讯过程的加密尤为重要。

     Blowfish算法免费、速度快,不宜破解(关键是key数据不要泄露),在及时加密、解密中应用广泛。下面以Blowfish算法为例简单讲下数据的压缩、加密盒解密、解压过程。

  1、定义keySpec,用来储存key数据的object:

static private SecretKeySpec keySpec;

byte[] key=KeyGenerator.getInstance("Blowfish").generateKey().getEncoded();

keySpec = new SecretKeySpec(key, "Blowfish");


  2、再定义getCipher方法,根据mode获得加密/解密的Cipher Object:

	static private Cipher getCipher (int mode) {
		try {
			Cipher cipher = Cipher.getInstance("Blowfish");
			cipher.init(mode, keySpec);
			return cipher;
		} catch (Exception ex) {
			throw new KryoException(ex);
		}
	}

3、下面是对w_str的压缩、加密和解密、解压:

   public static void main(String[] args) throws IOException, NoSuchAlgorithmException{
   
   	keySpec = new SecretKeySpec(KeyGenerator.getInstance("Blowfish").generateKey().getEncoded(), "Blowfish");
   	String w_src=http://www.mamicode.com/"这是整數數組[1, -105, 104, 101, 108, 108, 111, 119, 111, 114, 108, 100, -17, -68, -116, -28, -72, -83, -26, -106, -121, -17, -68, -116, -25, -71, -127, -23, -85, -108, -17, -68, -116, -25, -80, -95, -23, -85, -108, -17, -68, -116, -25, -82, -128, -28, -67, -109]";>

当然,对于极度重要的数据,为了安全起见,权衡加解密速度、破解难度等方面,个人建议还是用AES不对称加密。


转载请注明出处:http://blog.csdn.net/rocklee