分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 技术分享

上传与下载文件加密

发布时间:2023-09-06 01:28责任编辑:董明明关键词:暂无标签

文件上传与下载时,对文件进行加密。

1、定义KEY

// 加密所需key对象private static Key key;

2、初始化KEY ( 加密和解密方法中getKey("xx")  中xx要相同 )

/** * 根据参数生成KEY */public static void getKey(String strKey) { ???try { ???????KeyGenerator generator = KeyGenerator.getInstance("DES"); ???????generator.init(new SecureRandom(strKey.getBytes())); ???????key = generator.generateKey(); ???} catch (Exception e) { ???????throw new RuntimeException("Error initializing SqlMap class. Cause: " + e); ???}}

3、加密 

/** * 对文件加密 * @param srcFile * @throws Exception */public static void encFile(File srcFile) throws Exception { ???if(!srcFile.exists()){ ???????throw new WarnException("文件不存在!"); ???} ???String fileName = srcFile.getAbsolutePath(); ???int i = fileName.lastIndexOf("."); ???if (i>0) { ???????fileName = fileName.substring(0,i); ???} ???File encFile = new File(fileName); ???getKey("aaaa"); ???Cipher cipher = Cipher.getInstance("DES"); ???cipher.init(Cipher.ENCRYPT_MODE,key); ???InputStream is = new FileInputStream(srcFile); ???CipherOutputStream out = new CipherOutputStream(new FileOutputStream(encFile), cipher); ???IOUtils.copyLarge(is, out); ???is.close(); ???out.flush(); ???out.close();    ???srcFile.delete();}

4、解密

/** * 解密 * @param srcFile * @param suffix * @return * @throws Exception */public static FileInputStream decFile(File srcFile,String suffix) throws Exception { ???FileInputStream fis = null; ???if(!srcFile.exists()){ ???????throw new WarnException("文件不存在!"); ???} ???String fileName = srcFile.getAbsolutePath() + "." + suffix; ???File decFile = new File(fileName); ???getKey("aaaa"); ???Cipher cipher = Cipher.getInstance("DES"); ???cipher.init(Cipher.DECRYPT_MODE, key); ???InputStream is = new FileInputStream(srcFile); ???OutputStream out = new FileOutputStream(decFile); ???CipherOutputStream cos = new CipherOutputStream(out, cipher); ???byte[] buffer = new byte[1024]; ???int length; ???while ((length = is.read(buffer)) >= 0) { ???????cos.write(buffer, 0, length); ???} ???fis = new FileInputStream(decFile); ???cos.close(); ???out.close(); ???is.close(); ???return fis;}

上传与下载文件加密

原文地址:http://www.cnblogs.com/hugang2017/p/7978271.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved