package com.test;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
public class des3_24 {
/**
* @throws Exception
* @功能:测试用例
* @参数: 参数
*/
public static void main(String[] args) throws Exception {
String key = "123456789000000000000000";
String str = "{}";
System.out.println("随机key-----------> " + key);
String encrypt3DES = encrypt3DES(str,key);
System.out.println("加密-----------> " + encrypt3DES);
String decrypt3DES = decrypt3DES(encrypt3DES,key);
System.out.println("解密-----------> " + decrypt3DES);
}
/**
* 3DES加密
*
* @param data
* @return
* @throws Exception
*/
public static String encrypt3DES(String data,String key) throws Exception {
//加密
byte key_byte[] = key.getBytes();
SecretKey secretKey = new SecretKeySpec(key_byte, "DESede");
Cipher cipher = Cipher.getInstance("DESede/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] bytes = cipher.doFinal(data.getBytes("utf-8"));
String str =bytesToHexString(bytes);
return str;
}
/**
* 3DES解密
*
* @param data
* @return
* @throws Exception
*/
public static String decrypt3DES(String data,String key) throws Exception {
//解密
byte key_byte[] = key.getBytes();
SecretKey secretKey = new SecretKeySpec(key_byte, "DESede");
Cipher cipher = Cipher.getInstance("DESede/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, secretKey);
byte[] bytes = cipher.doFinal(hexStringToBytes(data));
return new String(bytes, "UTF-8");
}
public static String bytesToHexString(byte[] bytes) {
StringBuilder stringBuilder = new StringBuilder();
if (bytes != null && bytes.length > 0) {
byte[] arg1 = bytes;
int arg2 = bytes.length;
for (int arg3 = 0; arg3 < arg2; ++arg3) {
byte b = arg1[arg3];
int v = b & 255;
String hv = Integer.toHexString(v);
if (hv.length() < 2) {
stringBuilder.append(0);
}
stringBuilder.append(hv);
}
return stringBuilder.toString().toUpperCase();
} else {
return "";
}
}
public static byte[] hexStringToBytes(String hexString) {
if (hexString != null && !"".equals(hexString)) {
hexString = hexString.toUpperCase();
int length = hexString.length() / 2;
char[] hexChars = hexString.toCharArray();
byte[] d = new byte[length];
for (int i = 0; i < length; ++i) {
int pos = i * 2;
d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
}
return d;
} else {
return null;
}
}
private static byte charToByte(char c) {
return (byte) "0123456789ABCDEF".indexOf(c);
}
}