A concise Java class that implements MD5

Source: Internet
Author: User
Because of the uniqueness and irreversibility of message digest, it is a simple and commonly used encryption method, for example, you can use MD5 to encrypt the user password in your application.

  1. Package test;
  2. Import Java.security.MessageDigest;
  3. /**
  4. * <p>title: </p>
  5. * <p>description: </p>
  6. * <p>copyright:copyright (c) 2003</p>
  7. * <p>company: </p>
  8. * @author unascribed
  9. * @version 1.0
  10. */
  11. public class Stringutil {
  12. Private final static string[] Hexdigits = {
  13. "0", "1", "2", "3", "4", "5", "6", "7",
  14. "8", "9", "a", "B", "C", "D", "E", "F"};
  15. /**
  16. * Convert byte array to 16 string
  17. * @param B-byte array
  18. * @return 16 string
  19. */
  20. public static String bytearraytohexstring (byte[] b) {
  21. StringBuffer RESULTSB = new StringBuffer ();
  22. for (int i = 0; i < b.length; i++) {
  23. Resultsb.append (bytetohexstring (b[i));
  24. }
  25. return resultsb.tostring ();
  26. }
  27. private static String bytetohexstring (Byte b) {
  28. int n = b;
  29. if (n < 0)
  30. n = 256 + N;
  31. int D1 = N/16;
  32. int d2 = n% 16;
  33. return HEXDIGITS[D1] + HEXDIGITS[D2];
  34. }
  35. public static string Md5encode (string origin) {
  36. String resultstring = null;
  37. try {
  38. Resultstring=new String (origin);
  39. MessageDigest MD = messagedigest.getinstance ("MD5");
  40. Resultstring=bytearraytohexstring (Md.digest (Resultstring.getbytes ()));
  41. }
  42. catch (Exception ex) {
  43. }
  44. return resultstring;
  45. }
  46. public static void Main (string[] args) {
  47. System.err.println (Md5encode ("a"));
  48. }
  49. }


In RFC 1321, the test suite is given to verify that your implementation is correct:

MD5 ("") = d41d8cd98f00b204e9800998ecf8427e
MD5 ("a") = 0cc175b9c0f1b6a831c399e269772661
MD5 ("abc") = 900150983cd24fb0d6963f7d28e17f72
MD5 ("message digest") = F96b697d7cb7938d525a2f31aaf161d0
MD5 ("abcdefghijklmnopqrstuvwxyz") = c3fcd3d76192e4007dfb496cca67e13b



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.