des加密java代码 java实现des加密解密( 二 )


public static void decrypt(String keyPath, String source, String dest) {
SecretKey key = null;
try
{
ObjectInputStream keyFile = new ObjectInputStream(
//读取加密密钥
new FileInputStream(keyPath));
key = (SecretKey) keyFile.readObject();
keyFile.close();
}
catch (FileNotFoundException ey1) {
throw new RuntimeException(ey1);
}
catch (Exception ey2) {
throw new RuntimeException(ey2);
}
//用key产生Cipher
Cipher cipher = null;
try {
//设置算法,应该与加密时的设置一样
cipher = Cipher.getInstance("DES");
//设置解密模式
cipher.init(Cipher.DECRYPT_MODE, key);
}
catch (Exception ey3) {
throw new RuntimeException(ey3);
}
//取得要解密的文件并解密
File file = new File(source);
String filename = file.getName();
try {
//输出流,请注意文件名称的获取
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(dest));
//输入流
CipherInputStream in = new CipherInputStream(new BufferedInputStream(
new FileInputStream(file)), cipher);
int thebyte = 0;
while ( (thebyte = in.read()) != -1) {
out.write(thebyte);
}
in.close();
out.close();
}
catch (Exception ey5) {
throw new RuntimeException(ey5);
}
}
public static void encrypt(String keyPath, String source, String dest) {
SecretKey key = null;
try
{
ObjectInputStream keyFile = new ObjectInputStream(
//读取加密密钥
new FileInputStream(keyPath));
key = (SecretKey) keyFile.readObject();
keyFile.close();
}
catch (FileNotFoundException ey1) {
throw new RuntimeException(ey1);
}
catch (Exception ey2) {
throw new RuntimeException(ey2);
}
//用key产生Cipher
Cipher cipher = null;
try {
//设置算法,应该与加密时的设置一样
cipher = Cipher.getInstance("DES");
//设置解密模式
cipher.init(Cipher.ENCRYPT_MODE, key);
}
catch (Exception ey3) {
throw new RuntimeException(ey3);
}
//取得要解密的文件并解密
File file = new File(source);
String filename = file.getName();
try {
//输出流,请注意文件名称的获取
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(dest));
//输入流
CipherInputStream in = new CipherInputStream(new BufferedInputStream(
new FileInputStream(file)), cipher);
int thebyte = 0;
while ( (thebyte = in.read()) != -1) {
out.write(thebyte);
}
in.close();
out.close();
}
catch (Exception ey5) {
throw new RuntimeException(ey5);
}
}
}
java des 加密 解密 密钥随机取得方法java DES 加密 解密 生成随机密钥
举例说明des加密java代码:
//保存生成des加密java代码的key
public static void saveDesKey() {
try {
SecureRandom sr = new SecureRandom();
// 选择des加密java代码的DES算法生成一个KeyGenerator对象
KeyGenerator kg = KeyGenerator.getInstance("DES");
kg.init(sr);
// 相对路径 需要新建 conf 文件夹
// String fileName = "conf/DesKey.xml";
// 绝对路径
String fileName = "d:/DesKey.xml";
FileOutputStream fos = new FileOutputStream(fileName);
ObjectOutputStream oos = new ObjectOutputStream(fos);
// 生成密钥
Key key = kg.generateKey();
oos.writeObject(key);
oos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
//获取生成des加密java代码的key
public static Key getKey() {
Key kp = null;
try {
// 相对路径 需要新建 conf 文件夹
// String fileName = "conf/DesKey.xml";

推荐阅读