import java.security.Key;
import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.swing.*;
public class DesEncrypt {
Key key;
public void getKey(String strKey) {
try {
KeyGenerator _generator = KeyGenerator.getInstance("DES");
_generator.init(new SecureRandom(strKey.getBytes()));// 此构造方法使用了一种用户提供的种子,它优先于在空构造方法描述中所提到的自供种子算法。
this.key = _generator.generateKey();
_generator = null;
} catch (Exception e) {
e.printStackTrace();
}
}
public String getEncString(String strMing) {
byte[] byteMi = null;
byte[] byteMing = null;
String strMi = "";
try {
return byte2hex(getEncCode(strMing.getBytes()));
} catch (Exception e) {
e.printStackTrace();
} finally {
byteMing = null;
byteMi = null;
}
return strMi;
}
public String getDesString(String strMi) {
byte[] byteMing = null;
byte[] byteMi = null;
String strMing = "";
try {
return new String(getDesCode(hex2byte(strMi.getBytes())));
} catch (Exception e) {
e.printStackTrace();
} finally {
byteMing = null;
byteMi = null;
}
return strMing;
}
private byte[] getEncCode(byte[] byteS) {
byte[] byteFina = null;
Cipher cipher;// 供了针对加密和解密的密码 cipher 功能。它构成了 Java Cryptographic
// Extension (JCE) 框架的核心
try {
cipher = Cipher.getInstance("DES");
cipher.init(Cipher.ENCRYPT_MODE, key);// 4 种操作之一初始化该
// cipher:加密、解密、密钥包装或密钥打开
byteFina = cipher.doFinal(byteS);// 结束时,此方法将把此 cipher 对象重置为上一次调用
// init
// 初始化得到的状态。即重置该对象,可供加密或解密(取决于调用
// init 时指定的操作模式)更多的数据
} catch (Exception e) {
e.printStackTrace();
} finally {
cipher = null;
}
return byteFina;
}
private byte[] getDesCode(byte[] byteD) {
Cipher cipher;
byte[] byteFina = null;
try {
cipher = Cipher.getInstance("DES");
cipher.init(Cipher.DECRYPT_MODE, key);
byteFina = cipher.doFinal(byteD);// 处理 input 缓冲区中的字节以及可能在上一次
// update
// 操作中已缓存的任何输入字节,其中应用了填充(如果请求)。结果存储在新缓冲区中
} catch (Exception e) {
e.printStackTrace();
} finally {
cipher = null;
}
return byteFina;
}
public static String byte2hex(byte[] b) { // 一个字节的数,
// 转成16进制字符串
String hs = "";
String stmp = "";
for (int n = 0; n < b.length; n++) {
// 整数转成十六进制表示
stmp = (java.lang.Integer.toHexString(b[n] & 0XFF));
if (stmp.length() == 1)
hs = hs + "0" + stmp;
else
hs = hs + stmp;
}
return hs.toUpperCase(); // 转成大写
}
public static byte[] hex2byte(byte[] b) {
if ((b.length % 2) != 0)
throw new IllegalArgumentException("长度不是偶数");
byte[] b2 = new byte[b.length / 2];
for (int n = 0; n < b.length; n += 2) {
String item = new String(b, n, 2);
// 两位一组,表示一个字节,把这样表示的16进制字符串,还原成一个进制字节
b2[n / 2] = (byte) Integer.parseInt(item, 16);
}
return b2;
}
}