ZipBase64加密和解密

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
/**
* 对字符串进行压缩及加解密
* @author Administrator
*
*/
public class ZipBase64 {
private BASE64Encoder Encoder=new BASE64Encoder();
private BASE64Decoder Decoder=new BASE64Decoder();
private int buffersize = 8092;
/**
* 先压缩后加密
* @param str
* @return
*/
public String encode(String str){
ByteArrayOutputStream byteos = new ByteArrayOutputStream();
try {
ByteArrayInputStream byteis = new ByteArrayInputStream(str.getBytes("UTF-8"));//输入流
ZipOutputStream zos = new ZipOutputStream(byteos);
zos.setMethod(ZipOutputStream.DEFLATED);
zos.putNextEntry(new ZipEntry("lbs"));
int b=-1;
byte buffer[] = new byte[buffersize];
while((b=byteis.read(buffer))!=-1)
{
zos.write(buffer,0,b);
}
zos.closeEntry();

} catch (Exception e) {
return null;
}

//从输出流获取String
return Encoder.encodeBuffer(byteos.toByteArray());

}
/**
* 先解密后解压
* @param str
* @return
* @throws IOException
* @throws UnsupportedEncodingException
*/
public String decode(String str) throws IOException {
ByteArrayOutputStream jbyteos = new ByteArrayOutputStream();
try {
byte buffer1[] = new byte[buffersize];
ByteArrayInputStream jbyteis = new ByteArrayInputStream(Decoder.decodeBuffer(str));
ZipInputStream zis = new ZipInputStream(jbyteis);
zis.getNextEntry();
int b=-1;
while((b=zis.read(buffer1,0,buffersize))!=-1)
{
jbyteos.write(buffer1,0,b);
}

} catch (Exception e) {
return null;
}
return new String(jbyteos.toByteArray(),"UTF-8");
}
/**
* 单元测试
* @param args
*/
public static void main(String[] args){
String y="测试:123467890-=asdfghjkl;'zxcvbnm,./!@#$%^&*()_+:<>?";
ZipBase64 z6=new ZipBase64();
String j=z6.encode(y);
System.out.println("原数据:"+y);
System.out.println("处理后:"+j);
System.out.println("反处理:"+y);
}

}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值