import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import java.nio.charset.Charset;
import java.security.SecureRandom;
/**
* Des 加解密工具類
*
* @author muraty
* @since 2019-05-29
*/
public class DesUtil {
private static final String DES = "DES";
private static final Charset CHARSET = Charset.forName("UTF8");
/**
* 加密
*
* @param src 明文
* @param key 公匙
* @return 密文
*/
public static String encrypt(String src, String key) {
byte[] s = src.getBytes(CHARSET);
byte[] buf = des(s, key, Cipher.ENCRYPT_MODE);
return parseByte2HexStr(buf);
}
/**
* 解密
*
* @param data 密文
* @param key 公鑰
* @return 明文
*/
public static String decrypt(String data, String key) {
byte[] d = parseHexStr2Byte(data);
byte[] buf = des(d, key, Cipher.DECRYPT_MODE);
return new String(buf, CHARSET);
}
/**
* 將二進制轉換成16進制
*/
private static String parseByte2HexStr(byte[] buf) {
StringBuilder sb = new StringBuilder();
for (byte b : buf) {
String hex = Integer.toHexString(b & 0xFF);
if (hex.length() == 1) {
hex = '0' + hex;
}
sb.append(hex.toUpperCase());
}
return sb.toString();
}
/**
* 將16進制轉換爲二進制
*/
private static byte[] parseHexStr2Byte(String hexStr) {
if (hexStr.length() < 1) {
return null;
}
byte[] result = new byte[hexStr.length() / 2];
for (int i = 0; i < hexStr.length() / 2; i++) {
int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16);
result[i] = (byte) (high * 16 + low);
}
return result;
}
/**
* DES 加/解密 核心
*/
private static byte[] des(byte[] src, String key, int mode) {
try {
byte[] k = key.getBytes();
// DES算法要求有一個可信任的隨機數源
SecureRandom random = new SecureRandom();
// 創建一個DESKeySpec對象
DESKeySpec desKey = new DESKeySpec(k);
// 創建一個密匙工廠
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
// 將DESKeySpec對象轉換成SecretKey對象
SecretKey secureKey = keyFactory.generateSecret(desKey);
// Cipher對象實際完成解密操作
Cipher cipher = Cipher.getInstance(DES);
// 用密匙初始化Cipher對象
cipher.init(mode, secureKey, random);
// 真正開始解密操作
return cipher.doFinal(src);
} catch (Throwable e) {
e.printStackTrace();
}
return null;
}
}
public class MainApp {
private static final String KEY = "983F0495B28B46DA9F7500D4E69FFC8F";
public static void main(String[] args) {
// 明文
String s = "中文,English,¢€£∞";
// 加密
String data = DesUtil.encrypt(s, KEY);
// 解密
String result = DesUtil.decrypt(data, KEY);
System.out.println("公鑰: " + KEY);
System.out.println("明文: " + s);
System.out.println("密文: " + data);
System.out.println("解密: " + result);
}
}