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);
}
}
ZipBase64加密和解密
最新推荐文章于 2024-05-13 13:37:34 发布