金币系统后端
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.

104 lines
2.4 KiB

  1. package com.example.demo.Util;
  2. import javax.crypto.Cipher;
  3. import java.security.*;
  4. import static org.apache.poi.poifs.crypt.CipherAlgorithm.des;
  5. public class BaseDES {
  6. private static String strDefaultKey = "98hltleg";
  7. private Cipher encryptCipher = null;
  8. private Cipher decryptCipher = null;
  9. public static String byteArr2HexStr(byte[] arrB) throws Exception {
  10. int iLen = arrB.length;
  11. StringBuffer sb = new StringBuffer(iLen * 2);
  12. for (int i = 0; i < iLen; i++) {
  13. int intTmp = arrB[i];
  14. while (intTmp < 0) {
  15. intTmp = intTmp + 256;
  16. }
  17. if (intTmp < 16) {
  18. sb.append("0");
  19. }
  20. sb.append(Integer.toString(intTmp, 16));
  21. }
  22. return sb.toString();
  23. }
  24. public static byte[] hexStr2ByteArr(String strIn) {
  25. byte[] arrB = strIn.getBytes();
  26. int iLen = arrB.length;
  27. byte[] arrOut = new byte[iLen / 2];
  28. for (int i = 0; i < iLen; i = i + 2) {
  29. String strTmp = new String(arrB, i, 2);
  30. arrOut[i / 2] = (byte) Integer.parseInt(strTmp, 16);
  31. }
  32. return arrOut;
  33. }
  34. public BaseDES() throws Exception {
  35. this(strDefaultKey);
  36. }
  37. public BaseDES(String strKey) throws Exception {
  38. Key key = getKey(strKey.getBytes());
  39. encryptCipher = Cipher.getInstance("DES");
  40. encryptCipher.init(Cipher.ENCRYPT_MODE, key);
  41. decryptCipher = Cipher.getInstance("DES");
  42. decryptCipher.init(Cipher.DECRYPT_MODE, key);
  43. }
  44. public byte[] encrypt(byte[] arrB) throws Exception {
  45. return encryptCipher.doFinal(arrB);
  46. }
  47. public String encrypt(String strIn) throws Exception {
  48. return byteArr2HexStr(encrypt(strIn.getBytes()));
  49. }
  50. public byte[] decrypt(byte[] arrB) throws Exception {
  51. return decryptCipher.doFinal(arrB);
  52. }
  53. public String decrypt(String strIn) throws Exception {
  54. return new String(decrypt(hexStr2ByteArr(strIn)));
  55. }
  56. private Key getKey(byte[] arrBTmp) {
  57. byte[] arrB = new byte[8];
  58. for (int i = 0; i < arrBTmp.length && i < arrB.length; i++) {
  59. arrB[i] = arrBTmp[i];
  60. }
  61. Key key = new javax.crypto.spec.SecretKeySpec(arrB, "DES");
  62. return key;
  63. }
  64. public static void main(String args[]) {
  65. try {
  66. BaseDES d = new BaseDES();
  67. String encryptedText = d.encrypt("94615273");
  68. System.out.println("加密结果:" + encryptedText);
  69. System.out.println("加密字符串:90005179》"+d.encrypt("90005179"));
  70. System.out.println("解密字符串:6aaef5277c050f7ae383f816651098ff》"+d.decrypt("6aaef5277c050f7ae383f816651098ff"));
  71. } catch (Exception e) {
  72. e.printStackTrace();
  73. }
  74. }
  75. }