Home > 类库下载 > java类库 > java MD5 encryption algorithm

java MD5 encryption algorithm

高洛峰
Release: 2016-11-05 10:18:21
Original
1760 people have browsed it

 MD5 (Message Digest Algorithm 5), translated as the fifth edition of the message digest algorithm. According to convention, we reason that there may also be historical versions with names like MD2 and MD3...

Even if we don’t understand the principles of this algorithm at all, we can We can see some clues from the naming. The so-called abstract is a short summary. Like the graduation thesis I wrote, the first part is the abstract. It makes a short and powerful summary of the long article that follows. In fact, the role of MD5 It also smells like this. Let's look at a text describing the function of the MD5 algorithm:

The function of MD5 is to allow large-capacity information to be "compressed" into a confidential format (that is, before using digital signature software to sign the private key). Convert a byte string of any length into a large integer of a certain length), which is mainly used to ensure the integrity and consistency of data transmission.

Suppose A wants to send a text file to B in the distance, with 1 million words. When B receives the file, how does he know whether the file has been tampered with during the transmission? It would not be good if someone intercepted and tampered with the file content. At this time, MD5 comes in handy. No matter No matter how big the file is, it will get a fixed-length string after MD5 encryption, usually 32 bits. At this time, A first encrypts the file with MD5, and the obtained string of ciphertext is also passed to B. When B receives it, file, also use MD5 to encrypt the file to see if the ciphertext obtained is consistent with the one sent by A. If it is consistent, it means that the file is safe. This ensures the integrity of the data transmission.

In fact, we When downloading files from the Internet, sometimes there is a MD5 ciphertext behind the downloaded file, such as MD5 (e8027a87676ea48b3a3c9b0a4d8d87a0), which has a similar function to the example I gave above (I think so...).

MD5 is a public irreversible algorithm, which means that there is no way to directly crack the ciphertext to obtain the source data information. MD5 can encrypt a file of any size and obtain a unique 32-bit string.

After briefly understanding the functions of MD5, you can look at the code directly.

Java code implements MD5 encryption

package com.wang.encryption;
import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
import java.security.MessageDigest;
/**
 * @author yogo.wang
 * @date 2016/11/04-下午1:02.
 */
public class MD5Test {
    public static String md5Encode(String msg) throws Exception{

        byte[] msgBytes = msg.getBytes("utf-8");
        /**
         * 声明使用Md5算法,获得MessaDigest对象
         */
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        /**
         * 使用指定的字节更新摘要
         */
        md5.update(msgBytes);
        /**
         * 完成哈希计算,获得密文
         */
        byte[] digest = md5.digest();
        /**
         * 以上两行代码等同于 byte[] digest = md5.digest(msgBytes);
         */
        return bytesToHexString(digest);
    }
    /**
     * 将byte数组转化为16进制字符串形式
     * @param bys
     * @return
     */
    public static String byteArr2hexString(byte[] bys){
        StringBuffer hexVal=new StringBuffer();
        int val=0;
        for (int i = 0; i < bys.length; i++) {
            //将byte转化为int  如果byte是一个负数就必须要和16进制的0xff做一次与运算
            val=((int)bys[i]) & 0xff;
            if(val<16){
                hexVal.append("0");
            }
            hexVal.append(Integer.toHexString(val));
        }

        return hexVal.toString();

    }

    public static void main(String[] args) throws Exception {
        String msg="helloworld";
        String result=md5Encode(msg);
        String result1=md5Encode(msg);
        System.out.println(result);
        System.out.println(result1);
    }

}
Copy after login

Run the code and the output results are as follows:

fc5e038d38a57032085441e7fe7010b0
fc5e038d38a570320 85441e7fe7010b0

 It can be seen that the same field is Encryption, the ciphertext obtained is always consistent. Next, let’s take a look at the principles and applications of MD5 implementation.

MD5 implementation principles and applications

