import javax.crypto.*;
import javax.crypto.spec.*;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import java.io.IOException;
import java.security.*;
public class DES {
byte[] encryptKey;
DESedeKeySpec spec;
SecretKeyFactory keyFactory;
SecretKey theKey;
Cipher cipher;
IvParameterSpec IvParameters;
public DES() {
try {
// 檢測是否有 TripleDES 加密的供應程式
// 如無,明確地安裝SunJCE 供應程式
try {
Cipher c = Cipher.getInstance("DESede");
} catch (Exception e) {
System.err.println("Installling SunJCE provider.");
Provider sunjce = new com.sun.crypto.provider.SunJCE();
Security.addProvider(sunjce);
} // 建立一個密鑰
encryptKey = "www.unsap.com8yu3ko0d9k3m!".getBytes();
// 為上一密鑰建立一個指定的 DESSede key
spec = new DESedeKeySpec(encryptKey);
// 得到 DESSede keys
keyFactory = SecretKeyFactory.getInstance("DESede");
// 產生一個 DESede 金鑰組象
theKey = keyFactory.generateSecret(spec);
// 建立一個 DESede 密碼
cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
// 為 CBC 模式建立一個用於初始化的 vector 對象
IvParameters = new IvParameterSpec(new byte[] { 12, 34, 56, 78, 90,
87, 65, 43 });
} catch (Exception ex) { // 記錄加密或解密操作錯誤
ex.printStackTrace();
}
}
/**
* 加密方法
* @param data
* @return
*/
public String encrypt(String data) {
String encryptedTxt = null;
try {
// 以加密模式初始化密鑰
cipher.init(Cipher.ENCRYPT_MODE, theKey, IvParameters);
// 加密密碼
byte[] encryptedBytes = cipher.doFinal(data.getBytes());
//密文位元組轉換成字串
encryptedTxt = this.byte2data(encryptedBytes);
} catch (Exception ex) {
ex.printStackTrace();
}
return encryptedTxt;
}
/**
* 位元組數組轉化成編碼字串
* @param bytes
* @return
*/
private String byte2data(byte[] bytes){
BASE64Encoder enc = new BASE64Encoder();
return enc.encode(bytes);
}
/**
* 解密方法
* @param encryptedTxt
* @return
*/
public String decrypt(String encryptedTxt) {
String data = null;
try {
// 以解密模式初始化密鑰
cipher.init(Cipher.DECRYPT_MODE, theKey, IvParameters);
byte[] dataBytes = cipher.doFinal(this.data2byte(encryptedTxt)); // 得到結果
data = new String(dataBytes);
System.out.println("解密得到結果:" + data);
} catch (Exception ex) {
ex.printStackTrace();
}
return data;
}
/**
* 字串通過解碼轉換成位元組數組
* @param data
* @return
* @throws IOException
*/
private byte[] data2byte(String data) throws IOException{
BASE64Decoder dec = new BASE64Decoder();
return dec.decodeBuffer(data);
}
public static void main(String[] asd) throws Exception {
DES one = new DES();
String mima = one.encrypt("qqqewe中國weweweweeeeeqqq");
//
DES two = new DES();
two.decrypt(mima);
// one.test();
}
}