You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

107 lines
2.4 KiB

  1. package com.example.demo.Util;
  2. import javax.crypto.Cipher;
  3. import java.security.Key;
  4. public class DESGB {
  5. private static String strDefaultKey = "testhlsoft";
  6. private Cipher encryptCipher = null;
  7. private Cipher decryptCipher = null;
  8. public static String byteArr2HexStr(byte[] arrB) throws Exception {
  9. int iLen = arrB.length;
  10. StringBuffer sb = new StringBuffer(iLen * 2);
  11. for (int i = 0; i < iLen; i++) {
  12. int intTmp = arrB[i];
  13. while (intTmp < 0) {
  14. intTmp = intTmp + 256;
  15. }
  16. if (intTmp < 16) {
  17. sb.append("0");
  18. }
  19. sb.append(Integer.toString(intTmp, 16));
  20. }
  21. return sb.toString();
  22. }
  23. public static byte[] hexStr2ByteArr(String strIn) throws Exception {
  24. byte[] arrB = strIn.getBytes();
  25. int iLen = arrB.length;
  26. byte[] arrOut = new byte[iLen / 2];
  27. for (int i = 0; i < iLen; i = i + 2) {
  28. String strTmp = new String(arrB, i, 2);
  29. arrOut[i / 2] = (byte) Integer.parseInt(strTmp, 16);
  30. }
  31. return arrOut;
  32. }
  33. public DESGB() throws Exception {
  34. this(strDefaultKey);
  35. }
  36. public DESGB(String strKey) throws Exception {
  37. Key key = getKey(strKey.getBytes());
  38. encryptCipher = Cipher.getInstance("DES");
  39. encryptCipher.init(Cipher.ENCRYPT_MODE, key);
  40. decryptCipher = Cipher.getInstance("DES");
  41. decryptCipher.init(Cipher.DECRYPT_MODE, key);
  42. }
  43. public byte[] encrypt(byte[] arrB) throws Exception {
  44. return encryptCipher.doFinal(arrB);
  45. }
  46. public String encrypt(String strIn) throws Exception {
  47. return byteArr2HexStr(encrypt(strIn.getBytes()));
  48. }
  49. public byte[] decrypt(byte[] arrB) throws Exception {
  50. return decryptCipher.doFinal(arrB);
  51. }
  52. /**
  53. * @功能描述: 解决中文乱码问题
  54. * @开发人员: 弘历研发部 刘志红 2024-1-28上午11:27:38 创建
  55. * @参数介绍: @param strIn
  56. * @参数介绍: @return
  57. * @参数介绍: @throws Exception
  58. * @返回数据: String
  59. * @版本编号: V1.0
  60. */
  61. public String decrypt(String strIn) throws Exception {
  62. return new String(decrypt(hexStr2ByteArr(strIn)),"UTF-8");
  63. }
  64. private Key getKey(byte[] arrBTmp) throws Exception {
  65. byte[] arrB = new byte[8];
  66. for (int i = 0; i < arrBTmp.length && i < arrB.length; i++) {
  67. arrB[i] = arrBTmp[i];
  68. }
  69. Key key = new javax.crypto.spec.SecretKeySpec(arrB, "DES");
  70. return key;
  71. }
  72. public static void main(String args[]) {
  73. try {
  74. DESGB d = new DESGB();
  75. System.out.println(d.decrypt("d19f27abb3486c689304600788c604e700abf96d6bd1c9ca"));
  76. } catch (Exception e) {
  77. e.printStackTrace();
  78. }
  79. }
  80. }