文件加密解密

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;


import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.CipherOutputStream;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;


/**
 * @Title: 文件加密/解密
 * 
 * @author sunhongwei
 */
public class FileAesEncryptUtil {
//加密文件扩展名称
private String encryptFileExtName="edata";
//加密密码
private String sPassword;
//记录被解密的文件
private  static String[] decryptFiles=new String[100];
//构造方法(加密密码)
public FileAesEncryptUtil(String sPassword){
this.sPassword=sPassword;
}
//构造方法(加密密码,加密文件扩展名)
public FileAesEncryptUtil(String sPassword,String encryptFileExtName){
this.sPassword=sPassword;
this.encryptFileExtName=encryptFileExtName;
}




/****************************************************************************************************************************************/
/************************************************   加  密  ******************************************************************************/
/****************************************************************************************************************************************/
/**
* @名 称:对原文件加密存储

* @param sourceFileName  原文件名称
*
* @return String 加密后文件
*
* @author sunhongwei
*/
public File encryptFile(String sourceFileName) {
return encryptFile(sourceFileName,null);
}
/**
* @名 称:对原文件加密存储

* @param sourceFileName  原文件名称
* @param encryptFileStorePath       加密文件存储路径
*
* @return String 加密后文件
*
* @author sunhongwei
*/
public File encryptFile(String sourceFileName,String encryptFileStorePath) {
return encryptFile(sourceFileName,encryptFileStorePath,null);
}

/**
* @名 称:对原文件加密存储

* @param sourceFileName  原文件名称
* @param encryptFileStorePath       加密文件存储路径
* @param encryptFileStoreName    加密文件存储名称
*
* @return String 加密后文件
*
* @author sunhongwei
*/
public File encryptFile(String sourceFileName,String encryptFileStorePath,String encryptFileStoreName) {
//对原文件实例化
File sourceFile=new File(sourceFileName);
//加密文件名称
String encrypFileName;
//encryptFile(sourceFileName)
if(encryptFileStorePath==null){
//取得原文件父文件夹的绝对路径
encryptFileStorePath=sourceFile.getParentFile().getAbsolutePath();
}else{
//根据加密文件存储路径创建文件夹
File path=new  File(encryptFileStorePath);
if(!path.exists())
path.mkdirs();
}
//encryptFile(sourceFileName,encryptFileStorePath)
if(encryptFileStoreName==null){
encryptFileStoreName=sourceFile.getName();
}
//File.separator表示\
encrypFileName=encryptFileStorePath+File.separator+encryptFileStoreName ;
System.out.println(encrypFileName);
File  encryptFile= encryptFile(sourceFile,encrypFileName,encryptFileExtName);
return encryptFile;
}
/*
* @param 原文件
* @param 加密文件名称
* @param 加密文件扩展名称
* @return 加密文件
*/
public File encryptFile(File sourceFile,String encrypFileName ,String encryptFileExtName) {
//新建输入流
InputStream inputStream = null;
//新建加密文件
File encrypFile = null;
try {
//实例化文件输入流
inputStream = new FileInputStream(sourceFile);
//加密文件
encrypFile=saveToEncryptFile( inputStream, encrypFileName,encryptFileExtName);
} catch (FileNotFoundException e) {
e.printStackTrace();
}finally{
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace(); //io异常  
}
}
if(encrypFile!=null){
return encrypFile;
}else{
return null;
}
}


/**
* @名 称:对文件进行AES加密

* @param sourceFile                     原文件
* @param encrypFileName           加密后文件名称
* @return                                       
*
* @return File                               加密后文件
*
* @author sunhongwei
*/
public File saveToEncryptFile(InputStream inputStream,String encrypFileName ,String encryptFileExtName) {
//新建临时加密文件  
File encrypFile = null;
//新建输出流
OutputStream outputStream = null;
try {
//路径+扩展名
encrypFileName+="."+encryptFileExtName;
System.out.println(encrypFileName);
//根据加密文件path实例化文件
encrypFile = new File(encrypFileName);

//新建输出流
outputStream = new FileOutputStream(encrypFile);

//初始化aes密码
Cipher cipher = initAESCipher(this.sPassword, Cipher.ENCRYPT_MODE);

//以加密流写入文件  
CipherInputStream cipherInputStream = new CipherInputStream(inputStream, cipher);
byte[] cache = new byte[1024];
int nRead = 0;
while ((nRead = cipherInputStream.read(cache)) != -1) {
outputStream.write(cache, 0, nRead);
outputStream.flush();
}
cipherInputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace(); //找不到文件异常 
} catch (IOException e) {
e.printStackTrace(); //io异常 
} finally {
try {
outputStream.close();//关闭输出流
} catch (IOException e) {
e.printStackTrace(); //io异常 
}
}
return encrypFile;
}


/****************************************************************************************************************************************/
/************************************************   解  密  ******************************************************************************/
/****************************************************************************************************************************************/
/**
* @名 称:对原文件解密存储

* @param sourceFileName  原文件名称
*
* @return String 加密后文件的路径
*
* @author sunhongwei
*/
public File decryptFile(String sourceFileName) {
return decryptFile(sourceFileName,null);
}
/**
* @名 称:对原文件加密存储

* @param sourceFileName  原文件名称
* @param encryptFileStorePath       加密文件存储路径
*
* @return String 加密后文件的路径
*
* @author sunhongwei
*/
public File decryptFile(String sourceFileName,String decryptFileStorePath) {
return decryptFile(sourceFileName,decryptFileStorePath,null);
}

