Administrator
2022-09-14 58d006e05dcf2a20d0ec5367dd03d66a61db6849
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
package com.mandi.common;
 
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Random;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
 
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
 
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
 
 
 
public class BasicMethod {
    public static String byte2hexStr(byte[] buf){
        if(buf==null)
            return null;
        StringBuffer sb=new StringBuffer();
        for(int i=0;i<buf.length;i++){
            String hex=Integer.toHexString(buf[i]&0xff);
            if(hex.length()==1)
            {
                hex='0'+hex;
            }
            sb.append(hex);
        }
        return sb.toString();
    }
    public static byte[] hexStr2bytes(String str){
        if(str==null||str.length()<1)
            return null;
        byte[] result=new byte[str.length()>>1];
        for(int i=0;i<str.length();i+=2){
            int high=Integer.parseInt(str.substring(i, i+1),16);
            int low=Integer.parseInt(str.substring(i+1, i+2),16);
            result[i>>1]=(byte)(((high<<4)&0xf0)+low);
        }
        return result;
    }
    /**
     * Aes 加密
     * @param source
     * @param password
     * @return
     */
    public static String encryptAES(String source,String password){
        if(source==null||password==null)
            return null;
        try {
            KeyGenerator keygen=KeyGenerator.getInstance("AES");
            SecureRandom sr=SecureRandom.getInstance("SHA1PRNG");
            sr.setSeed(password.getBytes());
            keygen.init(128,sr);
            SecretKey key=keygen.generateKey();
            byte[] keyendoce=key.getEncoded();
            SecretKeySpec keyspec=new SecretKeySpec(keyendoce, "AES");
            Cipher cipher=Cipher.getInstance("AES");
            cipher.init(Cipher.ENCRYPT_MODE,keyspec );
            byte[] sbytes=null;
            try {
                sbytes = cipher.doFinal(source.getBytes("utf8"));
            } catch (UnsupportedEncodingException e) {
                System.out.println("加密过程中,getbyte有错误!");
                e.printStackTrace();
            }
            return byte2hexStr(sbytes);  //这里也可以用base64来表示,这样解密的时候反解析base64
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        }
        
        return "";
    }
    public static String decryptAES(String source,String password)
    {
        if(source==null||password==null)
            return "";
        byte[] sbytes=hexStr2bytes(source);
        try {
            KeyGenerator keygen=KeyGenerator.getInstance("AES");
            SecureRandom sr=SecureRandom.getInstance("SHA1PRNG");
            sr.setSeed(password.getBytes());
            keygen.init(128,sr);
            SecretKey key=keygen.generateKey();
            byte[] keyendoce=key.getEncoded();
            SecretKeySpec keyspec=new SecretKeySpec(keyendoce, "AES");
            Cipher cipher=Cipher.getInstance("AES");
            cipher.init(Cipher.DECRYPT_MODE, keyspec);
            byte[] dbytes=cipher.doFinal(sbytes);
            try {
                return new String(dbytes,"utf8");
            } catch (UnsupportedEncodingException e) {
                System.out.println("解密过程中,编码错误!");
                e.printStackTrace();
            }
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        }
        return "";
    }
    public static String encryptSHA(String source)//SHA 摘要,不可逆
    {
        if(source==null)
            return null;
        MessageDigest md;
        try {
            md = MessageDigest.getInstance("SHA-256");
            byte[] bytes=md.digest(source.getBytes());
            return byte2hexStr(bytes);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }
    public static String encryptMD5(String source)//SHA 摘要,不可逆
    {
        if(source==null)
            return null;
        MessageDigest md;
        try {
            md = MessageDigest.getInstance("md5");
            byte[] bytes=md.digest(source.getBytes("utf-8"));
            return byte2hexStr(bytes);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return "";
    }
    public static String encryptSHA1(String source)//SHA 摘要,不可逆
    {
        if(source==null)
            return null;
        MessageDigest md;
        try {
            md = MessageDigest.getInstance("SHA-1");
            byte[] bytes=md.digest(source.getBytes());
            return byte2hexStr(bytes);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }
    public static boolean checkEmailFormat(String email)
    {
        if(email==null)
            return false;
        String patterns="[a-zA-Z]+([-.][a-zA-Z0-9_-]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*" +"(\\.[A-Za-z]{2,3})$";
        Pattern p=Pattern.compile(patterns);
        Matcher m=p.matcher(email);
        if(m.matches())
            return true;
        return false;
    }
    public static boolean checkvalidusername(String username)
    {
        if(username==null)
            return false;
        String patterns="^[a-zA-Z][a-zA-Z0-9._-]{5,50}";
        Pattern p=Pattern.compile(patterns);
        Matcher m=p.matcher(username);
        if(m.matches())
            return true;
        return false;
    }
    public static boolean checkIP(String ip)
    {
        if(ip==null)
            return false;
        String pattern="^(\\d{1,2}|1\\d\\d|2[0-4]\\d|25[0-5])\\.(\\d{1,2}|1\\d\\d|2[0-4]\\d|25[0-5])\\.(\\d{1,2}|1\\d\\d|2[0-4]\\d|25[0-5])\\.(\\d{1,2}|1\\d\\d|2[0-4]\\d|25[0-5])$";
        Pattern p=Pattern.compile(pattern);
        Matcher m=p.matcher(ip);
        if(m.matches())
            return true;
        return false;
    }
    /**
     * 判断date是否处于当前时间-days前
     * @param date
     * @param days
     * @return 
     */
    public static boolean before(Date date, int days)
    {
        if(date==null)
            return false;
        Date now=new Date(System.currentTimeMillis());
        Calendar nowcal=Calendar.getInstance();
        nowcal.setTime(now);
        Calendar datecal=Calendar.getInstance();
        datecal.setTime(date);
        nowcal.add(Calendar.DAY_OF_MONTH, -days);
        if(datecal.before(nowcal))
            return true;
        return false;
    }
    /**
     * 判断date是否处于当前时间+days后
     * @param date
     * @param days
     * @return
     */
    public static boolean after(Date date,int days)
    {
        if(date==null)
            return false;
        Date now=new Date(System.currentTimeMillis());
        Calendar nowcal=Calendar.getInstance();
        nowcal.setTime(now);
        Calendar datecal=Calendar.getInstance();
        datecal.setTime(date);
        nowcal.add(Calendar.DAY_OF_MONTH, days);
        if(datecal.after(nowcal))
            return true;
        return false;
    }
    /**
     * 讲string字符串,规整化掉sql里面的特殊字符'和\
     */
    public static String sqlformat(String param)
    {
        if(param==null)
            return null;
        param=param.trim();
        String t=param.replaceAll("'", "\\\\'");
        t=t.replaceAll("\"", "\\\\\"");
        return t;
    }
    /**
     * 使用Jsoup包解析html content,并提取出所有的img超链接
     * @param content
     * @return
     */
    public static String parseimgs(String content)
    {
        if(content==null)
            return null;
        Document doc=Jsoup.parse(content);
        Elements eles=doc.select("img");
        Iterator<Element> ele=eles.iterator();
        Set<String> set=new HashSet<String>();
        while(ele.hasNext())
        {
            Element e=ele.next();
            set.add(e.attr("src"));
        }
        if(set.size()>0)
            return Jacksonmethod.tojson(set, false);
        return null;
    }
    
    public static int countDays(Date stime,Date etime){
        if(stime==null||etime==null)
            return 0;
         return (int)((etime.getTime() - stime.getTime()) / (1000L * 60L * 60L * 24L));
    }
    public static String randomstr(int length)
    {
        if(length<=0)
            return null;
         char[] chars = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8',
                '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'k', 'l',
                'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x',
                'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
                'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V',
                'W', 'X', 'Y', 'Z' };
         Random r=new Random(System.currentTimeMillis());
         int charlength=chars.length;
         StringBuffer sb=new StringBuffer();
         for (int i = 0; i <length; i++) {
            int ri=r.nextInt(charlength);
            sb.append(chars[ri]);
        }
        return sb.toString();
    }
    
    public static String first2Upper(String str)
    {
        if(str==null)
            return null;
        char[] cs=str.toCharArray();
        cs[0]-=32;
        return String.valueOf(cs);
    }
    public static String getNow(Date now,String format){
        Date d=new Date();
        if(now!=null){
            d=now;
        }
        SimpleDateFormat sdf=new SimpleDateFormat(format==null?"yyyy-MM-dd HH:mm:ss":format);
        return sdf.format(d);
    }
}