本文目录一览:
- 如何使用JAVA实现对字符串的DES加密和解密
- [Java中 DES加密算法](#Java中 DES加密算法)
- 如何利用DES加密的算法保护Java源代码
- 用java实现DES加密算法,细致点,要直接粘贴进平台能运行的!!
- [DES加密算法 java实现](#DES加密算法 java实现)
- 求用JAVA实现的DES算法
如何使用JAVA实现对字符串的DES加密和解密
java加密字符串可以使用des加密算法,实例如下:
package test;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.security.*;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
/**
* 加密解密
*
* @author shy.qiu
* @since
*/
public class CryptTest {
/**
* 进行MD5加密
*
* @param info 要加密的信息
* @return String 加密后的字符串
*/
public String encryptToMD5(String info) {
byte[] digesta = null;
try {
// 得到一个md5的消息摘要
MessageDigest alga = MessageDigest.getInstance("MD5");
// 添加要进行计算摘要的信息
alga.update(info.getBytes());
// 得到该摘要
digesta = alga.digest();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
// 将摘要转为字符串
String rs = byte2hex(digesta);
return rs;
}
/**
* 进行SHA加密
*
* @param info 要加密的信息
* @return String 加密后的字符串
*/
public String encryptToSHA(String info) {
byte[] digesta = null;
try {
// 得到一个SHA-1的消息摘要
MessageDigest alga = MessageDigest.getInstance("SHA-1");
// 添加要进行计算摘要的信息
alga.update(info.getBytes());
// 得到该摘要
digesta = alga.digest();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
// 将摘要转为字符串
String rs = byte2hex(digesta);
return rs;
}
// //////////////////////////////////////////////////////////////////////////
/**
* 创建密匙
*
* @param algorithm 加密算法,可用 DES,DESede,Blowfish
* @return SecretKey 秘密(对称)密钥
*/
public SecretKey createSecretKey(String algorithm) {
// 声明KeyGenerator对象
KeyGenerator keygen;
// 声明 密钥对象
SecretKey deskey = null;
try {
// 返回生成指定算法的秘密密钥的 KeyGenerator 对象
keygen = KeyGenerator.getInstance(algorithm);
// 生成一个密钥
deskey = keygen.generateKey();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
// 返回密匙
return deskey;
}
/**
* 根据密匙进行DES加密
*
* @param key 密匙
* @param info 要加密的信息
* @return String 加密后的信息
*/
public String encryptToDES(SecretKey key, String info) {
// 定义 加密算法,可用 DES,DESede,Blowfish
String Algorithm = "DES";
// 加密随机数生成器 (RNG),(可以不写)
SecureRandom sr = new SecureRandom();
// 定义要生成的密文
byte[] cipherByte = null;
try {
// 得到加密/解密器
Cipher c1 = Cipher.getInstance(Algorithm);
// 用指定的密钥和模式初始化Cipher对象
// 参数:(ENCRYPT_MODE, DECRYPT_MODE, WRAP_MODE,UNWRAP_MODE)
c1.init(Cipher.ENCRYPT_MODE, key, sr);
// 对要加密的内容进行编码处理,
cipherByte = c1.doFinal(info.getBytes());
} catch (Exception e) {
e.printStackTrace();
}
// 返回密文的十六进制形式
return byte2hex(cipherByte);
}
/**
* 根据密匙进行DES解密
*
* @param key 密匙
* @param sInfo 要解密的密文
* @return String 返回解密后信息
*/
public String decryptByDES(SecretKey key, String sInfo) {
// 定义 加密算法,
String Algorithm = "DES";
// 加密随机数生成器 (RNG)
SecureRandom sr = new SecureRandom();
byte[] cipherByte = null;
try {
// 得到加密/解密器
Cipher c1 = Cipher.getInstance(Algorithm);
// 用指定的密钥和模式初始化Cipher对象
c1.init(Cipher.DECRYPT_MODE, key, sr);
// 对要解密的内容进行编码处理
cipherByte = c1.doFinal(hex2byte(sInfo));
} catch (Exception e) {
e.printStackTrace();
}
// return byte2hex(cipherByte);
return new String(cipherByte);
}
// /////////////////////////////////////////////////////////////////////////////
/**
* 创建密匙组,并将公匙,私匙放入到指定文件中
*
* 默认放入mykeys.bat文件中
*/
public void createPairKey() {
try {
// 根据特定的算法一个密钥对生成器
KeyPairGenerator keygen = KeyPairGenerator.getInstance("DSA");
// 加密随机数生成器 (RNG)
SecureRandom random = new SecureRandom();
// 重新设置此随机对象的种子
random.setSeed(1000);
// 使用给定的随机源(和默认的参数集合)初始化确定密钥大小的密钥对生成器
keygen.initialize(512, random);// keygen.initialize(512);
// 生成密钥组
KeyPair keys = keygen.generateKeyPair();
// 得到公匙
PublicKey pubkey = keys.getPublic();
// 得到私匙
PrivateKey prikey = keys.getPrivate();
// 将公匙私匙写入到文件当中
doObjToFile("mykeys.bat", new Object[] { prikey, pubkey });
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
}
/**
* 利用私匙对信息进行签名 把签名后的信息放入到指定的文件中
*
* @param info 要签名的信息
* @param signfile 存入的文件
*/
public void signToInfo(String info, String signfile) {
// 从文件当中读取私匙
PrivateKey myprikey = (PrivateKey) getObjFromFile("mykeys.bat", 1);
// 从文件中读取公匙
PublicKey mypubkey = (PublicKey) getObjFromFile("mykeys.bat", 2);
try {
// Signature 对象可用来生成和验证数字签名
Signature signet = Signature.getInstance("DSA");
// 初始化签署签名的私钥
signet.initSign(myprikey);
// 更新要由字节签名或验证的数据
signet.update(info.getBytes());
// 签署或验证所有更新字节的签名,返回签名
byte[] signed = signet.sign();
// 将数字签名,公匙,信息放入文件中
doObjToFile(signfile, new Object[] { signed, mypubkey, info });
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 读取数字签名文件 根据公匙,签名,信息验证信息的合法性
*
* @return true 验证成功 false 验证失败
*/
public boolean validateSign(String signfile) {
// 读取公匙
PublicKey mypubkey = (PublicKey) getObjFromFile(signfile, 2);
// 读取签名
byte[] signed = (byte[]) getObjFromFile(signfile, 1);
// 读取信息
String info = (String) getObjFromFile(signfile, 3);
try {
// 初始一个Signature对象,并用公钥和签名进行验证
Signature signetcheck = Signature.getInstance("DSA");
// 初始化验证签名的公钥
signetcheck.initVerify(mypubkey);
// 使用指定的 byte 数组更新要签名或验证的数据
signetcheck.update(info.getBytes());
System.out.println(info);
// 验证传入的签名
return signetcheck.verify(signed);
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 将二进制转化为16进制字符串
*
* @param b 二进制字节数组
* @return String
*/
public String byte2hex(byte[] b) {
String hs = "";
String stmp = "";
for (int n = 0; n < b.length; n++) {
stmp = (java.lang.Integer.toHexString(b[n] & 0XFF));
if (stmp.length() == 1) {
hs = hs + "0" + stmp;
} else {
hs = hs + stmp;
}
}
return hs.toUpperCase();
}
/**
* 十六进制字符串转化为2进制
*
* @param hex
* @return
*/
public byte[] hex2byte(String hex) {
byte[] ret = new byte[8];
byte[] tmp = hex.getBytes();
for (int i = 0; i < 8; i++) {
ret[i] = uniteBytes(tmp[i * 2], tmp[i * 2 + 1]);
}
return ret;
}
/**
* 将两个ASCII字符合成一个字节; 如:"EF"-- 0xEF
*
* @param src0 byte
* @param src1 byte
* @return byte
*/
public static byte uniteBytes(byte src0, byte src1) {
byte _b0 = Byte.decode("0x" + new String(new byte[] { src0 }))
.byteValue();
_b0 = (byte) (_b0 << 4);
byte _b1 = Byte.decode("0x" + new String(new byte[] { src1 }))
.byteValue();
byte ret = (byte) (_b0 ^ _b1);
return ret;
}
/**
* 将指定的对象写入指定的文件
*
* @param file 指定写入的文件
* @param objs 要写入的对象
*/
public void doObjToFile(String file, Object[] objs) {
ObjectOutputStream oos = null;
try {
FileOutputStream fos = new FileOutputStream(file);
oos = new ObjectOutputStream(fos);
for (int i = 0; i < objs.length; i++) {
oos.writeObject(objs[i]);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
oos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 返回在文件中指定位置的对象
*
* @param file 指定的文件
* @param i 从1开始
* @return
*/
public Object getObjFromFile(String file, int i) {
ObjectInputStream ois = null;
Object obj = null;
try {
FileInputStream fis = new FileInputStream(file);
ois = new ObjectInputStream(fis);
for (int j = 0; j < i; j++) {
obj = ois.readObject();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
ois.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return obj;
}
/**
* 测试
*
* @param args
*/
public static void main(String[] args) {
CryptTest jiami = new CryptTest();
// 执行MD5加密"Hello world!"
System.out.println("Hello经过MD5:" + jiami.encryptToMD5("Hello"));
// 生成一个DES算法的密匙
SecretKey key = jiami.createSecretKey("DES");
// 用密匙加密信息"Hello world!"
String str1 = jiami.encryptToDES(key, "Hello");
System.out.println("使用des加密信息Hello为:" + str1);
// 使用这个密匙解密
String str2 = jiami.decryptByDES(key, str1);
System.out.println("解密后为:" + str2);
// 创建公匙和私匙
jiami.createPairKey();
// 对Hello world!使用私匙进行签名
jiami.signToInfo("Hello", "mysign.bat");
// 利用公匙对签名进行验证。
if (jiami.validateSign("mysign.bat")) {
System.out.println("Success!");
} else {
System.out.println("Fail!");
}
}
}
Java中 DES加密算法
三个文件: 一:skey_DES.java
//对称秘钥生成及对象化保存
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
public class Skey_DES {
public static void main(String args[]) throws Exception {
KeyGenerator kg = KeyGenerator.getInstance("DESede");
kg.init(168);
SecretKey k = kg.generateKey();
FileOutputStream f = new FileOutputStream("key1.txt");
ObjectOutputStream b = new ObjectOutputStream(f);
b.writeObject(k);
}
};
二:SEnc.java
//对称秘钥加密,使用字节码
import java.io.*;
import java.security.*;
import javax.crypto.*;
public class SEnc {
public static void main(String args[]) throws Exception {
String s = "Hello123Hello123Hello123Hello123";
FileInputStream f = new FileInputStream("key1.txt");
ObjectInputStream b = new ObjectInputStream(f);
Key k = (Key) b.readObject();
Cipher cp = Cipher.getInstance("DESede");
cp.init(Cipher.ENCRYPT_MODE, k);
byte ptext[] = s.getBytes("UTF8");
for (int i = 0; i < ptext.length; i++) {
System.out.print(ptext[i] + ",");
}
System.out.println("");
byte ctext[] = cp.doFinal(ptext);
for (int i = 0; i < ctext.length; i++) {
System.out.print(ctext[i] + ",");
}
FileOutputStream f2 = new FileOutputStream("SEnc.txt");
f2.write(ctext);
}
};
三:SDec.java
//使用对称秘钥解密
import java.io.*;
import java.security.*;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
public class SDec {
public static void main(String args[]) throws Exception {
FileInputStream f = new FileInputStream("SEnc.txt");
int num = f.available();
byte[] ctext = new byte[num];
f.read(ctext);
FileInputStream f2 = new FileInputStream("key1.txt");
ObjectInputStream b = new ObjectInputStream(f2);
Key k = (Key) b.readObject();
Cipher cp = Cipher.getInstance("DESede");
cp.init(Cipher.DECRYPT_MODE, k);
byte[] ptext = cp.doFinal(ctext);
String p = new String(ptext, "UTF8");
System.out.println(p);
}
};
如何利用DES加密的算法保护Java源代码
Java语言是一种非常适用于网络编程的语言,它的基本结构与C极为相似,但抛弃了C/C中指针等内容,同时它吸收了Smalltalk、C++面向对象的编程思想。它具有简单性、鲁棒性、可移植性、动态性等特点。这些特点使得Java成为跨平台应用开发的一种规范,在世界范围内广泛流传。 加密Java源码的原因 Java源代码经过编译以后在JVM中执行。由于JVM界面是完全透明的,Java类文件能够很容易通过反编译器重新转换成源代码。因此,所有的算法、类文件等都可以以源代码的形式被公开,使得软件不能受到保护,为了保护产权,一般可以有以下几种方法:
- "模糊"类文件,加大反编译器反编译源代码文件的难度。然而,可以修改反编译器,使之能够处理这些模糊类文件。所以仅仅依赖"模糊类文件"来保证代码的安全是不够的。
- 流行的加密工具对源文件进行加密,比如PGP(Pretty Good Privacy)或GPG(GNU Privacy Guard)。这时,最终用户在运行应用之前必须先进行解密。但解密之后,最终用户就有了一份不加密的类文件,这和事先不进行加密没有什么差别。
- 加密类文件,在运行中JVM用定制的类装载器(Class Loader)解密类文件。Java运行时装入字节码的机制隐含地意味着可以对字节码进行修改。JVM每次装入类文件时都需要一个称为ClassLoader的对象,这个对象负责把新的类装入正在运行的JVM。JVM给ClassLoader一个包含了待装入类(例如java.lang.Object)名字的字符串,然后由ClassLoader负责找到类文件,装入原始数据,并把它转换成一个Class对象。 用户下载的是加密过的类文件,在加密类文件装入之时进行解密,因此可以看成是一种即时解密器。由于解密后的字节码文件永远不会保存到文件系统,所以窃密者很难得到解密后的代码。 Java密码体系和Java密码扩展 Java密码体系(JCA)和Java密码扩展(JCE)的设计目的是为Java提供与实现无关的加密函数API。它们都用factory方法来创建类的例程,然后把实际的加密函数委托给提供者指定的底层引擎,引擎中为类提供了服务提供者接口在Java中实现数据的加密/解密,是使用其内置的JCE(Java加密扩展)来实现的。Java开发工具集1.1为实现包括数字签名和信息摘要在内的加密功能,推出了一种基于供应商的新型灵活应用编程接口。Java密码体系结构支持供应商的互操作,同时支持硬件和软件实现。 Java密码学结构设计遵循两个原则:
- 算法的独立性和可靠性。
- 实现的独立性和相互作用性。 算法的独立性是通过定义密码服务类来获得。用户只需了解密码算法的概念,而不用去关心如何实现这些概念。实现的独立性和相互作用性通过密码服务提供器来实现。密码服务提供器是实现一个或多个密码服务的一个或多个程序包。软件开发商根据一定接口,将各种算法实现后,打包成一个提供器,用户可以安装不同的提供器。安装和配置提供器,可将包含提供器的ZIP和JAR文件放在CLASSPATH下,再编辑Java安全属性文件来设置定义一个提供器。Java运行环境Sun版本时, 提供一个缺省的提供器Sun。 下面介绍DES算法及如何利用DES算法加密和解密类文件的步骤。 DES算法简介 DES(Data Encryption Standard)是发明最早的最广泛使用的分组对称加密算法。DES算法的入口参数有三个:Key、Data、Mode。
用java实现DES加密算法,细致点,要直接粘贴进平台能运行的!!
/*des密钥生成代码*/
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import com.huateng.util.common.Log;
public class GenKey {
private static final String DES = "DES";
public static final String SKEY_NAME = "key.des";
public static void genKey1(String path) {
// 密钥
SecretKey skey = null;
// 密钥随机数生成
SecureRandom sr = new SecureRandom();
//生成密钥文件
File file = genFile(path);
try {
// 获取密钥生成实例
KeyGenerator gen = KeyGenerator.getInstance(DES);
// 初始化密钥生成器
gen.init(sr);
// 生成密钥
skey = gen.generateKey();
// System.out.println(skey);
ObjectOutputStream oos = new ObjectOutputStream(
new FileOutputStream(file));
oos.writeObject(skey);
oos.close();
Log.sKeyPath(path);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* @param file : 生成密钥的路径
* SecretKeyFactory 方式生成des密钥
* */
public static void genKey2(String path) {
// 密钥随机数生成
SecureRandom sr = new SecureRandom();
// byte[] bytes = {11,12,44,99,76,45,1,8};
byte[] bytes = sr.generateSeed(20);
// 密钥
SecretKey skey = null;
//生成密钥文件路径
File file = genFile(path);
try {
//创建deskeyspec对象
DESKeySpec desKeySpec = new DESKeySpec(bytes,9);
//实例化des密钥工厂
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
//生成密钥对象
skey = keyFactory.generateSecret(desKeySpec);
//写出密钥对象
ObjectOutputStream oos = new ObjectOutputStream(
new FileOutputStream(file));
oos.writeObject(skey);
oos.close();
Log.sKeyPath(path);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (InvalidKeySpecException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private static File genFile(String path) {
String temp = null;
File newFile = null;
if (path.endsWith("/") || path.endsWith("\\")) {
temp = path;
} else {
temp = path + "/";
}
File pathFile = new File(temp);
if (!pathFile.exists())
pathFile.mkdirs();
newFile = new File(temp + SKEY_NAME);
return newFile;
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
genKey2("E:/a/aa/");
}
}
/*加解密*/
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.SecretKey;
public class SecUtil {
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);
}
}
}
DES加密算法 java实现
package des;
import java.io.*;
import java.nio.*;
import java.nio.channels.FileChannel;
public class FileDES {
private static final boolean enc = true; //加密
private static final boolean dec = false; //解密
private String srcFileName;
private String destFileName;
private String inKey;
private boolean actionType;
private File srcFile;
private File destFile;
private Des des;
private void analyzePath() {
String dirName;
int pos = srcFileName.lastIndexOf("/");
dirName = srcFileName.substring(0, pos);
File dir = new File(dirName);
if (!dir.exists()) {
System.err.println(dirName + " is not exist");
System.exit(1);
} else if (!dir.isDirectory()) {
System.err.println(dirName + " is not a directory");
System.exit(1);
}
pos = destFileName.lastIndexOf("/");
dirName = destFileName.substring(0, pos);
dir = new File(dirName);
if (!dir.exists()) {
if (!dir.mkdirs()) {
System.out.println("can not creat directory:" + dirName);
System.exit(1);
}
} else if (!dir.isDirectory()) {
System.err.println(dirName + " is not a directory");
System.exit(1);
}
}
private static int replenish(FileChannel channel, ByteBuffer buf) throws IOException {
long byteLeft = channel.size() - channel.position();
if (byteLeft == 0L)
return -1;
buf.position(0);
buf.limit(buf.position() + (byteLeft < 8 ? (int) byteLeft : 8));
return channel.read(buf);
}
private void file_operate(boolean flag) {
des = new Des(inKey);
FileOutputStream outputFile = null;
try {
outputFile = new FileOutputStream(srcFile, true);
} catch (java.io.FileNotFoundException e) {
e.printStackTrace(System.err);
}
FileChannel outChannel = outputFile.getChannel();
try {
if (outChannel.size() % 2 != 0) {
ByteBuffer bufTemp = ByteBuffer.allocate(1);
bufTemp.put((byte) 32);
bufTemp.flip();
outChannel.position(outChannel.size());
outChannel.write(bufTemp);
bufTemp.clear();
}
} catch (Exception ex) {
ex.printStackTrace(System.err);
System.exit(1);
}
FileInputStream inFile = null;
try {
inFile = new FileInputStream(srcFile);
} catch (java.io.FileNotFoundException e) {
e.printStackTrace(System.err);
//System.exit(1);
}
outputFile = null;
try {
outputFile = new FileOutputStream(destFile, true);
} catch (java.io.FileNotFoundException e) {
e.printStackTrace(System.err);
}
FileChannel inChannel = inFile.getChannel();
FileChannel outChannel = outputFile.getChannel();
ByteBuffer inBuf = ByteBuffer.allocate(8);
ByteBuffer outBuf = ByteBuffer.allocate(8);
try {
String srcStr;
String destStr;
while (true) {
if (replenish(inChannel, inBuf) == -1) break;
srcStr = ((ByteBuffer) (inBuf.flip())).asCharBuffer().toString();
inBuf.clear();
if (flag)
destStr = des.enc(srcStr, srcStr.length());
else
destStr = des.dec(srcStr, srcStr.length());
outBuf.clear();
if (destStr.length() == 4) {
for (int i = 0; i < 4; i++) {
outBuf.putChar(destStr.charAt(i));
}
outBuf.flip();
} else {
outBuf.position(0);
outBuf.limit(2 * destStr.length());
for (int i = 0; i < destStr.length(); i++) {
outBuf.putChar(destStr.charAt(i));
}
outBuf.flip();
}
try {
outChannel.write(outBuf);
outBuf.clear();
} catch (java.io.IOException ex) {
ex.printStackTrace(System.err);
}
}
System.out.println(inChannel.size());
System.out.println(outChannel.size());
System.out.println("EoF reached.");
inFile.close();
outputFile.close();
} catch (java.io.IOException e) {
e.printStackTrace(System.err);
System.exit(1);
}
}
public FileDES(String srcFileName, String destFileName, String inKey, boolean actionType) {
this.srcFileName = srcFileName;
this.destFileName = destFileName;
this.actionType = actionType;
analyzePath();
srcFile = new File(srcFileName);
destFile = new File(destFileName);
this.inKey = inKey;
if (actionType == enc)
file_operate(enc);
else
file_operate(dec);
}
public static void main(String[] args) {
String file1 = System.getProperty("user.dir") + "/111.doc";
String file2 = System.getProperty("user.dir") + "/222.doc";
String file3 = System.getProperty("user.dir") + "/333.doc";
String passWord = "1234ABCD";
FileDES fileDes = new FileDES(file1, file2, passWord, true);
FileDES fileDes1 = new FileDES(file2, file3, passWord, false);
}
}
求用JAVA实现的DES算法
package des;
import java.io.*;
import java.nio.*;
import java.nio.channels.FileChannel;
public class FileDES {
private static final boolean enc = true; //加密
private static final boolean dec = false; //解密
private String srcFileName;
private String destFileName;
private String inKey;
private boolean actionType;
private File srcFile;
private File destFile;
private Des des;
private void analyzePath() {
String dirName;
int pos = srcFileName.lastIndexOf("/");
dirName = srcFileName.substring(0, pos);
File dir = new File(dirName);
if (!dir.exists()) {
System.err.println(dirName + " is not exist");
System.exit(1);
} else if (!dir.isDirectory()) {
System.err.println(dirName + " is not a directory");
System.exit(1);
}
pos = destFileName.lastIndexOf("/");
dirName = destFileName.substring(0, pos);
dir = new File(dirName);
if (!dir.exists()) {
if (!dir.mkdirs()) {
System.out.println("can not creat directory:" + dirName);
System.exit(1);
}
} else if (!dir.isDirectory()) {
System.err.println(dirName + " is not a directory");
System.exit(1);
}
}
private static int replenish(FileChannel channel, ByteBuffer buf) throws IOException {
long byteLeft = channel.size() - channel.position();
if (byteLeft == 0L)
return -1;
buf.position(0);
buf.limit(buf.position() + (byteLeft < 8 ? (int) byteLeft : 8));
return channel.read(buf);
}
private void file_operate(boolean flag) {
des = new Des(inKey);
FileOutputStream outputFile = null;
try {
outputFile = new FileOutputStream(srcFile, true);
} catch (java.io.FileNotFoundException e) {
e.printStackTrace(System.err);
}
FileChannel outChannel = outputFile.getChannel();
try {
if (outChannel.size() % 2 != 0) {
ByteBuffer bufTemp = ByteBuffer.allocate(1);
bufTemp.put((byte) 32);
bufTemp.flip();
outChannel.position(outChannel.size());
outChannel.write(bufTemp);
bufTemp.clear();
}
} catch (Exception ex) {
ex.printStackTrace(System.err);
System.exit(1);
}
FileInputStream inFile = null;
try {
inFile = new FileInputStream(srcFile);
} catch (java.io.FileNotFoundException e) {
e.printStackTrace(System.err);
//System.exit(1);
}
outputFile = null;
try {
outputFile = new FileOutputStream(destFile, true);
} catch (java.io.FileNotFoundException e) {
e.printStackTrace(System.err);
}
FileChannel inChannel = inFile.getChannel();
FileChannel outChannel = outputFile.getChannel();
ByteBuffer inBuf = ByteBuffer.allocate(8);
ByteBuffer outBuf = ByteBuffer.allocate(8);
try {
String srcStr;
String destStr;
while (true) {
if (replenish(inChannel, inBuf) == -1) break;
srcStr = ((ByteBuffer) (inBuf.flip())).asCharBuffer().toString();
inBuf.clear();
if (flag)
destStr = des.enc(srcStr, srcStr.length());
else
destStr = des.dec(srcStr, srcStr.length());
outBuf.clear();
if (destStr.length() == 4) {
for (int i = 0; i < 4; i++) {
outBuf.putChar(destStr.charAt(i));
}
outBuf.flip();
} else {
outBuf.position(0);
outBuf.limit(2 * destStr.length());
for (int i = 0; i < destStr.length(); i++) {
outBuf.putChar(destStr.charAt(i));
}
outBuf.flip();
}
try {
outChannel.write(outBuf);
outBuf.clear();
} catch (java.io.IOException ex) {
ex.printStackTrace(System.err);
}
}
System.out.println(inChannel.size());
System.out.println(outChannel.size());
System.out.println("EoF reached.");
inFile.close();
outputFile.close();
} catch (java.io.IOException e) {
e.printStackTrace(System.err);
System.exit(1);
}
}
public FileDES(String srcFileName, String destFileName, String inKey, boolean actionType) {
this.srcFileName = srcFileName;
this.destFileName = destFileName;
this.actionType = actionType;
analyzePath();
srcFile = new File(srcFileName);
destFile = new File(destFileName);
this.inKey = inKey;
if (actionType == enc)
file_operate(enc);
else
file_operate(dec);
}
public static void main(String[] args) {
String file1 = System.getProperty("user.dir") + "/111.doc";
String file2 = System.getProperty("user.dir") + "/222.doc";
String file3 = System.getProperty("user.dir") + "/333.doc";
String passWord = "1234ABCD";
FileDES fileDes = new FileDES(file1, file2, passWord, true);
FileDES fileDes1 = new FileDES(file2, file3, passWord, false);
}
}