MD5 hash value encryption

Ordinary is just two words: lazy and lazy;
Success is just two words: hard work and diligence;
Excellent is just two words: you and me.
Follow me to learn JAVA, spring family bucket and linux operation and maintenance from 0, take you from an ignorant teenager to the peak of your life, and marry Bai Fumei!
Follow wechat official account [IT is very reliable] and share technical experience every day~

 

MD5 hash value encryption

1 md5 encryption introduction

MD5 (message digest algorithm 5), the fifth edition of message digest algorithm, is a widely used cryptographic hash function. It can be used in digital signature, password encryption storage and other scenarios.

The basic principle of hash algorithm is to convert data (such as a text) into a fixed length (16 bytes) byte array. MD5 can generate a 128 bit (16 byte) hash value to ensure the integrity and consistency of the transmitted information.

Through encapsulation, each byte of 16 byte hash value can be converted into hexadecimal number (each byte corresponds to 2-bit hexadecimal number), so the final length of hexadecimal number string is 32 bits!

 

2 md5 encryption features

MD5 algorithm has the following characteristics:

(1) compressibility: for data of any length, the length of MD5 value obtained by operation is fixed (128 binary bits, 16 bytes);

(2) easy calculation: it is easy to calculate the corresponding MD5 value from the original data;

(3) modification resistance: for any change to the original data (even if only one character is modified), the calculated MD5 value is different (in extreme cases, the same value will exist);

(4) irreversibility: knowing the MD5 value cannot deduce the original data. MD5 message digest is irreversible, and its main function is to verify the consistency and integrity of information.

 

3 MD5 encryption tool class

import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import lombok.extern.slf4j.Slf4j;

/**
 * MD5 Hash value calculation tool class
 */
@Slf4j
public class Md5Util {

  /**
   * 16 Hexadecimal character
   */
  private static final char[] HEX_DIGIT = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};

  /**
   * Thread shared variable
   */
  private static ThreadLocal<MessageDigest> digesterContext = new ThreadLocal<>();

  /**
   * initialization
   */
  private static MessageDigest init() {
    MessageDigest digester = null;
    try {
      digester = digesterContext.get();
      if (digester == null) {
        digester = MessageDigest.getInstance("MD5");
        digesterContext.set(digester);
      }
      digester.reset();
      return digester;
    } catch (NoSuchAlgorithmException e) {
      log.error(e.getMessage(), e);
      throw new IllegalStateException("doesn't support MD5 algorithm");
    } catch (Exception e) {
      log.error(e.getMessage(), e);
      throw new IllegalStateException("init exception");
    }
  }

  /**
   * md5 Encryption, default UTF-8 encoding
   */
  public static String md5(String str) {
    if (str == null) {
      return null;
    }
    MessageDigest digester = init();
    return bytes2String(digester.digest(str.getBytes(StandardCharsets.UTF_8)));
  }

  /**
   * md5 Encryption, specifying the encoding type
   */
  public static String md5(String text, String encoding) {
    if (text == null) {
      return null;
    }
    MessageDigest digester = init();
    try {
      return bytes2String(digester.digest(text.getBytes(encoding)));
    } catch (UnsupportedEncodingException e) {
      log.error(e.getMessage(), e);
      throw new IllegalStateException("doesn't support encoding");
    }
  }

  /**
   * byte Convert array to hexadecimal string
   */
  private static String bytes2String(byte[] bytes) {
    if (bytes == null || bytes.length == 0) {
      return "";
    }
    StringBuilder sb = new StringBuilder();
    for (byte b : bytes) {
      sb.append(byte2Hex(b));
    }
    return sb.toString();
  }

  /**
   * Convert a single byte to a hexadecimal string
   */
  private static String byte2Hex(byte ib) {
    char[] ob = new char[2];
    ob[0] = HEX_DIGIT[(ib >>> 4) & 0X0F];
    ob[1] = HEX_DIGIT[ib & 0X0F];
    return new String(ob);
  }

  public static void main(String[] args) {
    String content = "Follow wechat official account: IT Very reliable";
    String md5Str = Md5Util.md5(content, "UTF-8");
    log.info("md5 Before encryption:{}", content);
    log.info("md5 After encryption:{}", md5Str);
  }
}

4 MD5 encryption test results

If you have any questions or need technical support, follow the official account and contact me~

 

Tags: Java Encryption

Posted by sabien on Fri, 06 May 2022 05:22:54 +0300