http://hi.baidu.com/java0804ms/item/111ea834fbd4d2f596f88d5a

实现效果:对文件内容进行加密,使之直接打开成为乱码,不以明文显示

实现步骤:1.key.txt里面存放的是加密文件的密码,这个是明文

2.源文件加密后,加密后的文件如果是压缩包必须通过程序解密后,方可打开,直接用软件是打不开加密后的压缩文件(此处需要注意一下,例如:将test.txt加密压缩后成为新的文件test.rar,test.rar必须通过程序解密后,才能用软件打开,如果直接打开test.rar是不行的)

3.已经测试,方案可行,详情请参见代码:

实现代码如下:

package com.test;

import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.security.Key; import java.security.SecureRandom; import java.util.UUID; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import java.util.zip.ZipOutputStream; import javax.crypto.Cipher; import javax.crypto.KeyGenerator; import javax.crypto.SecretKey; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec;

/** * 对文件加密/解密和压缩/解压缩对象类 */ public class test { public static void main(String args[]) throws Exception{   //自定义压缩方式   String srcFile = "c://test.rar";//源文件   String destFile = "c://test1.rar";//加密后文件   Key privateKey = new test().getKey("c://key.txt");//存放解密密码   new test().encrypt(srcFile, destFile, privateKey);//加密压缩文件(压缩后的文件必须通过程序解密才能打开)   new test().decrypt(destFile, "c://text2.rar", privateKey);//解密压缩文件 } private void directoryZip(ZipOutputStream out, File f, String base)    throws Exception {   // 如果传入的是目录   if (f.isDirectory()) {    File[] fl = f.listFiles();    // 创建压缩的子目录    out.putNextEntry(new ZipEntry(base + "/"));    if (base.length() == 0) {     base = "";    } else {     base = base + "/";    }    for (int i = 0; i < fl.length; i++) {     directoryZip(out, fl[i], base + fl[i].getName());    }   } else {    // 把压缩文件加入rar中    out.putNextEntry(new ZipEntry(base));    FileInputStream in = new FileInputStream(f);    byte[] bb = new byte[2048];    int aa = 0;    while ((aa = in.read(bb)) != -1) {     out.write(bb, 0, aa);    }    in.close();   } }

/**   * 压缩文件   *   * @param zos   * @param file   * @throws Exception   */ private void fileZip(ZipOutputStream zos, File file) throws Exception {   if (file.isFile()) {    zos.putNextEntry(new ZipEntry(file.getName()));    FileInputStream fis = new FileInputStream(file);    byte[] bb = new byte[2048];    int aa = 0;    while ((aa = fis.read(bb)) != -1) {     zos.write(bb, 0, aa);    }    fis.close();    System.out.println(file.getName());   } else {    directoryZip(zos, file, "");   } }

/**   * 解压缩文件   *   * @param zis   * @param file   * @throws Exception   */ private void fileUnZip(ZipInputStream zis, File file) throws Exception {   ZipEntry zip = zis.getNextEntry();   if (zip == null)    return;   String name = zip.getName();   File f = new File(file.getAbsolutePath() + "/" + name);   if (zip.isDirectory()) {    f.mkdirs();    fileUnZip(zis, file);   } else {    f.createNewFile();    FileOutputStream fos = new FileOutputStream(f);    byte b[] = new byte[2048];    int aa = 0;    while ((aa = zis.read(b)) != -1) {     fos.write(b, 0, aa);    }    fos.close();    fileUnZip(zis, file);   } }

/**   * 对directory目录下的文件压缩,保存为指定的文件zipFile   *   * @param directory   * @param zipFile   */ private void zip(String directory, String zipFile) {   try {    ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(      zipFile));    fileZip(zos, new File(directory));    zos.close();   } catch (Exception e) {    e.printStackTrace();   } }

/**   * 解压缩文件zipFile保存在directory目录下   *   * @param directory   * @param zipFile   */ private void unZip(String directory, String zipFile) {   try {    ZipInputStream zis = new ZipInputStream(      new FileInputStream(zipFile));    File f = new File(directory);    f.mkdirs();    fileUnZip(zis, f);    zis.close();   } catch (Exception e) {    e.printStackTrace();   } }

/**   * 根据key的路径文件获得持久化成文件的key   * <P>   * 例子: RsaEncrypt.getKey("c:/systemkey/private.key");   *   * @param keyPath   * @return   */ private Key getKey(String keyPath) throws Exception {   FileInputStream fis = new FileInputStream(keyPath);   byte[] b = new byte[16];   fis.read(b);   SecretKeySpec dks = new SecretKeySpec(b, "AES");   fis.close();   return dks; }

/**   * 把文件srcFile加密后存储为destFile   *   * @param srcFile   * @param destFile   */ private void encrypt(String srcFile, String destFile, Key privateKey)    throws Exception {   SecureRandom sr = new SecureRandom();   Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");   IvParameterSpec spec = new IvParameterSpec(privateKey.getEncoded());   cipher.init(Cipher.ENCRYPT_MODE, privateKey, spec, sr);   FileInputStream fis = new FileInputStream(srcFile);   FileOutputStream fos = new FileOutputStream(destFile);   byte[] b = new byte[2048];   while (fis.read(b) != -1) {    fos.write(cipher.doFinal(b));   }   fos.close();   fis.close(); }

/**   * 把文件srcFile解密后存储为destFile   *   * @param srcFile   * @param destFile   * @param privateKey   * @throws Exception   */ private void decrypt(String srcFile, String destFile, Key privateKey)    throws Exception {   SecureRandom sr = new SecureRandom();   Cipher ciphers = Cipher.getInstance("AES/CBC/PKCS5Padding");   IvParameterSpec spec = new IvParameterSpec(privateKey.getEncoded());   ciphers.init(Cipher.DECRYPT_MODE, privateKey, spec, sr);   FileInputStream fis = new FileInputStream(srcFile);   FileOutputStream fos = new FileOutputStream(destFile);   byte[] b = new byte[2064];   while (fis.read(b) != -1) {    fos.write(ciphers.doFinal(b));   }   fos.close();   fis.close(); }

/**   * 对目录srcFile下的所有文件目录进行先压缩后操作,然后保存为destfile   *   * @param srcFile   *            要操作的目录 如c:/test/test   * @param destfile   *            压缩加密后存放的文件名 如c:/加密压缩文件.zip   * @param keyfile   *            公钥存放地点   */ public void encryptZip(String srcFile, String destfile, String keyfile)    throws Exception {   SecureRandom sr = new SecureRandom();   KeyGenerator kg = KeyGenerator.getInstance("AES");   kg.init(128, sr);   SecretKey key = kg.generateKey();   File f = new File(keyfile);   if (!f.getParentFile().exists())    f.getParentFile().mkdirs();   f.createNewFile();   FileOutputStream fos = new FileOutputStream(f);   fos.write(key.getEncoded());   File temp = new File(UUID.randomUUID().toString() + ".zip");   temp.deleteOnExit();   // 先压缩文件   zip(srcFile, temp.getAbsolutePath());   // 对文件加密   encrypt(temp.getAbsolutePath(), destfile, key);   temp.delete(); }

/**   * 对文件srcfile进行先解密后解压缩,然后解压缩到目录destfile下   *   * @param srcfile   *            要解密和解压缩的文件名 如c:/目标.zip   * @param destfile   *            解压缩后的目录 如c:/abc   * @param publicKey   *            公钥   */ public void decryptUnzip(String srcfile, String destfile, String keyfile)    throws Exception {   // 先对文件解密   File temp = new File(UUID.randomUUID().toString() + ".zip");   temp.deleteOnExit();   decrypt(srcfile, temp.getAbsolutePath(), this.getKey(keyfile));   // 解压缩   unZip(destfile, temp.getAbsolutePath());   temp.delete(); } }

【开发技术】对文件内容进行加密-java的更多相关文章

  1. java 实现文件内容的加密和解密

    package com.umapp.test; import java.io.FileInputStream; import java.io.FileOutputStream; import java ...

  2. iphone开发技术要学习的内容

    一.iOS基础 1 开发环境搭建以及IOS组件.框架的概要介绍. 2 mac操作系统与iOS操作系统 3 xcode IDE开发环境的初始 二.C语言基础 1数据类型.表达式与控制流程语句 2数组.函 ...

  3. Java不走弯路教程(3.用户验证与文件内容查询)

    3.用户验证与文件内容查询 在上一章中,我们完成了对指定文件内容的输出操作. 我们现在有如下格式的文件product.db id,product_name,product_detail 1,noteb ...

  4. 博主有偿带徒 《编程语言设计和实现》《MUD游戏开发》《软件破解和加密》《游戏辅助外挂》《JAVA开发》

    <考研专题>操作系统原理 理论解答:8K 实战 1.5W CPU设计 理论解答:1W 实战 2.5W <编程语言设计和实现>初窥门径<5K>:编译原理.编译设计小试 ...

  5. Java EE开发技术课程第五周(Applet程序组件与AJAX技术)

    1.Applet程序组件 1.1.定义: Applet是采用Java编程语言编写的小应用程序,该程序可以包含在HTML(标准通用标记语言的一个应用)页中,与在页中包含图像的方式大致相同.含有Apple ...

  6. Java Web开发技术教程入门-JSP基本语法和九大内置对象

    这两天气温逐渐升高,好想把自己泡在冰块里······ 恩嗯摁蒽恩嗯摁蒽恩嗯摁蒽恩嗯摁蒽.......今天阅读到了这本书的第四章-JSP基本语法.经过第一天的阅读,我们明白JSP技术是Java Web开 ...

  7. Java Web开发技术教程入门-静态网页技术

        昨天了解了构建动态网站的几种技术:Servlet技术.JSP技术,ASP技术和ASP.NET技术以及PHP技术.昨天的精髓在于JSP技术的运行原理:通过用户请求JSP文件,首先检查JSP文件的 ...

  8. 五种方式让你在java中读取properties文件内容不再是难题

    一.背景 最近,在项目开发的过程中,遇到需要在properties文件中定义一些自定义的变量,以供java程序动态的读取,修改变量,不再需要修改代码的问题.就借此机会把Spring+SpringMVC ...

  9. java swing文件内容检索工具

    Java相关技术 - 文件内容检索工具 拿到一个几百M甚至上G的project让你去学习 有时候你会想知道某个关键词是在哪个文件里 比如:spring MVC配置的@RequestMapping,你从 ...

随机推荐

  1. 鸟哥的linux私房菜学习-(二)VMware虚拟机及linux系统安装过程

    一.安装虚拟机 1.虚拟机常用版本及注册码地址:https://pan.baidu.com/s/1dFnkBrN#list/path=%2FSoftware%20Big%2FVMware%20Work ...

  2. MySQL查询(进阶)(每个标点都是重点)

    MySQL 是工作中很普遍的需要用到的,所以必须掌握,而 之前我们一直说的都是怎么存. 你只会存不会取有个屁用.所以希望大家在如何查询读取数据这方面多下点功夫. 这篇和上一篇都是干货,我也是第一次学. ...

  3. 深入浅出Android之学习笔记

    1.查看启动log [2011-01-11 14:44:21 - BMI] Android Launch! [2011-01-11 14:44:21 - BMI] adb is running nor ...

  4. Xposed 学习笔记

    Xposed框架用法 1.配置AndroidManifest.xml <meta-data android:name="xposedmodule" android:value ...

  5. 微信小程序开发之详解生命周期方法

    生命周期是指一个小程序从创建到销毁的一系列过程 在小程序中 ,通过App()来注册一个小程序 ,通过Page()来注册一个页面 先来看一张小程序项目结构 从上图可以看出,根目录下面有包含了app.js ...

  6. 理解css伪类和伪元素

    伪类就是可以通过直接添加一个类样式达到同等效果,而伪元素,则需要先添加一个元素,然后在元素上添加样式才能达到同等效果 伪类 :active 向被激活的元素添加样式. :focus 向拥有键盘输入焦点的 ...

  7. Mongodb常规操作【一】

    Mongodb是一种比较常见的NOSQL数据库,数据库排名第四,今天介绍一下Net Core 下,常规操作. 首先下C# 版的驱动程序 "MongoDB.Driver",相关依赖包 ...

  8. css-display

    1. none:隐藏对象.与visibility属性的hidden值不同,其不为被隐藏的对象保留其物理空间 2. inline:指定对象为内联元素. 3. block:指定对象为块元素. 4. inl ...

  9. Qt用Zip压缩文件夹的一些坑

    环境: QT3.3.8 vs2005 QDir dir("/home/Blinux/html"); if ( !dir.exists() ) { //目录不存在 } QString ...

  10. [wiki]CDN

    内容分发网 内容分发网络(Content delivery network或Content distribution network,缩写:CDN)是指一种通过互联网互相连接的电脑网络系统,利用最靠近 ...