java文件加密压缩及解密-流程图及源码_第1页
java文件加密压缩及解密-流程图及源码_第2页
java文件加密压缩及解密-流程图及源码_第3页
java文件加密压缩及解密-流程图及源码_第4页
java文件加密压缩及解密-流程图及源码_第5页
已阅读5页,还剩19页未读, 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

1、文件加密压缩以及解密两种方式:1. 文件内容加密:首先对文件内容进行加密,然后压缩;对应的先解压,再对文件进行密匙匹配,匹配成功对文件解密2. ZIP4J:引入jar包,给文件添加密匙进行压缩,必须输入密码才可以打开文件。通过密码将文件进行解压缩。1.1文件内容加密流程图流程图对应的具体方法序号对应方法名相关参数01Main函数调用入口public void compressExe(String srcPathName,String destPathName,String key)srcPathName:源文件路径destPathName:目标文件路径key:密匙02判断压缩目标是“目录(文件

2、夹)”、“文件”private void compressByType(String srcPathName,ZipOutputStream out,String basedir,String key)srcPathName:要被操作的文件路径out:压缩文件流key:密匙03文件加密 private void compressFile(String srcPathName, ZipOutputStream out, String basedir,String key)代码前面部分srcPathName:要被操作的文件路径out:压缩文件流key:密匙04添加密匙public static v

3、oid appendLock(String fileName,String key)fileName:文件路径key:密匙05压缩文件private void compressFile(String srcPathName, ZipOutputStream out, String basedir,String key)代码在后面部分srcPathName:要被操作的文件路径out:压缩文件流key:密匙1.2文件加密方法:1.3文件压缩1.4文件解压整体流程图:序号对应方法名相关参数01Main函数调用入口,首先解压文件public static void unZipFiles(String

4、zipFile,String descDir,String key)zipFile:源zip路径descDir:文件输出路径key:密匙02匹配密匙public static boolean matchLock(String fileName,String key)fileName:文件路径key:密匙03文件解密 public static String decrypt(String srcPathName, String key)srcPathName:要被操作的文件路径key:密匙具体解压流程图如下:1.5文件解密decrypt(decryptFilePath,key);附源代码:imp

5、ort com.zl.base.core.MethodFactory;import com.zl.base.core.db.Executer;import com.zl.base.exception.DbException;import mon.CoreDispatchAction;import mon.MD5;import mons.beanutils.BasicDynaBean;import mons.beanutils.DynaProperty;import org.apache.log4j.Logger;import org.apache.struts.action.ActionFor

6、m;import org.apache.struts.action.ActionForward;import org.apache.struts.action.ActionMapping;import java.io.BufferedInputStream;import java.io.BufferedOutputStream;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.

7、IOException;import java.io.InputStream;import java.io.OutputStream;import java.io.RandomAccessFile;import java.util.List;import java.util.zip.CRC32;import java.util.zip.CheckedOutputStream;import java.util.zip.ZipEntry;import java.util.zip.ZipOutputStream;import java.util.zip.ZipInputStream;/*import

8、 com.zl.opt.schedule.zip4j.*;import com.zl.opt.schedule.zip4j.model.*;import com.zl.opt.schedule.zip4j.util.Zip4jConstants;/import com.zl.opt.schedule.zip4j.core.ZipFile;import com.zl.opt.schedule.zip4j.exception.ZipException;*/import javax.servlet.http.HttpServletRequest;import javax.servlet.http.H

