码迷,mamicode.com
首页 > Web开发 > 详细

上传与下载文件加密

时间:2017-12-04 19:02:52      阅读:208      评论:0      收藏:0      [点我收藏+]

标签:flush   sql   encrypt   string   map   dex   secure   under   return   

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

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;
}

 

上传与下载文件加密

标签:flush   sql   encrypt   string   map   dex   secure   under   return   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!