DigestUtil.java 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. package com.malk.server.xbongbong;
  2. import java.io.UnsupportedEncodingException;
  3. import java.security.MessageDigest;
  4. import java.security.NoSuchAlgorithmException;
  5. /**
  6. * 签名工具类
  7. */
  8. public class DigestUtil {
  9. /**
  10. * parameter strSrc is a string will be encrypted,
  11. * parameter encName is the algorithm name will be used.
  12. * encName dafault to "MD5"
  13. *
  14. * @throws UnsupportedEncodingException
  15. */
  16. public static String Encrypt(String strSrc, String encName) {
  17. MessageDigest md = null;
  18. String strDes = null;
  19. try {
  20. byte[] bt = strSrc.getBytes("utf-8");
  21. if (encName == null || encName.equals("")) {
  22. encName = "MD5";
  23. }
  24. md = MessageDigest.getInstance(encName);
  25. md.update(bt);
  26. strDes = bytes2Hex(md.digest()); // to HexString
  27. } catch (UnsupportedEncodingException e) {
  28. System.out.println("UnsupportedEncodingException.");
  29. return null;
  30. } catch (NoSuchAlgorithmException e) {
  31. System.out.println("Invalid algorithm.");
  32. return null;
  33. }
  34. return strDes;
  35. }
  36. public static String bytes2Hex(byte[] bts) {
  37. String des = "";
  38. String tmp = null;
  39. for (int i = 0; i < bts.length; i++) {
  40. tmp = (Integer.toHexString(bts[i] & 0xFF));
  41. if (tmp.length() == 1) {
  42. des += "0";
  43. }
  44. des += tmp;
  45. }
  46. return des;
  47. }
  48. public static void main(String[] args) throws UnsupportedEncodingException {
  49. String strSrc = "可以加密汉字.Oh,and english";
  50. System.out.println("Source String:" + strSrc);
  51. System.out.println("Encrypted String:");
  52. System.out.println("Use Def:" + DigestUtil.Encrypt(strSrc, null));
  53. System.out.println("Use MD5:" + DigestUtil.Encrypt(strSrc, "MD5"));
  54. System.out.println("Use SHA-1:" + DigestUtil.Encrypt(strSrc, "SHA-1"));
  55. System.out.println("Use SHA-256:" + DigestUtil.Encrypt(strSrc, "SHA-256"));
  56. }
  57. }