I looked at some md5 encryption codes implemented by some friends online, and I can only say half of them. If you don’t know much about it, here is an introduction to some implementation steps on the Internet (just take a look). The principle of the MD5 algorithm is mainly divided into the following steps,

 1) Filling: First, enter the input The length (bit) of the information is padded so that the remainder of 512 is equal to 448. The filling method is to fill a 1 and n 0s.

 2) Record information length: Use 64 bits to store the information length before filling. These 64 bits are added after the result of the first step, so that the information length becomes N*512+448+64=(N+1)*512 bits.


 3) Load the standard magic number: The standard magic number is (A=(01234567)16, B=(89ABCDEF)16, C=(FEDCBA98)16, D=(76543210)16). If defined in the program, it should be (A=0X67452301L, B=0XEFCDAB89L, C=0X98BADCFEL, D=0X10325476L).


 4) Four rounds of loop operation: the number of loops is the number of groups (N+1).



Here we mainly introduce the MessageDigest class in java. Check the jdk development document. You can see that this class is located under the java.security package. The document describes MessageDigest as follows:

public abstract class MessageDigest
    extends MessageDigestSpi
Copy after login


This MessageDigest Class provides applications with the functionality of message digest algorithms, such as MD5 or SHA algorithms. A message digest is a secure one-way hash function that accepts data of any size and outputs a fixed-length hash value.


The MessageDigest object begins to be initialized. This object processes data using the update method. The digest can be reset at any time by calling the reset method. Once all the data that needs to be updated has been updated, one of the digest methods should be called to complete the hash calculation.

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

Implementers can choose whether to implement the Cloneable interface at will. Client applications can test reproducibility by trying to copy and catching CloneNotSupportedException:

 MessageDigest md = MessageDigest.getInstance("SHA");
 try {
     md.update(toChapter1);
     MessageDigest tc1 = md.clone();
     byte[] toChapter1Digest = tc1.digest();
     md.update(toChapter2);
     ...etc.
 } catch (CloneNotSupportedException cnse) {
     throw new DigestException("couldn&#39;t make digest of partial content");
 }
Copy after login

Note that if a given implementation is not reproducible and the number of digests is known in advance, it will still be able to be computed by instantiating several instances Intermediate summary.

  The functions of the main methods have been given in the comments of the above code and will not be introduced here.

  The application fields of MD5 can be mainly divided into the following categories:



1. Prevent tampering ( File integrity verification), for example, if I provide file downloads, in order to prevent criminals from adding Trojans to the installation program, I can publish the MD5 output results obtained from the installation file on the website.

2. Prevent direct viewing of plain text (password encryption). Nowadays, many websites store the MD5 value of the user's password in the database when storing the user's password. In this way, even if criminals obtain the MD5 value of the user password in the database, they will not be able to know the user's password.

3. Prevent repudiation (digital signature). For example, A writes a file, and the certification authority uses the MD5 algorithm to generate summary information for the file and keep a record. This can prevent trouble caused by A not admitting the matter in the future.

Although MD5 is an irreversible algorithm, it does not mean that it cannot be cracked. Most users will use fields with special meaning when setting passwords, such as birthday, abbreviated name, etc. If I put your relevant information, guess the passwords you may use, and then encrypt them all with MD5 to get a lot of ciphertext, and then get the ciphertext of your password and compare it one by one with my ciphertext library. If the ciphertext If it matches, then your password itself will be self-defeating. In the same way, many websites now provide some online MD5 value query functions. After entering the MD5 password value, if it exists in the database, it can be easily Get the password value quickly. The same principle applies. For example, in the above code, I encrypted the string "helloworld" with MD5. In theory, you only know the ciphertext and it is impossible to crack my original data, but in fact it is really Is that so? Let’s take a look at a website http://pmd5.com/

java MD5 encryption algorithm

After I entered the ciphertext generated by the above code, the website was cracked immediately, and the principle is very simple.

 More about MD5 For detailed text information, you can go to Baidu Encyclopedia. The introduction is quite detailed and worth reading.


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template