package com.zhongzheng.common.utils; import cn.hutool.core.convert.Convert; import cn.hutool.core.lang.Validator; import cn.hutool.core.util.StrUtil; import com.aliyun.dysmsapi20170525.models.SendSmsRequest; import com.aliyun.dysmsapi20170525.models.SendSmsResponse; import com.aliyun.teaopenapi.models.Config; import com.google.zxing.common.BitMatrix; import com.zhongzheng.common.core.domain.AjaxResult; import com.zhongzheng.common.exception.CustomException; import io.micrometer.core.lang.NonNull; import net.sf.jsqlparser.expression.LongValue; import javax.crypto.Cipher; import javax.crypto.SecretKey; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.DESKeySpec; import javax.crypto.spec.DESedeKeySpec; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; import java.awt.image.BufferedImage; import java.io.*; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.*; import static org.apache.xmlbeans.impl.util.Base64.encode; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; public class ToolsUtils { public static final int EMU_PER_PX = 9525; /** * 获取模块编码参数 */ public static String getSmsCode() { Random random = new Random(); String result=""; for (int i=0;i<6;i++) { result+=random.nextInt(10); } return result; } public static String join(@NonNull CharSequence delimiter, @NonNull Iterable tokens) { final Iterator it = tokens.iterator(); if (!it.hasNext()) { return ""; } final StringBuilder sb = new StringBuilder(); sb.append(it.next()); while (it.hasNext()) { sb.append(delimiter); sb.append(it.next()); } return sb.toString(); } public static final int emuToPx(double emu) { return DoubleUtils.div(emu, EMU_PER_PX).intValue(); } public static String getEncoding(String str) { String encode = "GB2312"; try { if (str.equals(new String(str.getBytes(encode), encode))) { String s = encode; return s; } } catch (Exception exception) { } encode = "ISO-8859-1"; try { if (str.equals(new String(str.getBytes(encode), encode))) { String s1 = encode; return s1; } } catch (Exception exception1) { } encode = "UTF-8"; try { if (str.equals(new String(str.getBytes(encode), encode))) { String s2 = encode; return s2; } } catch (Exception exception2) { } encode = "GBK"; try { if (str.equals(new String(str.getBytes(encode), encode))) { String s3 = encode; return s3; } } catch (Exception exception3) { } return ""; } /** * 字符串转换UTF-8编码 * * @param string 字符串 * @return java.lang.String * @date 2022/4/14. */ public static String toUtf8String(String string) { StringBuilder stringBuffer = new StringBuilder(); for (int i = 0; i < string.length(); i++) { char c = string.charAt(i); if (c <= 255) { stringBuffer.append(c); } else { byte[] b; try { b = Character.toString(c).getBytes(StandardCharsets.UTF_8); } catch (Exception ex) { b = new byte[0]; } for (int value : b) { int k = value; if (k < 0) k += 256; stringBuffer.append("%").append(Integer.toHexString(k).toUpperCase()); } } } return stringBuffer.toString(); } public static String StringToMd5(String psw) { { try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(psw.getBytes("UTF-8")); byte[] encryption = md5.digest(); StringBuffer strBuf = new StringBuffer(); for (int i = 0; i < encryption.length; i++) { if (Integer.toHexString(0xff & encryption[i]).length() == 1) { strBuf.append("0").append(Integer.toHexString(0xff & encryption[i])); } else { strBuf.append(Integer.toHexString(0xff & encryption[i])); } } return strBuf.toString(); } catch (NoSuchAlgorithmException e) { return ""; } catch (UnsupportedEncodingException e) { return ""; } } } public static String getCharAndNumr(int length) { Random random = new Random(); StringBuffer valSb = new StringBuffer(); String charStr = "0123456789abcdefghijklmnopqrstuvwxyz"; int charLength = charStr.length(); for (int i = 0; i < length; i++) { int index = random.nextInt(charLength); valSb.append(charStr.charAt(index)); } return valSb.toString(); } public static List> splitListBycapacity(List source, int capacity){ List> result=new ArrayList>(); if (source != null){ int size = source.size(); if (size > 0 ){ for (int i = 0; i < size;) { List value = null; int end = i+capacity; if (end > size){ end = size; } value = source.subList(i,end); i = end; result.add(value); } }else { result = null; } }else { result = null; } return result; } /** * 校验签名 * * @param token token * @param signature 签名 * @param timestamp 时间戳 * @param nonce 随机数 * @return 布尔值 */ public static boolean checkGzhServerSignature(String token,String signature, String timestamp, String nonce) { String checktext = null; if (null != signature) { //对ToKen,timestamp,nonce 按字典排序 String[] paramArr = new String[]{token, timestamp, nonce}; Arrays.sort(paramArr); //将排序后的结果拼成一个字符串 String content = paramArr[0].concat(paramArr[1]).concat(paramArr[2]); try { MessageDigest md = MessageDigest.getInstance("SHA-1"); //对接后的字符串进行sha1加密 byte[] digest = md.digest(content.toString().getBytes()); checktext = byteToStr(digest); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } } //将加密后的字符串与signature进行对比 return checktext != null ? checktext.equals(signature.toUpperCase()) : false; } public static String removeAllTrim(String content) { if(Validator.isNotEmpty(content)){ Pattern p = Pattern.compile("\\s*|\t|\r|\n"); Matcher m = p.matcher(content); content = m.replaceAll(""); content = content.replaceAll(" ", ""); content = content.replaceAll("[\\u3000-\\u303F\\s\\u00A0]",""); } return content; } /** * 将字节数组转化我16进制字符串 * * @param byteArrays 字符数组 * @return 字符串 */ private static String byteToStr(byte[] byteArrays) { String str = ""; for (int i = 0; i < byteArrays.length; i++) { str += byteToHexStr(byteArrays[i]); } return str; } /** * 将字节转化为十六进制字符串 * * @param myByte 字节 * @return 字符串 */ private static String byteToHexStr(byte myByte) { char[] Digit = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'}; char[] tampArr = new char[2]; tampArr[0] = Digit[(myByte >>> 4) & 0X0F]; tampArr[1] = Digit[myByte & 0X0F]; String str = new String(tampArr); return str; } /** * 将文件转换成Byte数组 */ public static byte[] getBytesByFile(String pathStr) { File file = new File(pathStr); try { FileInputStream fis = new FileInputStream(file); ByteArrayOutputStream bos = new ByteArrayOutputStream(1000); byte[] b = new byte[1000]; int n; while ((n = fis.read(b)) != -1) { bos.write(b, 0, n); } fis.close(); byte[] data = bos.toByteArray(); bos.close(); return data; } catch (IOException e) { } return null; } public static String encodetoStr(byte[] src) { byte[] encoded = encode(src); return new String(encoded,0,0,encoded.length); } /** * 不够位数的在前面补0,保留num的长度位数字 * @param code * @return */ public static String autoGenericCode(String code, int num) { String result = ""; // 保留num的位数 // 0 代表前面补充0 // num 代表长度为4 // d 代表参数为正数型 result = String.format("%0" + num + "d", Integer.parseInt(code)); return result; } public static Boolean checkSignFromOldSys(String stamp,String sign) { String newSign = stamp+"pubilc2022"; if(!sign.equals(ToolsUtils.EncoderByMd5(newSign))){ return false; } if((Long.parseLong(stamp)+10L>(DateUtils.getNowTime().longValue()))&&(Long.parseLong(stamp)<(DateUtils.getNowTime().longValue()-10L))){ return false; } return true; } public static Boolean checkOrderSignFromOldSys(String orderSn,String stamp,String sign) { String newSign = orderSn+stamp+"pubilc2022"; if(!sign.equals(ToolsUtils.EncoderByMd5(newSign))){ return false; } if((Long.parseLong(stamp)+10L>(DateUtils.getNowTime().longValue()))&&(Long.parseLong(stamp)<(DateUtils.getNowTime().longValue()-10L))){ return false; } return true; } public static Boolean checkSignCwSnFromOldSys(String cwSn,String stamp,String sign) { String newSign = cwSn+stamp+"pubilc2022"; if(!sign.equals(ToolsUtils.EncoderByMd5(newSign))){ return false; } if((Long.parseLong(stamp)+10L>(DateUtils.getNowTime().longValue()))&&(Long.parseLong(stamp)<(DateUtils.getNowTime().longValue()-10L))){ return false; } return true; } public static String EncoderByMd5WithUtf(String str) { String result = ""; MessageDigest md5 = null; try { md5 = MessageDigest.getInstance("MD5"); // 这句是关键 md5.update(str.getBytes("UTF-8")); } catch (NoSuchAlgorithmException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } byte b[] = md5.digest(); int i; StringBuffer buf = new StringBuffer(""); for (int offset = 0; offset < b.length; offset++) { i = b[offset]; if (i < 0) i += 256; if (i < 16) buf.append("0"); buf.append(Integer.toHexString(i)); } result = buf.toString(); return result; } public static String EncoderByMd5(String str) { String result = ""; MessageDigest md5 = null; try { md5 = MessageDigest.getInstance("MD5"); // 这句是关键 md5.update(str.getBytes("gbk")); } catch (NoSuchAlgorithmException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } byte b[] = md5.digest(); int i; StringBuffer buf = new StringBuffer(""); for (int offset = 0; offset < b.length; offset++) { i = b[offset]; if (i < 0) i += 256; if (i < 16) buf.append("0"); buf.append(Integer.toHexString(i)); } result = buf.toString(); return result; } public static boolean verifEasyPwd(String passWord) { if(Validator.isEmpty(passWord)){ return false; } if(passWord.length()<8||passWord.length()>16){ throw new CustomException("密码长度限制8到16位"); } return true; } public static boolean verifPwd(String passWord) { if(Validator.isEmpty(passWord)){ return false; } /*if(passWord.length()<8||passWord.length()>18){ return false; }*/ String regExp = "^(?=.*?[a-z])(?=.*?[A-Z])(?=.*?\\d)(?=.*?[!#@*&.])[a-zA-Z\\d!#@*&.]{8,16}$"; Pattern p = Pattern.compile(regExp); Matcher m = p.matcher(passWord); if (m.matches()){ return true; } else { throw new CustomException("密码应由8-16位数字、大小写字母、符号组成"); } } public static String getTenantId() { String TenantId = ServletUtils.getResponse().getHeader("TenantId"); if(!StrUtil.isNotBlank(TenantId)||TenantId==null){ TenantId = ServletUtils.getRequest().getHeader("TenantId"); } if(Validator.isNotEmpty(TenantId)){ if(TenantId.equals("undefined")){ throw new CustomException("企业ID错误"); } } return TenantId; } private static int getRandom(int count) { return (int) Math.round(Math.random() * (count)); } public static String getRandomString(int length){ String string = "abcdefghijklmnopqrstuvwxyz"; StringBuffer sb = new StringBuffer(); int len = string.length(); for (int i = 0; i < length; i++) { sb.append(string.charAt(getRandom(len-1))); } return sb.toString(); } public static BufferedImage toBufferedImage(BitMatrix matrix) { int black = 0xFF000000; int white = 0x00FFFFFF; int width = matrix.getWidth(); int height = matrix.getHeight(); BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { image.setRGB(x, y, matrix.get(x, y) ? black : white); } } int imgHeight = image.getHeight();//取得图片的长和宽 int imgWidth = image.getWidth(); int c = image.getRGB(3, 3); int alpha = 10; //防止越位 if (alpha < 0) { alpha = 0; } else if (alpha > 10) { alpha = 10; } BufferedImage tmpImg = new BufferedImage(imgWidth, imgHeight,BufferedImage.TYPE_4BYTE_ABGR);//新建一个类型支持透明的BufferedImage for(int i = 0; i < imgWidth; ++i)//把原图片的内容复制到新的图片,同时把背景设为透明 { for(int j = 0; j < imgHeight; ++j){ //把背景设为透明 if(image.getRGB(i, j) == c){ tmpImg .setRGB(i, j, c & 0x00ffffff); } //设置透明度 else{ int rgb = tmpImg .getRGB(i, j); rgb = ((alpha * 255 / 10) << 24) | (rgb & 0x00ffffff); tmpImg .setRGB(i, j, rgb); } } } return tmpImg ; } public static String solve(String num) { if (num == null) { return null; } // 判断是否有小数 int index = num.indexOf("."); if (index >= 0) { String integer = num.substring(0, index); String decimal = num.substring(index); // 分隔后的整数+小数拼接起来 return addSeparator(integer) + decimal; } else { return addSeparator(num); } } // 添加分隔符 public static String addSeparator(String num) { int length = num.length(); ArrayList list = new ArrayList(); while (length > 3) { list.add(num.substring(length - 3, length)); length = length - 3; } // 将前面小于三位的数字添加到ArrayList中 list.add(num.substring(0, length)); StringBuffer buffer = new StringBuffer(); // 倒序拼接 for (int i = list.size() - 1; i > 0; i--) { buffer.append(list.get(i) + ","); } buffer.append(list.get(0)); return buffer.toString(); } public static String dataSign(String sourceMsg, String pKey) throws NoSuchAlgorithmException { String tempPKey = MD5PubHasher(pKey.getBytes(StandardCharsets.UTF_8)); tempPKey = sourceMsg + tempPKey; tempPKey = MD5PubHasher(tempPKey.getBytes(StandardCharsets.UTF_8)); return tempPKey; } public static String MD5PubHasher(byte[] hashText) { try { MessageDigest md5 = MessageDigest.getInstance("MD5"); byte[] b = md5.digest(hashText); StringBuilder ret = new StringBuilder(); for (int i = 0; i < b.length; i++) { ret.append(String.format("%02x", b[i])); } return ret.toString(); }catch (NoSuchAlgorithmException e){ return null; } } public static String encryptDes(String source, byte[] key, byte[] iv) throws Exception { SecretKey secretKey = new SecretKeySpec(key, "DES"); IvParameterSpec ivParameterSpec = new IvParameterSpec(iv); Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivParameterSpec); byte[] inputByteArray = source.getBytes(StandardCharsets.UTF_8); byte[] encryptedByteArray = cipher.doFinal(inputByteArray); return new String(java.util.Base64.getEncoder().encode(encryptedByteArray)); } public static String decryptDes(String source, byte[] key, byte[] iv) throws Exception { SecretKey secretKey = new SecretKeySpec(key, "DES"); IvParameterSpec ivParameterSpec = new IvParameterSpec(iv); Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding"); cipher.init(Cipher.DECRYPT_MODE, secretKey, ivParameterSpec); byte[] inputByteArray = java.util.Base64.getDecoder().decode(source.getBytes(StandardCharsets.UTF_8)); byte[] decryptedByteArray = cipher.doFinal(inputByteArray); return new String(decryptedByteArray, StandardCharsets.UTF_8); } /*public static String encryptDesNew(String source, String pass) throws Exception { byte[] rgbKey = pass.getBytes("UTF-8"); byte[] rgbIV = pass.getBytes("UTF-8"); DESedeKeySpec desKeySpec = new DESedeKeySpec(rgbKey); SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); SecretKey secretKey = keyFactory.generateSecret(desKeySpec); Cipher cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding"); byte[] inputByteArray = source.getBytes("UTF-8"); IvParameterSpec ivParameterSpec = new IvParameterSpec(rgbIV); cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivParameterSpec); byte[] encrypted = cipher.doFinal(inputByteArray); return Base64.getEncoder().encodeToString(encrypted);} }*/ /** Des解密 @param source 源字符串 @param pass 密钥,长度必须8位 @return 解密后的字符串 */ /*public static String decryptDesNew(String source, String pass) throws Exception { byte[] rgbKey = pass.getBytes("UTF-8"); byte[] rgbIV = pass.getBytes("UTF-8"); DESedeKeySpec desKeySpec = new DESedeKeySpec(rgbKey); SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); SecretKey secretKey = keyFactory.generateSecret(desKeySpec); Cipher cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding")) { byte[] inputByteArray = Base64.getDecoder().decode(source); IvParameterSpec ivParameterSpec = new IvParameterSpec(rgbIV); cipher.init(Cipher.DECRYPT_MODE, secretKey, ivParameterSpec); byte[] decrypted = cipher.doFinal(inputByteArray); return new String(decrypted, "UTF-8"); } }*/ public static String encryptDesNew(String source, String pass) throws Exception { byte[] rgbKey = pass.getBytes(StandardCharsets.UTF_8); byte[] rgbIV = pass.getBytes(StandardCharsets.UTF_8); DESKeySpec desKeySpec = new DESKeySpec(rgbKey); SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); SecretKey secretKey = keyFactory.generateSecret(desKeySpec); Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding"); byte[] inputByteArray = source.getBytes(StandardCharsets.UTF_8); IvParameterSpec ivParameterSpec = new IvParameterSpec(rgbIV); cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivParameterSpec); byte[] encryptedByteArray = cipher.doFinal(inputByteArray); return Base64.getEncoder().encodeToString(encryptedByteArray); } public static String decryptDesNew(String source, String pass) throws Exception { byte[] rgbKey = pass.getBytes(StandardCharsets.UTF_8); byte[] rgbIV = pass.getBytes(StandardCharsets.UTF_8); DESKeySpec desKeySpec = new DESKeySpec(rgbKey); SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); SecretKey secretKey = keyFactory.generateSecret(desKeySpec); Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding"); byte[] inputByteArray = Base64.getDecoder().decode(source); IvParameterSpec ivParameterSpec = new IvParameterSpec(rgbIV); cipher.init(Cipher.DECRYPT_MODE, secretKey, ivParameterSpec); byte[] decryptedByteArray = cipher.doFinal(inputByteArray); return new String(decryptedByteArray, StandardCharsets.UTF_8); } private static String base64Encode(byte[] bytes) throws IOException { ByteArrayOutputStream output = new ByteArrayOutputStream(); Base64.getEncoder().wrap(output).write(bytes); return output.toString(StandardCharsets.UTF_8.name()); } /*private static byte[] base64Decode(String str) throws IOException { ByteArrayOutputStream output = new ByteArrayOutputStream(); Base64.getDecoder().wrap(output).write(str.getBytes(StandardCharsets.UTF_8)); return output.toByteArray(); }*/ private static byte[] base64Decode(String str) throws IOException { byte[] decodedString = Base64.getDecoder().decode(new String(str).getBytes("UTF-8")); return decodedString; } }