Java comes with cryptography class MessageDigest class (Encryption MD5 and SHA)

Source: Internet
Author: User
Tags md5 digest



Java comes with Data encryption class MessageDigest (MD5 or SHA encryption)

Description
In the website, in order to protect the website member's user name and the password and so on privacy information, therefore we in the user registers the direct MD5 way or other way encrypts, even if is the database administrator also cannot view this member's password and so on information, View the password effect in the database such as: 8e830882f03b2cb84d1a657f346dd41a effect.
Because the MD5 algorithm is not reversible, so it is widely used by many websites,

Three commonly used encryption methods
Method One: Use the bitwise operator to convert the encrypted data into 16 binary
Mode two: Use the format to convert the encrypted data into 16 binary (recommended)
Method Three: Use the algorithm to convert the encrypted data into 16 binary


import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
  
/ **
 * Use the MessageDigest class that comes with Java
 * @author xiaokui
 * /
public class EncryptionUtil {
  
    / **
     * Since MD5 and SHA-1 are both developed from MD4, their structure and strength have many similarities.
     * The biggest difference between SHA-1 and MD5 is that the digest is 32 bits longer than the MD5 digest (1byte = 8bit, which is equivalent to 4bytes in length, and 8 characters longer than MD5 after hex conversion).
     * For brute force attacks: MD5 is an operation on the order of 2128, and SHA-1 is an operation on the order of 2160.
     * For the difficulty of two messages with the same digest: MD5 is 264 is an operation of the order of magnitude, and SHA-1 is an operation of the order of 280 orders of magnitude.
     * Therefore, SHA-1 is more powerful against brute force attacks. But because SHA-1 has more loop steps than MD5 (80:64) and a larger cache (160 bits: 128 bits) to be processed, SHA-1 runs slower than MD5.
     *
     * @param source string to be encrypted
     * @param hashType encryption type (MD5 and SHA)
     * @return
     * /
    public static String getHash (String source, String hashType) {
        // character used to convert bytes into hexadecimal representation
        char hexDigits [] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
  
        try {
            MessageDigest md = MessageDigest.getInstance (hashType);
            md.update (source.getBytes ()); // Update the summary of the specified byte array by using the update method to process the data (why do you need to use the update method first? Why not use some of the md5 methods?)
            byte [] encryptStr = md.digest (); // Obtain the ciphertext and complete the hash calculation to produce a 128-bit long integer
            char str [] = new char [16 * 2]; // If each byte is represented in hexadecimal, use two characters
            int k = 0; // the corresponding character position in the conversion result
            for (int i = 0; i <16; i ++) {// starting from the first byte, for each byte, convert to hexadecimal characters
                byte byte0 = encryptStr [i]; // take the i-th byte
                str [k ++] = hexDigits [byte0 >>> 4 & 0xf]; // Take the upper 4 digits of the byte conversion, >>> is a logical right shift, and the sign bits are shifted right together
                str [k ++] = hexDigits [byte0 & 0xf]; // convert the lower 4 digits of the byte
            }
            return new String (str); // convert the result to a string
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace ();
        }
        return null;
    }
  
    / ** @param source string to be encrypted
     * @param hashType encryption type (MD5 and SHA)
     * @return
     * /
    public static String getHash2 (String source, String hashType) {
        StringBuilder sb = new StringBuilder ();
        MessageDigest md5;
        try {
            md5 = MessageDigest.getInstance (hashType);
            md5.update (source.getBytes ());
            for (byte b: md5.digest ()) {
                sb.append (String.format ("% 02X", b)); // Decimal to hexadecimal, X means output in hexadecimal form, 02 means less than two digits followed by 0.
            }
            return sb.toString ();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace ();
        }
        return null;
    }
  
    / ** @param source string to be encrypted
     * @param hashType encryption type (MD5 and SHA)
     * @return
     * /
    public static String getHash3 (String source, String hashType) {
        // character used to convert bytes into hexadecimal representation
        char hexDigits [] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
          
        StringBuilder sb = new StringBuilder ();
        MessageDigest md5;
        try {
            md5 = MessageDigest.getInstance (hashType);
            md5.update (source.getBytes ());
            byte [] encryptStr = md5.digest ();
            for (int i = 0; i <encryptStr.length; i ++) {
                int iRet = encryptStr [i];
                if (iRet <0) {
                    iRet + = 256;
                }
                int iD1 = iRet / 16;
                int iD2 = iRet% 16;
                sb.append (hexDigits [iD1] + "" + hexDigits [iD2]);
            }
            return sb.toString ();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace ();
        }
        return null;
    }
  
    public static void main (String [] args) {
        System.out.println (getHash ("小 奎", "MD5"));
        System.out.println (getHash ("小 奎", "SHA") + "\ n");
  
        System.out.println (getHash2 ("小 奎", "MD5"));
        System.out.println (getHash2 ("小 奎", "SHA") + "\ n");
  
        System.out.println (getHash3 ("小 奎", "MD5"));
        System.out.println (getHash3 ("小 奎", "SHA") + "\ n");
    }
  
}


Output results


    1. 8e830882f03b2cb84d1a657f346dd41a
    2. 0ba5512371d00c86e91712f44aab7138
    3. 8e830882f03b2cb84d1a657f346dd41a
    4. 0ba5512371d00c86e91712f44aab713898745f91
    5. 8e830882f03b2cb84d1a657f346dd41a
    6. 0ba5512371d00c86e91712f44aab713898745f91



We found that 3 methods performed the same, with SHA lengths of 8 characters (32 bits) more than MD5






Java comes with cryptography class MessageDigest class (Encryption MD5 and SHA)


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.