ToolsUtils.java 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665
  1. package com.zhongzheng.common.utils;
  2. import cn.hutool.core.convert.Convert;
  3. import cn.hutool.core.lang.Validator;
  4. import cn.hutool.core.util.StrUtil;
  5. import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
  6. import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
  7. import com.aliyun.teaopenapi.models.Config;
  8. import com.google.zxing.common.BitMatrix;
  9. import com.zhongzheng.common.core.domain.AjaxResult;
  10. import com.zhongzheng.common.exception.CustomException;
  11. import io.micrometer.core.lang.NonNull;
  12. import net.sf.jsqlparser.expression.LongValue;
  13. import javax.crypto.Cipher;
  14. import javax.crypto.SecretKey;
  15. import javax.crypto.SecretKeyFactory;
  16. import javax.crypto.spec.DESKeySpec;
  17. import javax.crypto.spec.DESedeKeySpec;
  18. import javax.crypto.spec.IvParameterSpec;
  19. import javax.crypto.spec.SecretKeySpec;
  20. import java.awt.image.BufferedImage;
  21. import java.io.*;
  22. import java.nio.charset.StandardCharsets;
  23. import java.security.MessageDigest;
  24. import java.security.NoSuchAlgorithmException;
  25. import java.util.*;
  26. import static org.apache.xmlbeans.impl.util.Base64.encode;
  27. import java.util.regex.Matcher;
  28. import java.util.regex.Pattern;
  29. import java.util.zip.ZipEntry;
  30. import java.util.zip.ZipOutputStream;
  31. public class ToolsUtils {
  32. public static final int EMU_PER_PX = 9525;
  33. /**
  34. * 获取模块编码参数
  35. */
  36. public static String getSmsCode()
  37. {
  38. Random random = new Random();
  39. String result="";
  40. for (int i=0;i<6;i++)
  41. {
  42. result+=random.nextInt(10);
  43. }
  44. return result;
  45. }
  46. public static String join(@NonNull CharSequence delimiter, @NonNull Iterable tokens) {
  47. final Iterator<?> it = tokens.iterator();
  48. if (!it.hasNext()) {
  49. return "";
  50. }
  51. final StringBuilder sb = new StringBuilder();
  52. sb.append(it.next());
  53. while (it.hasNext()) {
  54. sb.append(delimiter);
  55. sb.append(it.next());
  56. }
  57. return sb.toString();
  58. }
  59. public static final int emuToPx(double emu) {
  60. return DoubleUtils.div(emu, EMU_PER_PX).intValue();
  61. }
  62. public static String getEncoding(String str) {
  63. String encode = "GB2312";
  64. try {
  65. if (str.equals(new String(str.getBytes(encode), encode))) {
  66. String s = encode;
  67. return s;
  68. }
  69. } catch (Exception exception) {
  70. }
  71. encode = "ISO-8859-1";
  72. try {
  73. if (str.equals(new String(str.getBytes(encode), encode))) {
  74. String s1 = encode;
  75. return s1;
  76. }
  77. } catch (Exception exception1) {
  78. }
  79. encode = "UTF-8";
  80. try {
  81. if (str.equals(new String(str.getBytes(encode), encode))) {
  82. String s2 = encode;
  83. return s2;
  84. }
  85. } catch (Exception exception2) {
  86. }
  87. encode = "GBK";
  88. try {
  89. if (str.equals(new String(str.getBytes(encode), encode))) {
  90. String s3 = encode;
  91. return s3;
  92. }
  93. } catch (Exception exception3) {
  94. }
  95. return "";
  96. }
  97. /**
  98. * 字符串转换UTF-8编码
  99. *
  100. * @param string 字符串
  101. * @return java.lang.String
  102. * @date 2022/4/14.
  103. */
  104. public static String toUtf8String(String string) {
  105. StringBuilder stringBuffer = new StringBuilder();
  106. for (int i = 0; i < string.length(); i++) {
  107. char c = string.charAt(i);
  108. if (c <= 255) {
  109. stringBuffer.append(c);
  110. } else {
  111. byte[] b;
  112. try {
  113. b = Character.toString(c).getBytes(StandardCharsets.UTF_8);
  114. } catch (Exception ex) {
  115. b = new byte[0];
  116. }
  117. for (int value : b) {
  118. int k = value;
  119. if (k < 0) k += 256;
  120. stringBuffer.append("%").append(Integer.toHexString(k).toUpperCase());
  121. }
  122. }
  123. }
  124. return stringBuffer.toString();
  125. }
  126. public static String StringToMd5(String psw) {
  127. {
  128. try {
  129. MessageDigest md5 = MessageDigest.getInstance("MD5");
  130. md5.update(psw.getBytes("UTF-8"));
  131. byte[] encryption = md5.digest();
  132. StringBuffer strBuf = new StringBuffer();
  133. for (int i = 0; i < encryption.length; i++) {
  134. if (Integer.toHexString(0xff & encryption[i]).length() == 1) {
  135. strBuf.append("0").append(Integer.toHexString(0xff & encryption[i]));
  136. } else {
  137. strBuf.append(Integer.toHexString(0xff & encryption[i]));
  138. }
  139. }
  140. return strBuf.toString();
  141. } catch (NoSuchAlgorithmException e) {
  142. return "";
  143. } catch (UnsupportedEncodingException e) {
  144. return "";
  145. }
  146. }
  147. }
  148. public static String getCharAndNumr(int length) {
  149. Random random = new Random();
  150. StringBuffer valSb = new StringBuffer();
  151. String charStr = "0123456789abcdefghijklmnopqrstuvwxyz";
  152. int charLength = charStr.length();
  153. for (int i = 0; i < length; i++) {
  154. int index = random.nextInt(charLength);
  155. valSb.append(charStr.charAt(index));
  156. }
  157. return valSb.toString();
  158. }
  159. public static <T> List<List<T>> splitListBycapacity(List<T> source, int capacity){
  160. List<List<T>> result=new ArrayList<List<T>>();
  161. if (source != null){
  162. int size = source.size();
  163. if (size > 0 ){
  164. for (int i = 0; i < size;) {
  165. List<T> value = null;
  166. int end = i+capacity;
  167. if (end > size){
  168. end = size;
  169. }
  170. value = source.subList(i,end);
  171. i = end;
  172. result.add(value);
  173. }
  174. }else {
  175. result = null;
  176. }
  177. }else {
  178. result = null;
  179. }
  180. return result;
  181. }
  182. /**
  183. * 校验签名
  184. *
  185. * @param token token
  186. * @param signature 签名
  187. * @param timestamp 时间戳
  188. * @param nonce 随机数
  189. * @return 布尔值
  190. */
  191. public static boolean checkGzhServerSignature(String token,String signature, String timestamp, String nonce) {
  192. String checktext = null;
  193. if (null != signature) {
  194. //对ToKen,timestamp,nonce 按字典排序
  195. String[] paramArr = new String[]{token, timestamp, nonce};
  196. Arrays.sort(paramArr);
  197. //将排序后的结果拼成一个字符串
  198. String content = paramArr[0].concat(paramArr[1]).concat(paramArr[2]);
  199. try {
  200. MessageDigest md = MessageDigest.getInstance("SHA-1");
  201. //对接后的字符串进行sha1加密
  202. byte[] digest = md.digest(content.toString().getBytes());
  203. checktext = byteToStr(digest);
  204. } catch (NoSuchAlgorithmException e) {
  205. e.printStackTrace();
  206. }
  207. }
  208. //将加密后的字符串与signature进行对比
  209. return checktext != null ? checktext.equals(signature.toUpperCase()) : false;
  210. }
  211. public static String removeAllTrim(String content) {
  212. if(Validator.isNotEmpty(content)){
  213. Pattern p = Pattern.compile("\\s*|\t|\r|\n");
  214. Matcher m = p.matcher(content);
  215. content = m.replaceAll("");
  216. content = content.replaceAll(" ", "");
  217. content = content.replaceAll("[\\u3000-\\u303F\\s\\u00A0]","");
  218. }
  219. return content;
  220. }
  221. /**
  222. * 将字节数组转化我16进制字符串
  223. *
  224. * @param byteArrays 字符数组
  225. * @return 字符串
  226. */
  227. private static String byteToStr(byte[] byteArrays) {
  228. String str = "";
  229. for (int i = 0; i < byteArrays.length; i++) {
  230. str += byteToHexStr(byteArrays[i]);
  231. }
  232. return str;
  233. }
  234. /**
  235. * 将字节转化为十六进制字符串
  236. *
  237. * @param myByte 字节
  238. * @return 字符串
  239. */
  240. private static String byteToHexStr(byte myByte) {
  241. char[] Digit = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
  242. char[] tampArr = new char[2];
  243. tampArr[0] = Digit[(myByte >>> 4) & 0X0F];
  244. tampArr[1] = Digit[myByte & 0X0F];
  245. String str = new String(tampArr);
  246. return str;
  247. }
  248. /**
  249. * 将文件转换成Byte数组
  250. */
  251. public static byte[] getBytesByFile(String pathStr) {
  252. File file = new File(pathStr);
  253. try {
  254. FileInputStream fis = new FileInputStream(file);
  255. ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);
  256. byte[] b = new byte[1000];
  257. int n;
  258. while ((n = fis.read(b)) != -1) {
  259. bos.write(b, 0, n);
  260. }
  261. fis.close();
  262. byte[] data = bos.toByteArray();
  263. bos.close();
  264. return data;
  265. } catch (IOException e) {
  266. }
  267. return null;
  268. }
  269. public static String encodetoStr(byte[] src) {
  270. byte[] encoded = encode(src);
  271. return new String(encoded,0,0,encoded.length);
  272. }
  273. /**
  274. * 不够位数的在前面补0,保留num的长度位数字
  275. * @param code
  276. * @return
  277. */
  278. public static String autoGenericCode(String code, int num) {
  279. String result = "";
  280. // 保留num的位数
  281. // 0 代表前面补充0
  282. // num 代表长度为4
  283. // d 代表参数为正数型
  284. result = String.format("%0" + num + "d", Integer.parseInt(code));
  285. return result;
  286. }
  287. public static Boolean checkSignFromOldSys(String stamp,String sign) {
  288. String newSign = stamp+"pubilc2022";
  289. if(!sign.equals(ToolsUtils.EncoderByMd5(newSign))){
  290. return false;
  291. }
  292. if((Long.parseLong(stamp)+10L>(DateUtils.getNowTime().longValue()))&&(Long.parseLong(stamp)<(DateUtils.getNowTime().longValue()-10L))){
  293. return false;
  294. }
  295. return true;
  296. }
  297. public static Boolean checkOrderSignFromOldSys(String orderSn,String stamp,String sign) {
  298. String newSign = orderSn+stamp+"pubilc2022";
  299. if(!sign.equals(ToolsUtils.EncoderByMd5(newSign))){
  300. return false;
  301. }
  302. if((Long.parseLong(stamp)+10L>(DateUtils.getNowTime().longValue()))&&(Long.parseLong(stamp)<(DateUtils.getNowTime().longValue()-10L))){
  303. return false;
  304. }
  305. return true;
  306. }
  307. public static Boolean checkSignCwSnFromOldSys(String cwSn,String stamp,String sign) {
  308. String newSign = cwSn+stamp+"pubilc2022";
  309. if(!sign.equals(ToolsUtils.EncoderByMd5(newSign))){
  310. return false;
  311. }
  312. if((Long.parseLong(stamp)+10L>(DateUtils.getNowTime().longValue()))&&(Long.parseLong(stamp)<(DateUtils.getNowTime().longValue()-10L))){
  313. return false;
  314. }
  315. return true;
  316. }
  317. public static String EncoderByMd5WithUtf(String str) {
  318. String result = "";
  319. MessageDigest md5 = null;
  320. try {
  321. md5 = MessageDigest.getInstance("MD5");
  322. // 这句是关键
  323. md5.update(str.getBytes("UTF-8"));
  324. } catch (NoSuchAlgorithmException e) {
  325. // TODO Auto-generated catch block
  326. e.printStackTrace();
  327. } catch (UnsupportedEncodingException e) {
  328. // TODO Auto-generated catch block
  329. e.printStackTrace();
  330. }
  331. byte b[] = md5.digest();
  332. int i;
  333. StringBuffer buf = new StringBuffer("");
  334. for (int offset = 0; offset < b.length; offset++) {
  335. i = b[offset];
  336. if (i < 0)
  337. i += 256;
  338. if (i < 16)
  339. buf.append("0");
  340. buf.append(Integer.toHexString(i));
  341. }
  342. result = buf.toString();
  343. return result;
  344. }
  345. public static String EncoderByMd5(String str) {
  346. String result = "";
  347. MessageDigest md5 = null;
  348. try {
  349. md5 = MessageDigest.getInstance("MD5");
  350. // 这句是关键
  351. md5.update(str.getBytes("gbk"));
  352. } catch (NoSuchAlgorithmException e) {
  353. // TODO Auto-generated catch block
  354. e.printStackTrace();
  355. } catch (UnsupportedEncodingException e) {
  356. // TODO Auto-generated catch block
  357. e.printStackTrace();
  358. }
  359. byte b[] = md5.digest();
  360. int i;
  361. StringBuffer buf = new StringBuffer("");
  362. for (int offset = 0; offset < b.length; offset++) {
  363. i = b[offset];
  364. if (i < 0)
  365. i += 256;
  366. if (i < 16)
  367. buf.append("0");
  368. buf.append(Integer.toHexString(i));
  369. }
  370. result = buf.toString();
  371. return result;
  372. }
  373. public static boolean verifEasyPwd(String passWord) {
  374. if(Validator.isEmpty(passWord)){
  375. return false;
  376. }
  377. if(passWord.length()<8||passWord.length()>16){
  378. throw new CustomException("密码长度限制8到16位");
  379. }
  380. return true;
  381. }
  382. public static boolean verifPwd(String passWord) {
  383. if(Validator.isEmpty(passWord)){
  384. return false;
  385. }
  386. /*if(passWord.length()<8||passWord.length()>18){
  387. return false;
  388. }*/
  389. String regExp = "^(?=.*?[a-z])(?=.*?[A-Z])(?=.*?\\d)(?=.*?[!#@*&.])[a-zA-Z\\d!#@*&.]{8,16}$";
  390. Pattern p = Pattern.compile(regExp);
  391. Matcher m = p.matcher(passWord);
  392. if (m.matches()){
  393. return true;
  394. } else {
  395. throw new CustomException("密码应由8-16位数字、大小写字母、符号组成");
  396. }
  397. }
  398. public static String getTenantId() {
  399. String TenantId = ServletUtils.getResponse().getHeader("TenantId");
  400. if(!StrUtil.isNotBlank(TenantId)||TenantId==null){
  401. TenantId = ServletUtils.getRequest().getHeader("TenantId");
  402. }
  403. if(Validator.isNotEmpty(TenantId)){
  404. if(TenantId.equals("undefined")){
  405. throw new CustomException("企业ID错误");
  406. }
  407. }
  408. return TenantId;
  409. }
  410. private static int getRandom(int count) {
  411. return (int) Math.round(Math.random() * (count));
  412. }
  413. public static String getRandomString(int length){
  414. String string = "abcdefghijklmnopqrstuvwxyz";
  415. StringBuffer sb = new StringBuffer();
  416. int len = string.length();
  417. for (int i = 0; i < length; i++) {
  418. sb.append(string.charAt(getRandom(len-1)));
  419. }
  420. return sb.toString();
  421. }
  422. public static BufferedImage toBufferedImage(BitMatrix matrix) {
  423. int black = 0xFF000000;
  424. int white = 0x00FFFFFF;
  425. int width = matrix.getWidth();
  426. int height = matrix.getHeight();
  427. BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
  428. for (int x = 0; x < width; x++) {
  429. for (int y = 0; y < height; y++) {
  430. image.setRGB(x, y, matrix.get(x, y) ? black : white);
  431. }
  432. }
  433. int imgHeight = image.getHeight();//取得图片的长和宽
  434. int imgWidth = image.getWidth();
  435. int c = image.getRGB(3, 3);
  436. int alpha = 10;
  437. //防止越位
  438. if (alpha < 0) {
  439. alpha = 0;
  440. } else if (alpha > 10) {
  441. alpha = 10;
  442. }
  443. BufferedImage tmpImg = new BufferedImage(imgWidth, imgHeight,BufferedImage.TYPE_4BYTE_ABGR);//新建一个类型支持透明的BufferedImage
  444. for(int i = 0; i < imgWidth; ++i)//把原图片的内容复制到新的图片,同时把背景设为透明
  445. {
  446. for(int j = 0; j < imgHeight; ++j){
  447. //把背景设为透明
  448. if(image.getRGB(i, j) == c){
  449. tmpImg .setRGB(i, j, c & 0x00ffffff);
  450. }
  451. //设置透明度
  452. else{
  453. int rgb = tmpImg .getRGB(i, j);
  454. rgb = ((alpha * 255 / 10) << 24) | (rgb & 0x00ffffff);
  455. tmpImg .setRGB(i, j, rgb);
  456. }
  457. }
  458. }
  459. return tmpImg ;
  460. }
  461. public static String solve(String num) {
  462. if (num == null) {
  463. return null;
  464. }
  465. // 判断是否有小数
  466. int index = num.indexOf(".");
  467. if (index >= 0) {
  468. String integer = num.substring(0, index);
  469. String decimal = num.substring(index);
  470. // 分隔后的整数+小数拼接起来
  471. return addSeparator(integer) + decimal;
  472. } else {
  473. return addSeparator(num);
  474. }
  475. }
  476. // 添加分隔符
  477. public static String addSeparator(String num) {
  478. int length = num.length();
  479. ArrayList list = new ArrayList();
  480. while (length > 3) {
  481. list.add(num.substring(length - 3, length));
  482. length = length - 3;
  483. }
  484. // 将前面小于三位的数字添加到ArrayList中
  485. list.add(num.substring(0, length));
  486. StringBuffer buffer = new StringBuffer();
  487. // 倒序拼接
  488. for (int i = list.size() - 1; i > 0; i--) {
  489. buffer.append(list.get(i) + ",");
  490. }
  491. buffer.append(list.get(0));
  492. return buffer.toString();
  493. }
  494. public static String dataSign(String sourceMsg, String pKey) throws NoSuchAlgorithmException {
  495. String tempPKey = MD5PubHasher(pKey.getBytes(StandardCharsets.UTF_8));
  496. tempPKey = sourceMsg + tempPKey;
  497. tempPKey = MD5PubHasher(tempPKey.getBytes(StandardCharsets.UTF_8));
  498. return tempPKey;
  499. }
  500. public static String MD5PubHasher(byte[] hashText) {
  501. try {
  502. MessageDigest md5 = MessageDigest.getInstance("MD5");
  503. byte[] b = md5.digest(hashText);
  504. StringBuilder ret = new StringBuilder();
  505. for (int i = 0; i < b.length; i++) {
  506. ret.append(String.format("%02x", b[i]));
  507. }
  508. return ret.toString();
  509. }catch (NoSuchAlgorithmException e){
  510. return null;
  511. }
  512. }
  513. public static String encryptDes(String source, byte[] key, byte[] iv) throws Exception {
  514. SecretKey secretKey = new SecretKeySpec(key, "DES");
  515. IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);
  516. Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
  517. cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivParameterSpec);
  518. byte[] inputByteArray = source.getBytes(StandardCharsets.UTF_8);
  519. byte[] encryptedByteArray = cipher.doFinal(inputByteArray);
  520. return new String(java.util.Base64.getEncoder().encode(encryptedByteArray));
  521. }
  522. public static String decryptDes(String source, byte[] key, byte[] iv) throws Exception {
  523. SecretKey secretKey = new SecretKeySpec(key, "DES");
  524. IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);
  525. Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
  526. cipher.init(Cipher.DECRYPT_MODE, secretKey, ivParameterSpec);
  527. byte[] inputByteArray = java.util.Base64.getDecoder().decode(source.getBytes(StandardCharsets.UTF_8));
  528. byte[] decryptedByteArray = cipher.doFinal(inputByteArray);
  529. return new String(decryptedByteArray, StandardCharsets.UTF_8);
  530. }
  531. /*public static String encryptDesNew(String source, String pass) throws Exception {
  532. byte[] rgbKey = pass.getBytes("UTF-8");
  533. byte[] rgbIV = pass.getBytes("UTF-8");
  534. DESedeKeySpec desKeySpec = new DESedeKeySpec(rgbKey);
  535. SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
  536. SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
  537. Cipher cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
  538. byte[] inputByteArray = source.getBytes("UTF-8");
  539. IvParameterSpec ivParameterSpec = new IvParameterSpec(rgbIV);
  540. cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivParameterSpec);
  541. byte[] encrypted = cipher.doFinal(inputByteArray);
  542. return Base64.getEncoder().encodeToString(encrypted);}
  543. }*/
  544. /**
  545. Des解密
  546. @param source 源字符串
  547. @param pass 密钥,长度必须8位
  548. @return 解密后的字符串 */
  549. /*public static String decryptDesNew(String source, String pass) throws Exception {
  550. byte[] rgbKey = pass.getBytes("UTF-8");
  551. byte[] rgbIV = pass.getBytes("UTF-8");
  552. DESedeKeySpec desKeySpec = new DESedeKeySpec(rgbKey);
  553. SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
  554. SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
  555. Cipher cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding")) {
  556. byte[] inputByteArray = Base64.getDecoder().decode(source);
  557. IvParameterSpec ivParameterSpec = new IvParameterSpec(rgbIV);
  558. cipher.init(Cipher.DECRYPT_MODE, secretKey, ivParameterSpec);
  559. byte[] decrypted = cipher.doFinal(inputByteArray);
  560. return new String(decrypted, "UTF-8");
  561. }
  562. }*/
  563. public static String encryptDesNew(String source, String pass) throws Exception {
  564. byte[] rgbKey = pass.getBytes(StandardCharsets.UTF_8);
  565. byte[] rgbIV = pass.getBytes(StandardCharsets.UTF_8);
  566. DESKeySpec desKeySpec = new DESKeySpec(rgbKey);
  567. SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
  568. SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
  569. Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
  570. byte[] inputByteArray = source.getBytes(StandardCharsets.UTF_8);
  571. IvParameterSpec ivParameterSpec = new IvParameterSpec(rgbIV);
  572. cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivParameterSpec);
  573. byte[] encryptedByteArray = cipher.doFinal(inputByteArray);
  574. return Base64.getEncoder().encodeToString(encryptedByteArray);
  575. }
  576. public static String decryptDesNew(String source, String pass) throws Exception {
  577. byte[] rgbKey = pass.getBytes(StandardCharsets.UTF_8);
  578. byte[] rgbIV = pass.getBytes(StandardCharsets.UTF_8);
  579. DESKeySpec desKeySpec = new DESKeySpec(rgbKey);
  580. SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
  581. SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
  582. Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
  583. byte[] inputByteArray = Base64.getDecoder().decode(source);
  584. IvParameterSpec ivParameterSpec = new IvParameterSpec(rgbIV);
  585. cipher.init(Cipher.DECRYPT_MODE, secretKey, ivParameterSpec);
  586. byte[] decryptedByteArray = cipher.doFinal(inputByteArray);
  587. return new String(decryptedByteArray, StandardCharsets.UTF_8);
  588. }
  589. private static String base64Encode(byte[] bytes) throws IOException {
  590. ByteArrayOutputStream output = new ByteArrayOutputStream();
  591. Base64.getEncoder().wrap(output).write(bytes);
  592. return output.toString(StandardCharsets.UTF_8.name());
  593. }
  594. /*private static byte[] base64Decode(String str) throws IOException {
  595. ByteArrayOutputStream output = new ByteArrayOutputStream();
  596. Base64.getDecoder().wrap(output).write(str.getBytes(StandardCharsets.UTF_8));
  597. return output.toByteArray();
  598. }*/
  599. private static byte[] base64Decode(String str) throws IOException {
  600. byte[] decodedString = Base64.getDecoder().decode(new String(str).getBytes("UTF-8"));
  601. return decodedString;
  602. }
  603. }