kongzy
2024-07-01 47a751cb301d05276ae5d75145d57b2d090fe4e1
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
package com.nanometer.smartlab.util;
 
import org.apache.commons.lang3.StringUtils;
 
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
 
/**
 * Created by johnny on 15/9/8.
 */
public class MD5Utils {
 
    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) throws CharacterCodingException {
        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 (CharacterCodingException e) {
            throw e;
        }
    }
 
    public static String encode(String data) throws NoSuchAlgorithmException, CharacterCodingException {
        try {
            if (StringUtils.isEmpty(data)) {
                data = "";
            }
            MessageDigest messageDigest = MessageDigest.getInstance(MD5);
            byte[] digest = messageDigest.digest(Utf8Encode(data));
            return new String(HexEncode(digest));
        } catch (NoSuchAlgorithmException e) {
            throw e;
        } catch (CharacterCodingException e) {
            throw e;
        }
    }
 
    public static void main(String[] args) {
        String str = "123456789";
        try {
            System.out.println(encode(str));
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (CharacterCodingException e) {
            e.printStackTrace();
        }
 
    }
}