package com.example.demo.Util; import javax.crypto.Cipher; import java.security.Key; public class DESGB { private static String strDefaultKey = "testhlsoft"; private Cipher encryptCipher = null; private Cipher decryptCipher = null; public static String byteArr2HexStr(byte[] arrB) throws Exception { int iLen = arrB.length; StringBuffer sb = new StringBuffer(iLen * 2); for (int i = 0; i < iLen; i++) { int intTmp = arrB[i]; while (intTmp < 0) { intTmp = intTmp + 256; } if (intTmp < 16) { sb.append("0"); } sb.append(Integer.toString(intTmp, 16)); } return sb.toString(); } public static byte[] hexStr2ByteArr(String strIn) throws Exception { byte[] arrB = strIn.getBytes(); int iLen = arrB.length; byte[] arrOut = new byte[iLen / 2]; for (int i = 0; i < iLen; i = i + 2) { String strTmp = new String(arrB, i, 2); arrOut[i / 2] = (byte) Integer.parseInt(strTmp, 16); } return arrOut; } public DESGB() throws Exception { this(strDefaultKey); } public DESGB(String strKey) throws Exception { Key key = getKey(strKey.getBytes()); encryptCipher = Cipher.getInstance("DES"); encryptCipher.init(Cipher.ENCRYPT_MODE, key); decryptCipher = Cipher.getInstance("DES"); decryptCipher.init(Cipher.DECRYPT_MODE, key); } public byte[] encrypt(byte[] arrB) throws Exception { return encryptCipher.doFinal(arrB); } public String encrypt(String strIn) throws Exception { return byteArr2HexStr(encrypt(strIn.getBytes())); } public byte[] decrypt(byte[] arrB) throws Exception { return decryptCipher.doFinal(arrB); } /** * @功能描述: 解决中文乱码问题 * @开发人员: 弘历研发部 刘志红 于 2024-1-28上午11:27:38 创建 * @参数介绍: @param strIn * @参数介绍: @return * @参数介绍: @throws Exception * @返回数据: String * @版本编号: V1.0 */ public String decrypt(String strIn) throws Exception { return new String(decrypt(hexStr2ByteArr(strIn)),"UTF-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 javax.crypto.spec.SecretKeySpec(arrB, "DES"); return key; } public static void main(String args[]) { try { DESGB d = new DESGB(); System.out.println(d.decrypt("d19f27abb3486c689304600788c604e700abf96d6bd1c9ca")); } catch (Exception e) { e.printStackTrace(); } } }