Java Encryption algorithm summary--MD5 encryption algorithm

Source: Internet
Author: User
Tags base64 md5 encryption



The previous article collated the BASE64 algorithm of the relevant knowledge, strictly speaking, Base64 can only be regarded as a coding method rather than encryption algorithm, this article to tidy up a widely used encryption algorithm---MD5.


Easy to understand


MD5 (Message Digest algorithm 5), translated by the fifth version of the Message digest algorithm, according to the Convention, we reasoned that there might also be a historical version of md2,md3 such a name.



Even if you do not understand the principle of the algorithm, we can also see from the name of some eyebrows, the so-called summary, is a short summary, like I wrote the graduation thesis, up to the first part is a summary, it on the back of a lengthy article made a brief and powerful summary, in fact, the role of MD5 is a bit like this flavor, Let's take a look at the text describing the function of the MD5 algorithm:


 MD5 's role is to allow bulk information to be "compressed" into a confidential format before signing a private key with a digital signature software (that is, converting an arbitrary-length byte string into a long, large integer), which is primarily used to ensure the integrity and consistency of data transmission.


Suppose a to send a text file to a distant B, there are 1 million words, when B received the file, how to know that the file on the way to pass over has been tampered with, if someone cut and tampered with the contents of the file in the middle of it is not very good, this time MD5 come in handy, no matter how big the file, Through MD5 encryption will get a fixed-length string, usually 32-bit, this time a first file with MD5 encryption, get a string of ciphertext by the way also passed to B, when B received the file, the same file with MD5 encryption, see if the ciphertext and a pass over the same, if consistent, Indicates that the file is secure. This ensures the integrity of the data transfer.



In fact, when we download the file from the network, sometimes the downloaded file has a section of MD5, such as MD5 (E8027A87676EA48B3A3C9B0A4D8D87A0), the role and the above I give examples similar (I think this is ...).



MD5 is an open and irreversible algorithm, meaning that there is no way to directly crack the ciphertext to get the source data information, MD5 can encrypt an arbitrary size file, get a unique 32-bit string.



Simply understand the MD5 function, you can directly see the code.


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 PM.
 */
Public class MD5Test {
    Public static String md5Encode(String msg) throws Exception{

        Byte[] msgBytes = msg.getBytes("utf-8");
        /**
         * Declare using the Md5 algorithm to get the MessaDigest object
         */
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        /**
         * Update summary with the specified bytes
         */
        Md5.update(msgBytes);
        /**
         * Complete the hash calculation and get the ciphertext
         */
        Byte[] digest = md5.digest();
        /**
         * The above two lines of code are equivalent to byte[] digest = md5.digest(msgBytes);
         */
        Return bytesToHexString(digest);
    }
    /**
     * Convert byte array to hex string
     * @param bys
     * @return
     */
    Public static String byteArr2hexString(byte[] bys){
        StringBuffer hexVal=new StringBuffer();
        Int val=0;
        For (int i = 0; i < bys.length; i++) {
            / / Convert byte to int If byte is a negative number must be done with the hexadecimal 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);
    }

} 


Running the code, the resulting output is as follows:


Fc5e038d38a57032085441e7fe7010b0
Fc5e038d38a57032085441e7fe7010b0


Visible, the same field is encrypted, the resulting ciphertext is always consistent. Let's take a look at the principle and application of MD5 implementation.


MD5 realization Principle and application


I saw some friends on the net to achieve their own MD5 encryption code, can only say half-knowledge half-solution, here posted, some of the implementation of the network on the introduction of the steps (casually look at it).


The principle of MD5 algorithm is mainly divided into the following steps,

1) Fill: First fill in the length of the input information (bit), so that the result of 512 redundancy equals 448. The padding method is to populate a 1 and N 0.

2) record information length: Use 64 bits to store the pre-fill information length. These 64 bits are added to the back 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 the definition in the program should be (A=0X67452301L,B=0XEFCDAB89L,C=0X98BADCFEL,D=0X10325476L).

4) Four-wheel loop operation: The number of cycles is the number of packets (n+1).


Here is the main introduction, Java MessageDigest This class, review the development documentation of the JDK, you can see that the class is located under the java.security Package, the document describes the MessageDigest as follows:



Public abstract class MessageDigest



Extends Messagedigestspi



This messagedigest class provides the application with an information digest algorithm, such as the MD5 or SHA algorithm. The information digest is a secure, one-way hash function that receives data of any size and outputs a fixed-length hash value.



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



Thedigest method can only be called once for a given number of updated data. after the digest is called, the MessageDigest object is reset to its initial state.



Implementations are free to choose whether to implement the Cloneable interface. The client application can replicate by trying to replicate and capture clonenotsupportedexception tests:



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 ' t make Digest of partial content");



}



Note that if the given implementation is non-replicable and the number of summaries is known beforehand, the Intermediate digest can still be computed by instantiating several instances.



The function of the main method is given in the comments in the above code and is not introduced here.



MD5 's application areas can be divided into the following categories:


1, to prevent tampering (file integrity verification), such as I provide file download, in order to prevent the illegal elements in the installation program to add Trojan, I can publish on the website by the installation files obtained by the MD5 output results.

2, to prevent direct access to clear text (password encryption), now many websites in the database store user's password when the user password is stored MD5 value. This way even if the criminals get the MD5 value of the user password of the database, they cannot know the user's password.

3, to prevent repudiation (digital signature), such as a write a file, the certification authority for this file using the MD5 algorithm to generate summary information and record. This will prevent the trouble of not admitting it later.


Although MD5 is an irreversible algorithm, but does not mean that it is not cracked, most users will use a special field to set passwords, such as birthdays, names, and so on, if I put your relevant information, guess what you might use the password, and then put them all with MD5 encryption again, Get a lot of ciphertext, and then get your password cipher and my secret library in one by one contrast, if the cipher can match, then your password itself is self-defeating. the same reason, now there are many sites have provided some online MD5 value query function, enter the MD5 password value, if it exists in the database, then can quickly get its password value, the same reason, such as the above code I was the "HelloWorld" this string MD5 encryption , in theory you only know that ciphertext is impossible to hack my original data, but is it really? Take a look at a website http://pmd5.com/






I entered the above code generated ciphertext, the site suddenly cracked, the principle is very simple.



About MD5 more detailed text material, can step Baidu Encyclopedia, introduction of quite detailed, worth a look.





RELATED LINKS


"Java Cryptographic algorithm summary--base64 algorithm"






Java Encryption algorithm summary--MD5 encryption algorithm


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.