package org.test;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.security.Key;
import java.security.Security;
import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.CipherOutputStream;
import javax.crypto.KeyGenerator;
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 = "bin\\Order.xml";
//读入并加密文件
try {
//输入流
cipher.init(Cipher.ENCRYPT_MODE, key);
BufferedInputStream in = new BufferedInputStream(new FileInputStream(filename));
//输出流
CipherOutputStream out = new CipherOutputStream(new BufferedOutputStream(new FileOutputStream("bin\\Order_Encryption.xml")), 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");
ey5.printStackTrace();
System.exit(0);
}
try {
cipher.init(Cipher.DECRYPT_MODE, key);
//输出流
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream("bin\\Order_Decryption.xml"));
//输入流
CipherInputStream in = new CipherInputStream(new BufferedInputStream(
new FileInputStream("bin\\Order_Encryption.xml")), 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");
ey5.printStackTrace();
System.exit(0);
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}
评论3
最新资源