ToolsUtils.java 18 KB

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