1 | |
package liquibase.util; |
2 | |
|
3 | |
import liquibase.exception.UnexpectedLiquibaseException; |
4 | |
import liquibase.logging.LogFactory; |
5 | |
|
6 | |
import java.io.InputStream; |
7 | |
import java.security.DigestInputStream; |
8 | |
import java.security.MessageDigest; |
9 | |
|
10 | |
|
11 | |
|
12 | |
|
13 | 0 | public class MD5Util { |
14 | |
|
15 | |
|
16 | |
|
17 | |
|
18 | 1 | private static final char[] DIGITS_LOWER = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', |
19 | |
'e', 'f' }; |
20 | |
|
21 | |
public static String computeMD5(String input) { |
22 | 323 | if (input == null) { |
23 | 0 | return null; |
24 | |
} |
25 | |
MessageDigest digest; |
26 | |
try { |
27 | 323 | digest = MessageDigest.getInstance("MD5"); |
28 | 323 | digest.update(input.getBytes("UTF-8")); |
29 | 0 | } catch (Exception e) { |
30 | 0 | throw new UnexpectedLiquibaseException(e); |
31 | 323 | } |
32 | 323 | byte[] digestBytes = digest.digest(); |
33 | |
|
34 | 323 | String returnString = new String(encodeHex(digestBytes)); |
35 | 323 | LogFactory.getLogger().debug("Computed checksum for " + input + " as " + returnString); |
36 | 323 | return returnString; |
37 | |
|
38 | |
} |
39 | |
|
40 | |
public static String computeMD5(InputStream stream) { |
41 | |
MessageDigest digest; |
42 | |
try { |
43 | 8 | digest = MessageDigest.getInstance("MD5"); |
44 | |
|
45 | 8 | DigestInputStream digestStream = new DigestInputStream(stream, digest); |
46 | 631 | while (digestStream.read() != -1) { |
47 | |
; |
48 | |
} |
49 | 0 | } catch (Exception e) { |
50 | 0 | throw new RuntimeException(e); |
51 | 8 | } |
52 | 8 | byte[] digestBytes = digest.digest(); |
53 | |
|
54 | 8 | String returnString = new String(encodeHex(digestBytes)); |
55 | |
|
56 | 8 | LogFactory.getLogger().debug("Computed checksum for " + returnString + " as " + returnString); |
57 | 8 | return returnString; |
58 | |
} |
59 | |
|
60 | |
|
61 | |
|
62 | |
|
63 | |
|
64 | |
|
65 | |
|
66 | |
|
67 | |
|
68 | |
|
69 | |
private static char[] encodeHex(byte[] data) { |
70 | |
|
71 | 331 | int l = data.length; |
72 | |
|
73 | 331 | char[] out = new char[l << 1]; |
74 | |
|
75 | |
|
76 | 5627 | for (int i = 0, j = 0; i < l; i++) { |
77 | 5296 | out[j++] = DIGITS_LOWER[(0xF0 & data[i]) >>> 4]; |
78 | 5296 | out[j++] = DIGITS_LOWER[0x0F & data[i]]; |
79 | |
} |
80 | |
|
81 | 331 | return out; |
82 | |
} |
83 | |
|
84 | |
} |