About MD5 Encryption in Java (can be used directly)

Source: Internet
Author: User
Tags md5 encryption

This article transferred from: http://www.cnblogs.com/solove/archive/2011/10/18/2216715.html

The upper part is reproduced about the encryption of the string, the latter part is more complete, including string, file, byte array, etc.

  1. Package util;
  2. Import Java.security.MessageDigest;
  3. Public class Encript {
  4. //16 binary number-to-character mapping array
  5. Private final static string[] Hexdigits = {"0","1","2","3","4","5","6", "7","8","9","A","B","C","D","E","F"};
  6. /** Encrypt the inputstring * /
  7. public static string MD5 (string inputstr) {
  8. return encodeByMD5 (INPUTSTR);
  9. }
  10. /** 
  11. * Verify that the password you entered is correct
  12. * @param password Real password (encrypted true password)
  13. * @param inputstring Input string
  14. * @return Validation result, Boolean type
  15. */
  16. public Static boolean Authenticatepassword (String password,string inputstring) {
  17. if (Password.equals (EncodeByMD5 (inputstring))) {
  18. return true;
  19. }else{
  20. return false;
  21. }
  22. }
  23. /** MD5 Encoding of strings * /
  24. private static string EncodeByMD5 (String originstring) {
  25. if (originstring!=null) {
  26. try {
  27. //Create a summary of information with the specified algorithm name
  28. MessageDigest MD5 = messagedigest.getinstance ("MD5");
  29. //Use the specified byte array to make the last update to the summary and complete the summary calculation
  30. byte[] results = md5.digest (Originstring.getbytes ());
  31. //The resulting byte array becomes a string return
  32. String result = bytearraytohexstring (results);
  33. return result;
  34. } catch (Exception e) {
  35. E.printstacktrace ();
  36. }
  37. }
  38. return null;
  39. }
  40. /** 
  41. * Rotate byte array to hexadecimal string
  42. * @param B-byte array
  43. * @return Hexadecimal string
  44. */
  45. private static String bytearraytohexstring (byte[] b) {
  46. StringBuffer RESULTSB = new StringBuffer ();
  47. For (int i=0;i<b.length;i++) {
  48. Resultsb.append (bytetohexstring (b[i));
  49. }
  50. return resultsb.tostring ();
  51. }
  52. //Converts a byte into a string of 16 binary form
  53. private static String bytetohexstring (byte b) {
  54. int n = b;
  55. if (n<0)
  56. n=256+n;
  57. int d1 = n/;
  58. int d2 = n%;
  59. return HEXDIGITS[D1] + hexdigits[d2];
  60. }
  61. }
  62. +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
  63. Package com.angsentech.ssm.util;

    Import Java.io.File;
    Import Java.io.FileInputStream;
    Import java.io.IOException;
    Import Java.io.InputStream;
    Import java.io.UnsupportedEncodingException;
    Import Java.security.MessageDigest;
    Import java.security.NoSuchAlgorithmException;

    /**
    * MD5 Cryptographic Processing Tool class
    * @author Administrator
    *
    */

    public class Md5utils {
    /**
    * Default password string combination, used to convert bytes to 16 binary characters, Apache check the correctness of the downloaded file is the default of this combination
    */
    protected static char hexdigits[] = {' 0 ', ' 1 ', ' 2 ', ' 3 ', ' 4 ', ' 5 ', ' 6 ',
    ' 7 ', ' 8 ', ' 9 ', ' A ', ' B ', ' C ', ' d ', ' e ', ' f '};

    protected static MessageDigest messagedigest = null;
    static {
    try {
    MessageDigest = Messagedigest.getinstance ("MD5");
    } catch (NoSuchAlgorithmException Nsaex) {
    System.err.println (MD5Utils.class.getName ()
    + "Initialization failed, MessageDigest does not support Md5util. ");
    Nsaex.printstacktrace ();
    }
    }

    /**
    * Generate MD5 checksum for string
    *
    * @param s
    * @return
    */
    public static string getmd5string (string s) {
    Return getmd5string (S.getbytes ());
    }

    /**
    * Determine if the MD5 check code of the string matches a known MD5 code
    *
    * @param password
    * The string to validate
    * @param md5pwdstr
    * Known MD5 check code
    * @return
    */
    public static Boolean IsEqualsToMd5 (string password, string md5pwdstr) {
    String s = getmd5string (password);
    Return S.equals (MD5PWDSTR);
    }

    /**
    * MD5 checksum value of generated file
    *
    * @param file
    * @return
    * @throws IOException
    */
    public static String getfilemd5string (file file) throws IOException {
    InputStream fis;
    FIS = new FileInputStream (file);
    byte[] buffer = new byte[1024];
    int numread = 0;
    while ((Numread = fis.read (buffer)) > 0) {
    Messagedigest.update (buffer, 0, numread);
    }
    Fis.close ();
    Return Buffertohex (Messagedigest.digest ());
    }

    /**
    * Generate MD5 checksum value for byte array
    *
    * @param s
    * @return
    */
    public static String getmd5string (byte[] bytes) {
    Messagedigest.update (bytes);
    Return Buffertohex (Messagedigest.digest ());
    }

    private static String Buffertohex (byte bytes[]) {
    Return Buffertohex (bytes, 0, bytes.length);
    }

    private static String Buffertohex (byte bytes[], int m, int n) {
    StringBuffer StringBuffer = new StringBuffer (2 * n);
    int k = m + N;
    for (int l = m; l < K; l++) {
    Appendhexpair (Bytes[l], stringbuffer);
    }
    return stringbuffer.tostring ();
    }

    private static void Appendhexpair (Byte bt, StringBuffer StringBuffer) {
    char C0 = hexdigits[(BT & 0xf0) >> 4];//byte-high 4-bit numeric conversion, >>>
    Move to the right of the logic, move the symbol bit to the right, there is no difference between the two symbols found here
    Char C1 = HEXDIGITS[BT & 0xf];//number conversion with low 4 bits in bytes
    Stringbuffer.append (C0);
    Stringbuffer.append (C1);
    }

    /**
    * Encrypt the source string to a byte array using MD5
    * @param source
    * @return
    */
    public static byte[] Encode2bytes (String source) {
    byte[] result = NULL;
    try {
    MessageDigest MD = messagedigest.getinstance ("MD5");
    Md.reset ();
    Md.update (Source.getbytes ("UTF-8"));
    result = Md.digest ();
    } catch (NoSuchAlgorithmException e) {
    E.printstacktrace ();
    } catch (Unsupportedencodingexception e) {
    E.printstacktrace ();
    }

    return result;
    }

    /**
    * Use MD5 to encrypt the source string to 32-bit 16 binary number
    * @param source
    * @return
    */
    public static string Encode2hex (string source) {
    byte[] data = encode2bytes (source);
    StringBuffer hexstring = new StringBuffer ();
    for (int i = 0; i < data.length; i++) {
    String hex = integer.tohexstring (0xFF & Data[i]);

    if (hex.length () = = 1) {
    Hexstring.append (' 0 ');
    }

    Hexstring.append (hex);
    }

    return hexstring.tostring ();
    }

    /**
    * Verify string matches
    * @param unknown string to be validated
    * @param okhex using MD5 encrypted 16 binary string
    * @return Match returns True, mismatch returns false
    */
    public static Boolean validate (string unknown, string okhex) {
    Return Okhex.equals (Encode2hex (unknown));
    }
    }

About MD5 Encryption in Java (can be used directly)

Related Article

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.