文件上传与下载时,对文件进行加密。
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