郑永安
2023-09-19 69185134fcfaf913ea45f1255677225a2cc311a4
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
package com.gk.hotwork.Domain.Utils;
 
import com.gk.hotwork.Domain.Exception.BusinessException;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
 
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.security.MessageDigest;
 
public class MD5Utils {
 
        private static Logger logger = Logger.getLogger(MD5Utils.class);
        private static final char[] HEX = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e',
                'f' };
        private static final String MD5 = "MD5";
        private static final Charset CHARSET = Charset.forName("UTF-8");
 
        public static char[] HexEncode(byte[] bytes) {
            final int nBytes = bytes.length;
            char[] result = new char[2 * nBytes];
 
            int j = 0;
            for (int i = 0; i < nBytes; i++) {
                result[j++] = HEX[(0xF0 & bytes[i]) >>> 4];
                result[j++] = HEX[(0x0F & bytes[i])];
            }
 
            return result;
        }
 
        public static byte[] Utf8Encode(CharSequence string) {
            try {
                ByteBuffer bytes = CHARSET.newEncoder().encode(CharBuffer.wrap(string));
                byte[] bytesCopy = new byte[bytes.limit()];
                System.arraycopy(bytes.array(), 0, bytesCopy, 0, bytes.limit());
 
                return bytesCopy;
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
                throw new BusinessException("字符转码失败。");
            }
        }
 
        public static String encode(String data) {
            try {
                if (StringUtils.isEmpty(data)) {
                    data = "";
                }
                MessageDigest messageDigest = MessageDigest.getInstance(MD5);
                byte[] digest = messageDigest.digest(Utf8Encode(data));
                return new String(HexEncode(digest));
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
                throw new BusinessException("字符转码失败。");
            }
        }
 
}