日期:2014-05-20  浏览次数:20781 次

!!!!!!!!!!求DES 算法加解密数据 JAVA版
拜求!!!

------解决方案--------------------
http://www.java2s.com/Code/JavaDownload/DESCrypterandDecrypter.zip
------解决方案--------------------
DES算法加、解密
(originalFile为原文件,encrtpy为加密后的文件,decrtpy为解密的文件)
DES算法的密钥内容不是由用户提供的,是随机产生的这样每次加密后的文件都不相同
public class DESkey {
public DESkey() {
//加密
try {
FileInputStream fileIn = new FileInputStream(originalFile);
//此类提供(对称)密钥生成器的功能(生成一个DES算法的密钥)
KeyGenerator keygen = KeyGenerator.getInstance( "DES ");
//这里是重点:生成一个密钥--deskey
SecretKey deskey = keygen.generateKey();
//定义一个DES加密算法
Cipher cipher = Cipher.getInstance( "DES ")
//由于DES算法的密钥是随机的,要解密,就要获得这个密钥
FileOutputStream writeFilekey = new FileOutputStream(fileKey);
//在这里已字节码形式保存这个密钥,使之能在解密时使用
writeFilekey.write(deskey.getEncoded());
//定义DES算法的状态(加密),和使用的密钥
cipher.init(Cipher.ENCRYPT_MODE, deskey);
byte[] cipherByte = new byte[(int) originalFile.length()];
fileIn.read(cipherByte);
//对读入的文件加密
cipherByte = cipher.doFinal(cipherByte);
FileOutputStream fileout = new FileOutputStream(encryptFile);
fileout.write(cipherByte);
fileIn.close();
writeFilekey.close();
fileout.close();
//解密
FileInputStream fileIn2 = new FileInputStream(encryptFile);
FileInputStream readkey = new FileInputStream(fileKey);
byte[] rawKeyData = new byte[(int) fileKey.length()];
//获得原DES加密时使用密钥的字节码
readkey.read(rawKeyData);
//使用获得的字节码创建一个DES算法密钥生成的规则-- dks
DESKeySpec dks = new DESKeySpec(rawKeyData);
//创建一个DES算法密钥的密钥工厂
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance( "DES ");
try {
//在工厂中使用DES算法密钥生成的规则—dks,创建一个DES密钥
SecretKey skey = keyFactory.generateSecret(dks);
Cipher thiskey = Cipher.getInstance( "DES ");
thiskey.init(Cipher.DECRYPT_MODE, skey);
byte[] cipherByte2 = new byte[(int) encryptFile.length()];
fileIn2.read(cipherByte2);
cipherByte = thiskey.doFinal(cipherByte2);
FileOutputStream fileout2 = new FileOutputStream(decryptFile);
fileout2.write(cipherByte);
fileIn2.close();
fileout2.close();
} catch (InvalidKeySpecException ex) {
}
}
catch (FileNotFoundException ex) {
} catch (NoSuchAlgorithmException ex) {
} catch (IOException ex) {
} catch (NoSuchPaddingException ex) {
} catch (InvalidKeyException ex) {
} catch (BadPaddingException ex) {
} catch (IllegalBlockSizeException ex) {
}
}
}