MD5 encryption algorithm characteristics and simple implementation (Java)

MD5 encryption and simple implementation (Java)

I need to use irreversible encryption of user passwords in my own study projects to ensure the security of user accounts. Write this article to record the simple implementation of the MD5 encryption algorithm.


What is MD5

MD5 stands for Message-Digest Algorithm 5 (message-digest algorithm 5), which is used to ensure complete and consistent information transmission. It is one of the hash algorithms widely used by computers (also translated digest algorithm and hash algorithm). Nowadays, mainstream programming languages ​​are generally used. There is an implementation of MD5.

The basic principle of the hash algorithm is: to calculate data (such as Chinese characters) into another fixed length value.


Features of MD5 encryption

  • Compressibility : It can return a fixed-length MD5 encrypted string for data, strings, etc. to be encrypted with different lengths. (Usually a 32-bit hexadecimal string);
  • Encryption is irreversible : The encryption process is almost irreversible. Unless a huge Key-Value database is maintained for collision cracking, it is almost impossible to unlock.
  • Easy to calculate : It is easy to calculate the MD5 value from the original data.
  • Anti-modification : For a fixed string. Numbers, etc., the string after MD5 encryption is fixed, which means that no matter how many times MD5 is encrypted, the same result will be obtained. And if one of the bytes is modified, the MD5 value obtained varies greatly.
  • Strong anti-collision : Knowing the original data and its MD5 value, it is very difficult to find a data with the same MD5 value (ie, fake data).

Based on the above characteristics of MD5, it is often used as an encryption processing algorithm for user passwords and other important data applicable to irreversible encryption .


MD5 encryption of the string

1. Simple implementation, no processing

/**
 * 对字符串进行MD5加密
 * @param str 需要进行加密的字符串
 * @return		md5加密后的字符串
 */
public String pwByMD5(String str){
    
    
    try {
    
    
        // 生成一个MD5加密计算摘要
        MessageDigest md = MessageDigest.getInstance("MD5");
        //调用md5函数计算
        md.update(str.getBytes());
        
        /** 
         * digest()最后确定返回md5 hash值,返回值为8位字符串。
         * BigInteger函数则将8位的字符串转换成16位hex值,以字符串表示;
         * 一个byte是八位二进制,即2位十六进制字符(2的8次方等于16的2次方)
         */
        return new BigInteger(1,md.digest()).toString(16);
    } catch (NoSuchAlgorithmException e) {
    
    
        e.printStackTrace();
        return null;
    }
}

The above is a simple implementation and notes of the MD5 algorithm. If there is further and in-depth implementation of the algorithm in the future, it will be updated again...

Guess you like

Origin blog.csdn.net/weixin_40849588/article/details/98469677