您所在的位置: 首页 > 开发 > JAVA > JAVA专区 > 基础教程 >

高级编程:三重DES加密程序(2)

  • 摘要:本文介绍利用Java实现的三重DES加密方法,包括使用的加密函数、解密函数以及实现的源代码。
  • 标签:Java  DES  加密  程序

解密函数
输入:
要解密的文件,密码(由0-F组成,共48个字符,表示3个8位的密码)如:
AD67EA2F3BE6E5ADD368DFE03120B5DF92A8FD8FEC2F0746
其中:
AD67EA2F3BE6E5AD DES密码一
D368DFE03120B5DF DES密码二
92A8FD8FEC2F0746 DES密码三
输出:
对输入的文件解密后,保存到用户指定的文件中。
*/

private void decrypt(File fileIn,String sKey){
try{
if(sKey.length() == 48){
String strPath = fileIn.getPath();
if(strPath.substring(strPath.length()-5).toLowerCase().equals(".tdes"))
strPath = strPath.substring(0,strPath.length()-5);
else{
JOptionPane.showMessageDialog(this,"不是合法的加密文件!",

"提示",JOptionPane.OK_OPTION);
return;
}
JFileChooser chooser = new JFileChooser();
chooser.setCurrentDirectory(new File("."));
chooser.setSelectedFile(new File(strPath));
//用户指定要保存的文件
int ret = chooser.showSaveDialog(this);
if(ret==JFileChooser.APPROVE_OPTION){
byte[] bytK1 = getKeyByStr(sKey.substring(0,16));
byte[] bytK2 = getKeyByStr(sKey.substring(16,32));
byte[] bytK3 = getKeyByStr(sKey.substring(32,48));
FileInputStream fis = new FileInputStream(fileIn);
byte[] bytIn = new byte[(int)fileIn.length()];
for(int i = 0;i< fileIn.length();i++){
bytIn[i] = (byte)fis.read();
}
//解密
byte[] bytOut = decryptByDES(decryptByDES(decryptByDES(bytIn,bytK3),bytK2),bytK1);
File fileOut = chooser.getSelectedFile();
fileOut.createNewFile();
FileOutputStream fos = new FileOutputStream(fileOut);
for(int i = 0;i< bytOut.length;i++){
fos.write((int)bytOut[i]);
}
fos.close();
JOptionPane.showMessageDialog(this,"解密成功!","提示",JOptionPane.OK_OPTION);
}
}else
JOptionPane.showMessageDialog(this,"密码长度必须等于48!",

"错误信息",JOptionPane.ERROR_MESSAGE);
}catch(Exception e){
JOptionPane.showMessageDialog(this,"解密失败,请核对密码!",

"提示",JOptionPane.OK_OPTION);
}
}

/**
用DES方法加密输入的字节
bytKey需为8字节长,是加密的密码
*/

private byte[] encryptByDES(byte[] bytP,byte[] bytKey) throws Exception{
DESKeySpec desKS = new DESKeySpec(bytKey);
SecretKeyFactory skf = SecretKeyFactory.getInstance("DES");
SecretKey sk = skf.generateSecret(desKS);
Cipher cip = Cipher.getInstance("DES");
cip.init(Cipher.ENCRYPT_MODE,sk);
return cip.doFinal(bytP);
}

/**
用DES方法解密输入的字节
bytKey需为8字节长,是解密的密码
*/

private byte[] decryptByDES(byte[] bytE,byte[] bytKey) throws Exception{
DESKeySpec desKS = new DESKeySpec(bytKey);
SecretKeyFactory skf = SecretKeyFactory.getInstance("DES");
SecretKey sk = skf.generateSecret(desKS);
Cipher cip = Cipher.getInstance("DES");
cip.init(Cipher.DECRYPT_MODE,sk);
return cip.doFinal(bytE);
}


共3页: 上一页 [1] 2 [3] 下一页
【内容导航】
深入Vista应用程序开发
程序员如何成长?
Java实用开发全集
Java类的基础教程专题
Java发展动态专题
 
 验证码: (点击刷新验证码)   匿名发表
  • 微软360度-成功与成长

  • 作者:张奭,方敏,欧琼
  • 本书是由微软总部华人协会组织编写的第二本书,是《微软360度——企业和文化》一书的姐妹篇,本书将着重向你呈现微软总部的华人..
Copyright©2005-2008 51CTO.COM 版权所有