1. 程式人生 > >上傳與下載文件加密

上傳與下載文件加密

erro void exceptio write cfi put secure sta ring

文件上傳與下載時,對文件進行加密。

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

上傳與下載文件加密