DES加密工具类封装
import java.security.Key;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
public class EncrypDES {
private static String strDefaultKey = "inventec2020@#$%^&";
private Cipher encryptCipher;
private Cipher decryptCipher;
public EncrypDES() throws Exception {
this(strDefaultKey);
}
public EncrypDES(String strKey) throws Exception {
this.encryptCipher = null;
this.decryptCipher = null;
Key key = this.getKey(strKey.getBytes());
//以DES加密算法创建加密解密对象Cipher
this.encryptCipher = Cipher.getInstance("DES");
//初始化,以密钥规则key和加密模式进行初始化
this.encryptCipher.init(1, key);
//以DES加密算法创建加密解密对象Cipher
this.decryptCipher = Cipher.getInstance("DES");
//密钥规则key和解析模式进行初始化
this.decryptCipher.init(2, key);
}
//将byte数组转换为表示16进制值的字符串, 如:byte[]{8,18}转换为:0813
//和public static byte[] hexStr2ByteArr(String strIn) 互为可逆的转换过程
public static String byteArr2HexStr(byte[] arrB) throws Exception {
int iLen = arrB.length;
//每个byte用两个字符才能表示,所以字符串的长度是数组长度的两倍
StringBuffer sb = new StringBuffer(iLen * 2);
for(int i = 0; i < iLen; ++i) {
int intTmp;
//把负数转为正数
for(intTmp = arrB[i]; intTmp < 0; intTmp += 256) {
}
//小于0F的数需要在前面补0
if (intTmp < 16) {
sb.append("0");
}
sb.append(Integer.toString(intTmp, 16));
}
return sb.toString();
}
//将表示16进制的字符串转换为byte数组 和public static String byteArr2HexStr(byte[] arrB)互为可逆的转换过程
public static byte[] hexStr2ByteArr(String strIn) throws Exception {
//将字符串转为byte数组
byte[] arrB = strIn.getBytes();
//获取长度
int iLen = arrB.length;
//两个字符表示一个字节,所以字节数组长度是字符串长度除以2
byte[] arrOut = new byte[iLen / 2];
for(int i = 0; i < iLen; i += 2) {
String strTmp = new String(arrB, i, 2);
arrOut[i / 2] = (byte)Integer.parseInt(strTmp, 16);
}
return arrOut;
}
//加密字节数组
public byte[] encrypt(byte[] arrB) throws Exception {
return this.encryptCipher.doFinal(arrB);
}
//先将字符串以byte数组进行加密再转为16进制字符串
public String encrypt(String strIn) throws Exception {
return byteArr2HexStr(this.encrypt(strIn.getBytes()));
}
//解密字节数组
public byte[] decrypt(byte[] arrB) throws Exception {
return this.decryptCipher.doFinal(arrB);
}
//先将字符串转为字节数组再进行解密
public String decrypt(String strIn) throws Exception {
return new String(this.decrypt(hexStr2ByteArr(strIn)));
}
//从指定字符串生成密钥,密钥所需的字节数组长度为8位,不足8位时后面补0,超出8位只取前8位
private Key getKey(byte[] arrBTmp) throws Exception {
byte[] arrB = new byte[8];
for(int i = 0; i < arrBTmp.length && i < arrB.length; ++i) {
arrB[i] = arrBTmp[i];
}
Key key = new SecretKeySpec(arrB, "DES");
return key;
}
}