9、ttpServletResponse;public class zipCompressor extends CoreDispatchAction static Logger logger = Logger.getLogger(zipCompressor.class.getName();static final int BUFFER = 8192;public zipCompressor()public ActionForward createfile(ActionMapping mapping, ActionForm form,HttpServletRequest request, HttpS

10、ervletResponse response)String filepath="e:"/"usrlocalhnpierce"String sql="select id,title,systemcode,file_passwd,sqlrule,isappoint,separator,int(current date) as datecol from S_DATAOFFERRULE where starttime <= current date and endtime >= current date"try List lis

11、t1 = Executer.getInstance().ExecSeletSQL(sql).getResultSet();if(list1.size()>0)BasicDynaBean rowBean = null;String info="",separator=""for(int i=0;i<list1.size();i+)rowBean = (BasicDynaBean) list1.get(i);separator=rowBean.get("separator")+""List list2=nu

12、ll;if("-1".equals(rowBean.get("isappoint")+"") list2 = Executer.getInstance().ExecSeletSQL(MethodFactory.replace(rowBean.get("sqlrule")+"", "''", "'")+"").getResultSet();elseif(MethodFactory.replace(rowBean.g

13、et("sqlrule")+"", "''", "'").split("group by").length=2) list2 = Executer.getInstance().ExecSeletSQL(MethodFactory.replace(rowBean.get("sqlrule")+"", "''", "'").split("group by"

14、;)0+" and cust_code in (select custcode from S_SPECIALRETAILER where systemcode = '"+rowBean.get("systemcode")+"' and usecode = '"+rowBean.get("isappoint")+"') group by "+MethodFactory.replace(rowBean.get("sqlrule")+"&q

15、uot;, "''", "'").split("group by")1).getResultSet();else list2 = Executer.getInstance().ExecSeletSQL(MethodFactory.replace(rowBean.get("sqlrule")+"", "''", "'")+" and cust_code in (select custcode from

16、 S_SPECIALRETAILER where systemcode = '"+rowBean.get("systemcode")+"' and usecode = '"+rowBean.get("isappoint")+"') ").getResultSet();if(list2.size()>0)File filesave = new File(filepath+rowBean.get("systemcode")+"/"+

17、rowBean.get("title")+""+rowBean.get("datecol")+"000"+i+".txt");for(int j=0;j<list2.size();j+)BasicDynaBean rowBeandata = (BasicDynaBean) list2.get(j); DynaProperty str=rowBeandata.getDynaClass().getDynaProperties();/str7.getName()for(int k=0;k<

18、str.length;k+)if(k=str.length-1)info+=rowBeandata.get(strk.getName()+"n"elseinfo+=rowBeandata.get(strk.getName()+separator;/info=rowBeandata.get("v_province")+separator+rowBeandata.get("org_code")+separator/+rowBeandata.get("sale_reg_code")+separator+rowBeanda

19、ta.get("yearmonth")+separator/+rowBeandata.get("yearweek")+separator+rowBeandata.get("cust_code")+separator/+rowBeandata.get("brand_code")+separator+rowBeandata.get("demand")+separator/+rowBeandata.get("order")+separator+rowBeandata.get(&qu

20、ot;money")+"n"OutputStream bos = null;try bos = new FileOutputStream(filesave);bos.write(info.getBytes();bos.close(); catch (Exception e) / TODO Auto-generated catch blocke.printStackTrace();compressExe(filepath+rowBean.get("systemcode")+""+rowBean.get("title&

21、quot;)+""+rowBean.get("datecol")+"000"+i+".txt",filepath+rowBean.get("title")+""+rowBean.get("datecol")+"000"+i+".zip",rowBean.get("file_passwd")+"");Executer.getInstance().ExecUpdateSQL(&qu

22、ot;insert into S_filenameOperate(systemcode,usecode,usename,filename,address,status,recordcount)"+ "values('"+rowBean.get("systemcode")+"','"+rowBean.get("id")+"','"+rowBean.get("title")+"','"+rowB

23、ean.get("title")+""+rowBean.get("datecol")+"000"+i+".zip"+"','"+rowBean.get("systemcode")+"','1',"+list2.size()+")"); catch (DbException e) / TODO Auto-generated catch blocke.printStackTrace

24、();return null;/*执行压缩操作 * * param srcPathName 要被压缩的文件 * param destPathName 压缩包 * param key 密匙 */public void compressExe(String srcPathName,String destPathName,String key)File file = new File(srcPathName);File zipFile = new File(destPathName);if (!file.exists() throw new RuntimeException(srcPathName+

25、"不存在!");try FileOutputStream fileOutputStream = new FileOutputStream(zipFile);CheckedOutputStream cos = new CheckedOutputStream(fileOutputStream, new CRC32();ZipOutputStream out = new ZipOutputStream(cos); /打包String basedir = ""/compressByType(file, out, basedir);/根据(文件夹/文件)来执行不同

26、压缩方法compressByType(srcPathName, out, basedir,key);/根据(文件夹/文件)来执行不同压缩方法out.close(); catch (Exception e) / TODO: handle exceptione.printStackTrace();logger.error("执行压缩操作时发生异常"+e);throw new RuntimeException(e);/* * 判断压缩目标是“目录(文件夹)”、“文件” * param file * param out * param basedir */private void

27、compressByType(String srcPathName,ZipOutputStream out,String basedir,String key)File file = new File(srcPathName);if(file.isDirectory()/目录("压缩"+basedir+file.getName();pressDirectory(file, out, basedir,key);("压缩"+basedir+file.getName();pressFile(srcPathNa

28、me, out, basedir,key);/* * 压缩目录 * param dir * param out * param basedir */private void compressDirectory(File dir, ZipOutputStream out, String basedir,String key) if(!dir.exists()return;File files = dir.listFiles();for(int i = 0; i<files.length;i+)/递归compressByType(filesi.getPath(), out, basedir+

29、dir.getName()+"/",key);/* * 压缩文件 * param srcPathName 压缩文件路径 * param out * param basedir * param key 密码 */private void compressFile(String srcPathName, ZipOutputStream out, String basedir,String key) File file = new File(srcPathName);if(!file.exists()return;try/对文件进行加密String path = file.get

30、Path();int index = path.lastIndexOf("");String destFile = path.substring(0, index)+""+"abc"File dest = new File(destFile);InputStream in = new FileInputStream(srcPathName);OutputStream fileout = new FileOutputStream(destFile);/创建一个长度为1024的内存空间,1024足够大,可以一次将文件读取完,不会出现中文注

31、释乱码问题 byte buffer = new byte1024;int r;byte buffer2 = new byte1024;/使用循环来重复读取数据/ 读入多个字节到字节数组buffer中,r为一次读入的字节数 while(r = in.read(buffer)>0)for(int i = 0;i<r;i+)byte b = bufferi;/System.out.println(b);buffer2i=b=255?0:+b;/位移fileout.write(buffer2, 0, r);fileout.flush();in.close();fileout.close()

32、;file.delete();dest.renameTo(new File(srcPathName);appendLock(srcPathName, key);System.out.println("加密成功");/把文件进行压缩zipBufferedInputStream bis = new BufferedInputStream(new FileInputStream(new File(srcPathName);ZipEntry entry = new ZipEntry(basedir+new File(srcPathName).getName();/Creates a

33、 new zip entry with the specified nameout.putNextEntry(entry);int count;byte data = new byteBUFFER;while(count =bis.read(data,0,BUFFER)!=-1) /bis.read()returns the number of bytes actually read. out.write(data,0,count);/Writes an array of bytes to the current ZIP entry data.out.flush();bis.close();c

34、atch(Exception e)throw new RuntimeException(e);/* * 添加密匙 * param fileName文件路径 * param key 密匙 */public static void appendLock(String fileName,String key)try/打开一个随机访问文件流,按读写方式RandomAccessFile randomFile = new RandomAccessFile(fileName, "rw");/文件长度,字节数/long fileLength = randomFile.length();/将

35、写文件指针移到文件20的位置,写入密匙int keyLength = key.length();/*int avgLength = keyLength/3;int start = 20;int center = 40;int last = 60;randomFile.seek(start);randomFile.writeBytes(key.substring(0,avgLength);randomFile.seek(center);randomFile.writeBytes(key.substring(avgLength,2*avgLength);randomFile.seek(last);

36、randomFile.writeBytes(key.substring(2*avgLength,keyLength);*/byte b = key.getBytes();randomFile.setLength(randomFile.length() + b.length); for(long i = randomFile.length() - 1; i > b.length + 20 - 1; i-) randomFile.seek(i - b.length); byte temp = randomFile.readByte(); randomFile.seek(i); randomF

37、ile.writeByte(temp); randomFile.seek(20); randomFile.write(b);randomFile.close();catch(IOException e)e.printStackTrace();/* * 解压文件到指定目录 * param zipFile 源zip路径 * param descDir 输出路径 * author */ public static void unZipFiles(String zipFile,String descDir,String key)throws IOException long startTime=Sys

38、tem.currentTimeMillis(); try ZipInputStream Zin=new ZipInputStream(new FileInputStream(zipFile); /输入源zip路径 BufferedInputStream Bin=new BufferedInputStream(Zin); String Parent=descDir;/输出路径(文件夹目录) File Fout=null; ZipEntry entry; try while(entry = Zin.getNextEntry()!=null && !entry.isDirectory

39、() Fout=new File(Parent,entry.getName(); if(!Fout.exists() (new File(Fout.getParent().mkdirs(); FileOutputStream out=new FileOutputStream(Fout); BufferedOutputStream Bout=new BufferedOutputStream(out); int b; while(b=Bin.read()!=-1) Bout.write(b); Bout.close(); out.close(); System.out.println(Fout+&

40、quot;解压成功"); try String decryptFilePath = Fout.getPath().replace("", "/");decrypt(decryptFilePath,key); catch (Exception e) / TODO Auto-generated catch blocke.printStackTrace(); Bin.close(); Zin.close(); catch (IOException e) / TODO Auto-generated catch block e.printStackTra

41、ce(); catch (FileNotFoundException e) / TODO Auto-generated catch block e.printStackTrace(); long endTime=System.currentTimeMillis(); System.out.println("耗费时间: "+(endTime-startTime)+" ms"); /* * 解密 * param srcPathName 源文件 * param tempUrl 临时文件 * param ketLength 密码长度 * return * thr

42、ows Exception */ public static String decrypt(String srcPathName, String key) throws Exception /将解密秘钥进行md5加密 String md5pass=new MD5().encrypt(key); System.out.println(md5pass); if(matchLock(srcPathName, md5pass)/ /匹配成功开始解密 File file = new File(srcPathName); if (!file.exists() return null; int keyLen

43、gth = md5pass.length(); int index = srcPathName.lastIndexOf("/"); String destFile = srcPathName.substring(0, index)+"/"+"abc" File dest = new File(destFile); if (!dest.getParentFile().exists() dest.getParentFile().mkdirs(); InputStream is = new FileInputStream(srcPathNa

44、me); OutputStream out = new FileOutputStream(destFile); byte buffer = new byte1024; byte buffer2=new byte1024; byte buffer3=new byte1024; byte buffer4=new byte1024-keyLength; byte bMax=(byte)255; long size = file.length() ;/- keyLength;/ int avgLength = keyLength/3; int mod = (int) (size%1024); int

45、div = (int) (size>>10);/将size向右移10位 int count = mod=0?div:(div+1); int k = 1, r,j=0; while (k <= count && ( r = is.read(buffer) > 0) if(mod != 0 && k=count) r = mod; for(int i = 0;i < r;i+) byte b=bufferi; if(k=1) if(i>=20 && i<(20+keyLength) )/|(i>=40

46、 && i<(40+avgLength)|(i>=60 && i<(60+keyLength-2*avgLength) / System.out.println(b=0?bMax:-b); else buffer3j=b; j+; else buffer2i=b=0?bMax:-b; / buffer2i=b=0?bMax:-b; if(k=1) for(int i = 0;i<j;i+) byte b=buffer3i; buffer4i=b=0?bMax:-b; out.write(buffer4, 0, j); else out.w

47、rite(buffer2, 0, r); k+; out.close(); is.close(); file.delete(); dest.renameTo(new File(srcPathName); System.out.println("解密成功"); else System.out.println("密码不匹配"); return srcPathName; /* * 匹配密匙 * param fileName文件路径 * param key 密匙 */public static boolean matchLock(String fileName,

48、String key)boolean isMatch = false;try/打开一个随机访问文件流,按读写方式RandomAccessFile randomFile = new RandomAccessFile(fileName, "r");/文件长度,字节数/long fileLength = randomFile.length();/将写文件指针移到文件20的位置int keyLength = key.length();int avgLength = keyLength/3;int start = 20;int center = 40;int last = 60;randomFile.seek(start);/指针指向start位置byte bKeyStart=new bytekeyLength;f

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论