Java's built in encryption class MessageDigest class code example

  • 2020-11-25 07:14:17
  • OfStack

MessageDigest class

The MessageDigest class provides the functionality of an information summary algorithm for an application, such as the MD5 or SHA algorithm. An information digest is a secure one-way hash function that receives arbitrary data sizes and outputs a fixed length hash value.

The MessageDigest object begins to be initialized. This object processes the data by using the update () method. The reset () method can be called at any time to reset the summary. Once all the data that needs to be updated has been updated, the digest() method 1 should be called to complete the hash.

The digest method can only be called once for a given amount of updated data. After calling digest, the MessageDigest object is reset to its original state.

Description:

On the site, in order to protect the members of the privacy information such as the user name and password, so we can directly when user registration MD5 encrypted way or the other way, even the database administrator can't view the member's information such as password, check the password in the database effect such as: 8 e830882f03b2cb84d1a657f346dd41a effect.

Because the MD5 algorithm is irreversible, it is widely used by many websites.

Three commonly used encryption methods

Option 1: Convert the encrypted data to hexadecimal using the bit operator
Method 2: Convert the encrypted data into hexadecimal using formatting (recommended)
Method 3: Convert the encrypted data into hexadecimal using an algorithm


import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/** 
 *  use Java built-in MessageDigest class  
 * @author xiaokui 
 */
public class EncryptionUtil {
	/** 
  *  Due to the MD5  with SHA-1 Both from MD4  Developed, they have a lot in common in such properties as structure and strength  
  * SHA-1 with MD5  The biggest difference lies in its summary ratio MD5  In the long  32  Bits ( 1byte=8bit , equivalent to the length of 4byte , the transformation 16 Than after into the system MD5 more 8 Three characters).  
  *  For forcible attack, : MD5  is 2128  An order of magnitude operation, SHA-1  is 2160 An operation of orders of magnitude.  
  *  Difficulty for two messages with the same abstract: MD5 is  264  It's an order of magnitude operation, SHA-1  is 280  An operation of orders of magnitude.  
  *  As a result, SHA-1  The intensity of a forced attack is greater.   But as a result of SHA-1  The cyclic step ratio MD5  More than ( 80:64 ) and the cache to be processed is large ( 160  The bit :128  Bits), SHA-1  Running speed ratio MD5  Slow.  
  * 
  * @param source  String that needs to be encrypted  
  * @param hashType  Encryption type   ( MD5  and  SHA )  
  * @return 
  */
	public static String getHash(String source, String hashType) {
		//  Used to convert bytes to  16  The character represented in base  
		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());
			//  Through the use of  update  Methods To process data , Make the specified  byte Array update summary  
			byte[] encryptStr = md.digest();
			//  Obtain ciphertext to complete the hash calculation , produce 128  Long integer of bits  
			char str[] = new char[16 * 2];
			//  Per byte  16  In base case, use two characters  
			int k = 0;
			//  Represents the corresponding character position in the conversion result  
			for (int i = 0; i < 16; i++) {
				//  From the first 1 Start with 2 bytes, for each 1 bytes , Converted to  16  Conversion of base characters  
				byte byte0 = encryptStr[i];
				//  Take the first  i  bytes  
				str[k++] = hexDigits[byte0 >>> 4 & 0xf];
				//  Takes the height of a byte  4  Digit conversion of bits , >>>  Move the symbol bit to the right of the logic 1 The moves to the right  
				str[k++] = hexDigits[byte0 & 0xf];
				//  Take the low in the byte  4  Digit conversion of bits 
			}
			return new String(str);
			//  The result is converted to a string 
		}
		catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return null;
	}
	/** @param source  String that needs 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));
				// 10 Turn into the system 16 Into the system, X  Said to 106 Output in base form, 02  Indicates insufficient two front fill 0 The output 
			}
			return sb.toString();
		}
		catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return null;
	}
	/** @param source  String that needs to be encrypted  
  * @param hashType  Encryption type   ( MD5  and  SHA )  
  * @return 
  */
	public static String getHash3(String source, String hashType) {
		//  Used to convert bytes to  16  The character represented in base  
		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(" Small, carlos ", "MD5"));
		System.out.println(getHash(" Small, carlos ", "SHA") + "\n");
		System.out.println(getHash2(" Small, carlos ", "MD5"));
		System.out.println(getHash2(" Small, carlos ", "SHA") + "\n");
		System.out.println(getHash3(" Small, carlos ", "MD5"));
		System.out.println(getHash3(" Small, carlos ", "SHA") + "\n");
	}
}

The output


 8e830882f03b2cb84d1a657f346dd41a 
 0ba5512371d00c86e91712f44aab7138 
 
 8E830882F03B2CB84D1A657F346DD41A 
 0BA5512371D00C86E91712F44AAB713898745F91 
 
 8e830882f03b2cb84d1a657f346dd41a 
 0ba5512371d00c86e91712f44aab713898745f91 

We found that all three methods performed the same, with SHA 8 more characters (32 bits) than MD5

conclusion

That's the end of this article on Java's built-in encryption class MessageDigest class code examples, I hope to help you. If there is any deficiency, please let me know.


Related articles: