---
title: "java实现DES加密算法"
author: "jian0487"
date: "2009-08-11T00:49:26Z"
tags: ["C", "C++", "Java", "XML", "算法"]
slug: "java-des"
draft: false
lastmod: "2009-08-11T00:49:26Z"
id: 444285
url: "https://jian0487.iteye.com/blog/444285"
---

一、java实现DES加密算法  
为了实现一对密钥对整个项目所有加密解密文件都适用的方法,采用先生成一对密钥.保存到xml文件中,以后获得私匙和公钥只需要从xml文件中取得就可以了.  
/\**  
\*把成生的一对密钥保存到DesKey.xml文件中  
\*/  
publicstaticvoidsaveDesKey(){  
try{  
SecureRandomsr=newSecureRandom();  
//为我们选择的DES算法生成一个KeyGenerator对象  
KeyGeneratorkg=KeyGenerator.getInstance(\\"DES\\");  
kg.init(sr);  
FileOutputStreamfos=newFileOutputStream(\\"C:/DesKey.xml\\");  
ObjectOutputStreamoos=newObjectOutputStream(fos);  
//生成密钥  
Keykey=kg.generateKey();  
oos.writeObject(key);  
oos.close();  
}catch(Exceptione){  
e.printStackTrace();  
}  
}

获取密钥方法如下:

/\**  
\*获得DES加密的密钥。在交易处理的过程中应该定时更  
\*换密钥。需要JCE的支持，如果jdk版本低于1.4，则需要  
\*安装jce-1\_2\_2才能正常使用。  
\*@returnKey返回对称密钥  
\*/  
publicstaticKeygetKey(){  
Keykp=null;  
try{  
StringfileName=\\"conf/DesKey.xml\\";  
InputStreamis=DesUtil.class.getClassLoader()  
.getResourceAsStream(fileName);  
ObjectInputStreamoos=newObjectInputStream(is);  
kp=(Key)oos.readObject(); \[Page]  
oos.close();  
}catch(Exceptione){  
e.printStackTrace();  
}  
returnkp;  
}

文件采用DES算法加密文件

/\**  
\*文件file进行加密并保存目标文件destFile中

\*@paramfile  
\*要加密的文件如c:/test/srcFile.txt  
\*@paramdestFile  
\*加密后存放的文件名如c:/加密后文件.txt  
\*/

publicstaticvoidencrypt(Stringfile,StringdestFile)throwsException{

Ciphercipher=Cipher.getInstance(\\"DES\\");

cipher.init(Cipher.ENCRYPT\_MODE,getKey());

InputStreamis=newFileInputStream(file);

OutputStreamout=newFileOutputStream(dest);

CipherInputStreamcis=newCipherInputStream(is,cipher);

byte\[]buffer=newbyte\[1024];

intr;

while((r=cis.read(buffer))&gt;0){

out.write(buffer,0,r);

}

cis.close();

is.close();

out.close();

}

文件采用DES算法解密文件

/\**  
\*文件file进行加密并保存目标文件destFile中