/**
* @名 称:对原文件加密存储

* @param sourceFileName  原文件名称
* @param encryptFileStorePath       加密文件存储路径
* @param encryptFileStoreName    加密文件存储名称
*
* @return String 加密后文件的路径
*
* @author sunhongwei
*/
public File decryptFile(String sourceFileName,String decryptFileStorePath,String decryptFileStoreName) {
//新建file对象
File sourceFile=new File(sourceFileName);
String decrypFileName;
//取得原文件父文件夹的绝对路径作为加密文件存储路径
if(decryptFileStorePath==null){
decryptFileStorePath=sourceFile.getParentFile().getAbsolutePath();
}else{
//创建路径
File path=new  File(decryptFileStorePath);
if(!path.exists())
path.mkdirs();
}
//根据原文件名称得到加密文件存储路径
if(decryptFileStoreName==null){
decryptFileStoreName=sourceFile.getName();
decryptFileStoreName=decryptFileStoreName.substring(0,(decryptFileStoreName.length()-encryptFileExtName.length()-1));
}else{
//原扩展名称
String fileName=sourceFile.getName();
String oldFileName=fileName.substring(0,(fileName.length()-encryptFileExtName.length()-1));
String oldExtName=oldFileName.substring(oldFileName.lastIndexOf(".")+1);
decryptFileStoreName+="."+oldExtName;
}

decrypFileName=decryptFileStorePath+File.separator+decryptFileStoreName;

File  decryptFile= decryptFile(sourceFile,decrypFileName);
return decryptFile;
}
/**
* AES方式解密文件

* @param sourceFile
* @return 解密文件存储位置
*/
public File decryptFile(File sourceFile,String decryptFileName) {
File decryptFile = null;
InputStream inputStream = null;
OutputStream outputStream = null;
try {
decryptFile = new File(decryptFileName);

Cipher cipher = initAESCipher(this.sPassword, Cipher.DECRYPT_MODE);
inputStream = new FileInputStream(sourceFile);
outputStream = new FileOutputStream(decryptFile);
CipherOutputStream cipherOutputStream = new CipherOutputStream(outputStream, cipher);
byte[] buffer = new byte[1024];
int r;
while ((r = inputStream.read(buffer)) >= 0) {
cipherOutputStream.write(buffer, 0, r);
}
cipherOutputStream.close();
} catch (IOException e) {
e.printStackTrace(); //io异常 
} finally {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace(); //io异常  
}
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace(); //io异常  
}
}
return decryptFile;
}

/**
* 判断文件是否为加密文件
* 参数:字符串数组,秘钥
* 返回字符串数组
*/
public static String [] judgmentEncryption(String[] path,String sKey){
String files[]=new String[path.length];
for(int i=0;i<path.length;i++){
if(path[i].substring(path[i].lastIndexOf(".")+1).equals("edata")){
//加密文件,先解密
FileAesEncryptUtil fileEncrypt=new FileAesEncryptUtil(sKey);
File file=fileEncrypt.decryptFile(path[i]);
files[i]=file.getAbsolutePath();
//记录被解密的文件
int j=0;
decryptFiles[j]=file.getAbsolutePath();
j++;
}else{
//非加密文件
files[i]=path[i];
}
}
return files;
}

/**
* 删除解密后的文件
*/
public static void removeDecryption(){
if(decryptFiles.length!=0){
for(int i=0;i<decryptFiles.length-1;i++){
if(decryptFiles[i]!=null){
     new File(decryptFiles[i]).delete();
}
}
}
}

/************************************************   初始化  ******************************************************************************/
/****************************************************************************************************************************************/
/**
* 初始化 AES Cipher

* @param sKey
* @param cipherMode
* @return
*/
private Cipher initAESCipher(String sKey, int cipherMode) {
//创建密匙产生器  
KeyGenerator keyGenerator = null;
Cipher cipher = null;
try {
//密匙产生器根据aes实例化
keyGenerator = KeyGenerator.getInstance("AES");
//使用用户提供的password初始化此密钥生成器,使其具有确定的密钥大小128字节长
keyGenerator.init(128, new SecureRandom(sKey.getBytes()));
//生成一个密匙
SecretKey secretKey = keyGenerator.generateKey();
//返回基本编码格式的密匙,如果此密匙不支持编码,则返回null
byte[] codeFormat = secretKey.getEncoded();
//根据给定的enCodeFormat字节数组构造一个用AES算法加密的密钥
SecretKeySpec key = new SecretKeySpec(codeFormat, "AES");
//创建密码器
cipher = Cipher.getInstance("AES");
//初始化  
cipher.init(cipherMode, key);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace(); //没有该算法异常
} catch (NoSuchPaddingException e) {
e.printStackTrace(); //没有该算法异常  
} catch (InvalidKeyException e) {
e.printStackTrace(); //无效密匙异常,超出密匙长度限制会报异常 
}
return cipher;
}



/**
* @名 称:
* @用 途:
* @思 路:
* @过 程:

* @param args

* @return void

* @author sunhongwei
*/
public static void main(String[] args) {
String sKey = "123456";

String sourceFile1 ="d://xcc//aa.txt";
long starttime=System.currentTimeMillis();
FileAesEncryptUtil fileEncrypt=new FileAesEncryptUtil(sKey);
fileEncrypt.encryptFile(sourceFile1,"d://files");
long endtime=System.currentTimeMillis();

System.out.println((endtime-starttime)/1000);

String sourceFile2 ="d://files//aa.txt.edata";
long starttime2=System.currentTimeMillis();
FileAesEncryptUtil fileEncrypt2=new FileAesEncryptUtil(sKey);
File file=fileEncrypt2.decryptFile(sourceFile2);
System.out.println(file.getAbsolutePath());
long endtime2=System.currentTimeMillis();

System.out.println((endtime2-starttime2)/1000);

}


}
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值