62,614
社区成员
发帖
与我相关
我的任务
分享
import java.io.*;
import javax.crypto.*;
import java.security.*;
public class DESCryptoTest {
public static void main(String[] args) {
Security.addProvider(new com.sun.crypto.provider.SunJCE());
// Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
KeyGenerator kg = null;
try {
//指定算法,这里为DES;如果想用Blowfish算法,则用 getInstance("Blowfish")
//BouncyCastle基本上支持所有通用标准算法
kg = KeyGenerator.getInstance("DES");
//指定密钥长度,长度越高,加密强度越大
kg.init(56);
//产生密钥
Key key = kg.generateKey();
System.out.println("Key format: " + key.getFormat());
System.out.println("Key algorithm: " + key.getAlgorithm());
//加密要用Cipher来实现
Cipher cipher = Cipher.getInstance("DES");
System.out.println("Cipher provider: " + cipher.getProvider());
System.out.println("Cipher algorithm: " + cipher.getAlgorithm());
byte[] data = "Hello World!".getBytes();
System.out.println("Original data : [" + data.length + "]" +
new String(data));
//设置加密模式
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] result = cipher.doFinal(data);
System.out.println("Encrypted data: [" + result.length + "]" +
new String(result));
//设置解密模式
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] original = cipher.doFinal(result);
System.out.println("Decrypted data: [" + original.length + "]" +
new String(original));
String filename = "d:\\加密前.txt";
//读入并加密文件
try {
//输入流
cipher.init(Cipher.ENCRYPT_MODE, key);
BufferedInputStream in = new BufferedInputStream(new FileInputStream(filename));
//输出流
CipherOutputStream out = new CipherOutputStream(new BufferedOutputStream(new FileOutputStream("d:\\加密后.txt")), cipher);
int i;
do {
i = in.read();
if (i != -1)
out.write(i);
}
while (i != -1);
in.close();
out.close();
System.out.println("加密文件完成!");
}
catch (Exception ey5) {
System.out.println("Error when encrypt the file");
System.exit(0);
}
try {
cipher.init(Cipher.DECRYPT_MODE, key);
//输出流
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream("d:\\解密后.txt"));
//输入流
CipherInputStream in = new CipherInputStream(new BufferedInputStream(
new FileInputStream("d:\\加密后.txt")), cipher);
int i;
do {
i = in.read();
if (i != -1)
out.write(i);
}
while (i != -1);
in.close();
out.close();
System.out.println("解密文件完成!");
}
catch (Exception ey5) {
System.out.println("Error when encrypt the file");
System.exit(0);
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}
修改为:
KeyGenerator _generator = KeyGenerator.getInstance("DES");
Security.addProvider(new sun.security.provider.Sun());
SecureRandom sr = SecureRandom.getInstance("SHA1PRNG","SUN");
sr.setSeed(strKey.getBytes());
generator.init(sr);
this.key = _generator.generateKey();
再把sun的jar包加到classpath即可。