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.

102 lines
2.3 KiB

2 months ago
  1. package com.example.demo.Util;
  2. import javax.crypto.Cipher;
  3. import java.security.Key;
  4. public class BaseDES {
  5. private static String strDefaultKey = "98hltleg";
  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) {
  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 BaseDES() throws Exception {
  34. this(strDefaultKey);
  35. }
  36. public BaseDES(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. public String decrypt(String strIn) throws Exception {
  53. return new String(decrypt(hexStr2ByteArr(strIn)));
  54. }
  55. private Key getKey(byte[] arrBTmp) {
  56. byte[] arrB = new byte[8];
  57. for (int i = 0; i < arrBTmp.length && i < arrB.length; i++) {
  58. arrB[i] = arrBTmp[i];
  59. }
  60. Key key = new javax.crypto.spec.SecretKeySpec(arrB, "DES");
  61. return key;
  62. }
  63. public static void main(String args[]) {
  64. try {
  65. BaseDES d = new BaseDES();
  66. String encryptedText = d.encrypt("94616995");
  67. System.out.println("加密结果:" + encryptedText);
  68. System.out.println("加密字符串:90005179》"+d.encrypt("90005179"));
  69. System.out.println("解密字符串:6aaef5277c050f7ae383f816651098ff》"+d.decrypt("6aaef5277c050f7ae383f816651098ff"));
  70. } catch (Exception e) {
  71. e.printStackTrace();
  72. }
  73. }
  74. }