package des;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.spec.SecretKeySpec;
import des.common.ReadConfig;
public class FileDESCr {
static int BUFFER_CAPACITY=80;
public FileDESCr() {
// TODO Auto-generated constructor stub
}
/**
*
* @param srcFilePath 需要加密/解密的原文件
* @param destFilePath 加密/解密后的目标文件
* @param keyStr 8位字符以上的密钥
* @param isEncrypt 加密/解密状态位-true为加密,false为解密
* @throws Exception 异常
*/
public static void fileDES(String srcFilePath,String destFilePath,String keyStr,boolean isEncrypt)throws Exception{
String algorithm = "DES";
//产生钥匙
SecretKeySpec key =new SecretKeySpec(keyStr.getBytes(),algorithm);
Cipher cipher = Cipher.getInstance(algorithm);
if(isEncrypt){
//加密算法
cipher.init(Cipher.ENCRYPT_MODE,key);
}else{
//解密算法
cipher.init(Cipher.DECRYPT_MODE,key);
}
File srcFile = new File(srcFilePath);
File destFile = new File(destFilePath);
byte[]tempBuffer=new byte[BUFFER_CAPACITY];
FileInputStream inputFile = new FileInputStream(srcFile);
FileOutputStream outputFile = new FileOutputStream(destFile);
//加密或解密
CipherInputStream cins = new CipherInputStream (inputFile,cipher);
for(int n =0;(n=cins.read(tempBuffer))!=-1;){
outputFile.write(tempBuffer,0,n);
};
inputFile.close();
outputFile.close();
}
/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
System.out.println("开始读取配置文件......");
String file1 = ReadConfig.getConfigValue("file1.PATH");//"D:/doc/加密/tmp/1.zip";//源文件
String file2 = ReadConfig.getConfigValue("file2.PATH");//"D:/doc/加密/tmp/2.zip";//加密文件
String file3 = ReadConfig.getConfigValue("file3.PATH");//"D:/doc/加密/tmp/3.zip";//解密文件
String passWord = ReadConfig.getConfigValue("file.PASSWORD");//"1234ABCD";//密钥
FileDESCr.fileDES(file1, file2, passWord, true);//加密
System.out.println("加密结束......");
FileDESCr.fileDES(file2, file3, passWord, false);//解密
System.out.println("解密结束......");
}
}
注意:javax.crypto.*; 该包是:jdk安装目录下的lib包中的jce.jar文件。将该jar文件导入你的工作路径即可。