资源简介
des对文件加密,生成.tdes文件、解密后生成解密文件。本方法是纯利用二进制流对文件的加解密、
代码片段和文件信息
package com.ricorsoft.safe.common;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
public class Demo1 {
public static void main(String[] args) throws IOException {
// 需要加密的文件
File file = new File(“d:/都站起來.xls“);
// new Demo1().encrypt(file.getAbsoluteFile()
// “83049E80D03B7F706DE085C2EA3EAD078CB69B2637455B4F“);
// 加密后的文件
File fileEnCase = new File(“d:/都站起來.xls.tdes“);
// 解密后的文件名
new Demo1().decrypt(fileEnCase
“83049E80D03B7F706DE085C2EA3EAD078CB69B2637455B4F“);
String filePath = fileEnCase.getParent();
String fileName = fileEnCase.getName();
String name = fileName.substring(0 fileName.lastIndexOf(“.“));
String newFileName = fileEnCase.getParent() + name;
}
// --------------------------------------------------加密-------------------------------
/**
* 加密函数 输入: 要加密的文件,密码(由0-F组成,共48个字符,表示3个8位的密码)如:
* AD67EA2F3BE6E5ADD368DFE03120B5DF92A8FD8FEC2F0746 其中: AD67EA2F3BE6E5AD
* DES密码一 D368DFE03120B5DF DES密码二 92A8FD8FEC2F0746 DES密码三 输出:
* 对输入的文件加密后,保存到同一文件夹下增加了“.tdes“扩展名的文件中。
*/
private void encrypt(File fileIn String sKey) {
try {
if (sKey.length() == 48) {
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 = encryptByDES(encryptByDES(encryptByDES(bytIn
bytK1) bytK2) bytK3);
String fileOut = fileIn.getPath() + “.tdes“;
FileOutputStream fos = new FileOutputStream(fileOut);
for (int i = 0; i < bytOut.length; i++) {
fos.write((int) bytOut[i]);
}
fos.close();
System.out.println(“加密成功!“);
} else
System.out.println(“密码长度必须等于48!“);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 用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);
}
/**
* 用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
- 上一篇:jsp外文参考文献
- 下一篇:DBUtils工具包Jar包及帮助文档
评论
共有 条评论