MD5Util.java 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. /*
  2. * FileName:MD5Util.java
  3. * <p>
  4. * Copyright (c) 2017-2020, <a href="http://www.webcsn.com">hermit (794890569@qq.com)</a>.
  5. * <p>
  6. * Licensed under the GNU General Public License, Version 3 (the "License");
  7. * you may not use this file except in compliance with the License.
  8. * You may obtain a copy of the License at
  9. * <p>
  10. * http://www.gnu.org/licenses/gpl-3.0.html
  11. * <p>
  12. * Unless required by applicable law or agreed to in writing, software
  13. * distributed under the License is distributed on an "AS IS" BASIS,
  14. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. * See the License for the specific language governing permissions and
  16. * limitations under the License.
  17. *
  18. */
  19. package cn.com.lzt.common.util;
  20. import java.security.MessageDigest;
  21. public class MD5Util {
  22. private static String byteArrayToHexString(byte b[]) {
  23. StringBuffer resultSb = new StringBuffer();
  24. for (int i = 0; i < b.length; i++)
  25. resultSb.append(byteToHexString(b[i]));
  26. return resultSb.toString();
  27. }
  28. private static String byteToHexString(byte b) {
  29. int n = b;
  30. if (n < 0)
  31. n += 256;
  32. int d1 = n / 16;
  33. int d2 = n % 16;
  34. return hexDigits[d1] + hexDigits[d2];
  35. }
  36. public static String MD5Encode(String origin, String charsetname) {
  37. String resultString = null;
  38. try {
  39. resultString = new String(origin);
  40. MessageDigest md = MessageDigest.getInstance("MD5");
  41. if (charsetname == null || "".equals(charsetname))
  42. resultString = byteArrayToHexString(md.digest(resultString
  43. .getBytes()));
  44. else
  45. resultString = byteArrayToHexString(md.digest(resultString
  46. .getBytes(charsetname)));
  47. } catch (Exception exception) {
  48. }
  49. return resultString;
  50. }
  51. public static String getMD5Code(String origin) {
  52. String resultString = null;
  53. try {
  54. resultString = new String(origin);
  55. MessageDigest md = MessageDigest.getInstance("MD5");
  56. resultString = byteArrayToHexString(md.digest(resultString
  57. .getBytes("utf-8")));
  58. } catch (Exception exception) {
  59. }
  60. return resultString;
  61. }
  62. private static final String hexDigits[] = { "0", "1", "2", "3", "4", "5",
  63. "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };
  64. }