java des加密与解密

 

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文件导入你的工作路径即可。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值