package com.ysyc.wsbs.utils.math;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;
import java.io.IOException;
import java.security.SecureRandom;
public class DES {
//加密算法是des
private static final String ALGORITHM = "DES";
//轉換格式
private static final String TRANSFORMATION = "DES/CBC/PKCS5Padding";
/**
* 加密
*
* @param src 數據源
* @param key 密鑰,長度必須是8的倍數
* @return 返回加密后的數據
* @throws Exception 出錯
*/
public static byte[] encrypt(byte[] src, byte[] key) throws Exception {
// DES算法要求有一個可信任的隨機數源
SecureRandom sr = new SecureRandom();
// 從原始密匙數據建立 DESKeySpec對象
DESKeySpec dks = new DESKeySpec(key);
// 建立一個密匙工廠,然后用它把DESKeySpec轉換成
// 一個SecretKey對象
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ALGORITHM);
SecretKey securekey = keyFactory.generateSecret(dks);
// Cipher對象實際完成加密操作
Cipher cipher = Cipher.getInstance(TRANSFORMATION);
// 用密匙原始化Cipher對象
cipher.init(Cipher.ENCRYPT_MODE, securekey, new IvParameterSpec(key));
// 現在,獲取數據並加密
// 正式執行加密操作
return cipher.doFinal(src);
}
/**
* 解密
*
* @param src 數據源
* @param key 密鑰,長度必須是8的倍數
* @return 返回解密后的原始數據
* @throws Exception 出錯
*/
public static byte[] decrypt(byte[] src, byte[] key) throws Exception {
// DES算法要求有一個可信任的隨機數源
SecureRandom sr = new SecureRandom();
// 從原始密匙數據建立一個DESKeySpec對象
DESKeySpec dks = new DESKeySpec(key);
// 建立一個密匙工廠,然后用它把DESKeySpec對象轉換成
// 一個SecretKey對象
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ALGORITHM);
SecretKey securekey = keyFactory.generateSecret(dks);
// Cipher對象實際完成解密操作
Cipher cipher = Cipher.getInstance(TRANSFORMATION);
// 用密匙原始化Cipher對象
cipher.init(Cipher.DECRYPT_MODE, securekey, new IvParameterSpec(key));
// 現在,獲取數據並解密
// 正式執行解密操作
return cipher.doFinal(src);
}
/**
* Description 根據鍵值進行加密
* @param data
* @param key 加密鍵byte數組
* @return
* @throws Exception
*/
public static String encrypt(String data, String key) throws Exception {
byte[] bt = encrypt(data.getBytes("UTF-8"), key.getBytes("UTF-8"));
BASE64Encoder encoder = new BASE64Encoder();
return encoder.encode(bt);
//return new String(Base64.encodeBase64(bt), "UTF-8");
}
/**
* Description 根據鍵值進行解密
* @param data
* @param key 加密鍵byte數組
* @return
* @throws IOException
* @throws Exception
*/
public static String decrypt(String data, String key) throws Exception {
if (data == null)
return null;
//byte[] buf = Base64.decodeBase64(data);
BASE64Decoder decoder = new BASE64Decoder();
byte[] buf = decoder.decodeBuffer(data);
byte[] bt = decrypt(buf,key.getBytes("UTF-8"));
return new String(bt,"UTF-8");
}
public static void main(String[] args) throws Exception{
String key = "12345678";
String jj = "<?xml version=\"1.0\" encoding=\"utf-8\"?><service><business_rerurn></business_rerurn></service>";
String pp = encrypt(jj, key);
System.out.println("加密:" + pp );
String mm2 = decrypt(pp, key);
System.out.println("解密:" + mm2 );
}
}