Wechat search: code nong StayUp

Home address: goZhuyinglong.github. IO

Source: github.com/gozhuyinglo…

Definition 1.

The one-way hash function computes different input values using the one-way hash function to obtain fixed-length output values. The input value is called a message, and the output value is a hash value.

The one-way hash function is also known as the Message Digest function, hash function, or hash function. The input message is also called a pre-image. The output hash value, also known as message digest or fingerprint, acts as the id of the message.

There are many implementations of one-way hash functions, including MD5, SHA-1, SHA-2, and SHA-3.

2. The characteristics of

From the above definition, our understanding of one-way hash functions is still vague. The following is an introduction to the characteristics of one-way hash functions to deepen the impression.

2.1 The length of the hash value is fixed

The length of the hash value calculated using the same algorithm is always fixed, regardless of the length of the message. The MD5 algorithm, for example, produces a hash of 128 bits (16 bytes) no matter how many are entered.

While bits are units that computers recognize, we humans are more accustomed to using hexadecimal strings (a byte takes up two hexadecimal characters).

2.2 Different messages have different hash values

Using the same message must produce the same hash value.

Different messages produce different hash values. Even a one-bit difference can make a big difference in the hash value.

This property is also called crashworthiness, and should not be used for algorithms with weak crashworthiness.

2.3 Unidirectional

The hash value can only be computed from the message, not from the hash value.

2.4 Fast computing speed

Computes hashes quickly. Although the longer the message, the longer it takes to compute the hash value, it is also done in a short time.

3. Common algorithms

MD5 and SHA-1 algorithms have been compromised and should not be used for new purposes. Sha-2 and SHA-3 are still safe to use.

Sha-2 includes SHA-224, SHA-256, SHA-384, SHA-512, SHA-512/224, and SHA-512/256.

Sha-3 includes SHA3-224, SHA3-256, SHA3-384, and SHA3-512.

The algorithm name Hash value length Is it safe
MD5 128 unsafe
SHA-1 160 unsafe
SHA-224 224 security
SHA-256 256 security
SHA-384 384 security
SHA-512 512 security
SHA-512/224 224 security
SHA-512/256 256 security
SHA3-224 224 security
SHA3-256 256 security
SHA3-384 384 security
SHA3-512 512 security

4. Application scenarios

One-way hash function can not guarantee the confidentiality of information, it is a cryptographic technology to ensure the integrity of information. Here’s how it works.

4.1 User Password Protection

When a user sets a password, only the hash value of the password is recorded. Only the user knows the plaintext of the password. If the entered password is correct, the hash value obtained must be the same, indicating that the password is correct.

In order to prevent the cracking of the rainbow table, you can also add salt to the password. As long as the password is verified, use the same salt to complete the verification.

The advantage of using hashed values to store passwords is that even if the database is stolen, it is impossible to reverse the ciphertext to what the plaintext is, making passwords more secure.

4.2 Interface verification

To ensure the security of the interface, you can send the packet in signature mode.

The sender and receiver must have a shared secret key. When the sender sends the request to the receiver, a signature is appended to the parameter (the signature is generated by the shared secret key + business parameter, encrypted by one-way hash function). After receiving the signature, the recipient uses the same method to generate the signature and compares it with the received signature. If the signature is consistent with the received signature, the signature is successfully verified.

This verifies whether the business parameters have been tampered with and the identity of the sender.

4.3 File integrity verification

When a file is mounted to a web site, it is accompanied by its hash value and algorithm, such as the Tomcat website.

After downloading the file, the user calculates the hash value and compares the result to verify the integrity of the file.

4.4 Cloud disk transmission in seconds

When we put our favorite video on the network disk, we found that it only took a few seconds to upload successfully, and this file is several GIGABytes in size, how to do it?

In fact, this “second pass” function can be implemented using a one-way hash function.

When we upload a file, the cloud disk client first generates a hash value for the file. Take the hash value and match it in the database. If a match is found, the file already exists in the cloud server. Simply associate the hash value with the user to complete the upload.

In this way, only one file can be saved on the cloud server, greatly saving the space of the cloud server.

5. Code implementation

The JDK Java. Security. The MessageDigest class provides us with a message digest algorithms, used to MD5 and SHA hash value is generated. The following code is simply wrapped for direct use.

public class MDUtil {

    /** * MD5 encryption **@paramData Indicates the data to be encrypted@returnA 32-bit hexadecimal character string */
    public static String MD5(byte[] data) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] bytes = md.digest(data);
            return bytesToHexString(bytes);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }

    /** * MD5 encryption **@paramData Indicates the data to be encrypted@returnA 32-bit hexadecimal character string */
    public static String MD5(String data) {
        return MD5(data.getBytes());
    }

    /** * SHA-1 encryption **@paramData Indicates the data to be encrypted@returnA 40-digit hexadecimal character string */
    public static String SHA1(byte[] data) {
        try {
            MessageDigest md = MessageDigest.getInstance("SHA-1");
            byte[] bytes = md.digest(data);
            return bytesToHexString(bytes);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }

    /** * SHA-1 encryption **@paramData Indicates the data to be encrypted@returnA 40-digit hexadecimal character string */
    public static String SHA1(String data) {
        return SHA1(data.getBytes());
    }

    /** * SHA-224 encryption **@paramData Indicates the data to be encrypted@returnA 56-digit hexadecimal character string */
    public static String SHA224(byte[] data) {
        try {
            MessageDigest md = MessageDigest.getInstance("SHA-224");
            byte[] bytes = md.digest(data);
            return bytesToHexString(bytes);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }

    /** * SHA-224 encryption **@paramData Indicates the data to be encrypted@returnA 56-digit hexadecimal character string */
    public static String SHA224(String data) {
        return SHA224(data.getBytes());
    }

    /** * SHA-256 encryption **@paramData Indicates the data to be encrypted@returnThe 64-bit hexadecimal character string */
    public static String SHA256(byte[] data) {
        try {
            MessageDigest md = MessageDigest.getInstance("SHA-256");
            byte[] bytes = md.digest(data);
            return bytesToHexString(bytes);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }

    /** * SHA-256 encryption **@paramData Indicates the data to be encrypted@returnThe 64-bit hexadecimal character string */
    public static String SHA256(String data) {
        return SHA256(data.getBytes());
    }

    /** * SHA-384 encryption **@paramData Indicates the data to be encrypted@returnA 96-digit hexadecimal character string */
    public static String SHA384(byte[] data) {
        try {
            MessageDigest md = MessageDigest.getInstance("SHA-384");
            byte[] bytes = md.digest(data);
            return bytesToHexString(bytes);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }

    /** * SHA-384 encryption **@paramData Indicates the data to be encrypted@returnA 96-digit hexadecimal character string */
    public static String SHA384(String data) {
        return SHA384(data.getBytes());
    }

    /** * SHA-512 encryption **@paramData Indicates the data to be encrypted@returnThe 128-bit hexadecimal character string */
    public static String SHA512(byte[] data) {
        try {
            MessageDigest md = MessageDigest.getInstance("SHA-512");
            byte[] bytes = md.digest(data);
            return bytesToHexString(bytes);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }

    /** * SHA-512 encryption **@paramData Indicates the data to be encrypted@returnThe 128-bit hexadecimal character string */
    public static String SHA512(String data) {
        return SHA512(data.getBytes());
    }

    /** * converts a byte array to a hexadecimal string **@paramBytes Bytes array *@returnThe hexadecimal character string */
    private static String bytesToHexString(byte[] bytes) {
        StringBuilder hexValue = new StringBuilder();
        for (byte b : bytes) {
            int val = b & 0xFF;
            if (val < 16) {
                hexValue.append("0");
            }
            hexValue.append(Integer.toHexString(val));
        }
        returnhexValue.toString(); }}Copy the code

These algorithms are used to calculate the hash value of “123456” :

public static void main(String[] args) {
    System.out.println("MD5\t\t" + MDUtil.MD5("123456"));
    System.out.println("SHA-1\t" + MDUtil.SHA1("123456"));
    System.out.println("SHA-224\t" + MDUtil.SHA224("123456"));
    System.out.println("SHA-256\t" + MDUtil.SHA256("123456"));
    System.out.println("SHA-384\t" + MDUtil.SHA384("123456"));
    System.out.println("SHA-512\t" + MDUtil.SHA512("123456"));
}
Copy the code

Output result:

MD5 e10adc3949ba59abbe56e057f20f883e SHA-1 7c4a8d09ca3762af61e59520943dc26494f8941b SHA-224 f8cdb04495ded47615258f9dc6a3f4707fd2405434fefc3cbf4ef4e6 SHA-256 8d969eef6ecad3c29a3a629280e686cf0c3f5d5a86aff3ca12020c923adc6c92 SHA-384 0a989ebc4a77b56a6e2bb7b19d995d185ce44090c13e2984b7ecc6d446d4b61ea9991b76a4c2f04b1b4d244841449454 SHA-512 ba3253876aed6bc22d4a6ff53d8406c6ad864195ed144ab5c87621b6c233b548baeae6956df346ec8c17f5ea10f35ee3cbc514797ed7ddd3145464e2 a0bab413Copy the code

I use Java8, which does not yet support sha-3, so the above code only encapsulates MD5, sha-1, and sha-2.

Sha-3 is supported as of Java9

6. Complete code

For the complete code, please visit my Github. If it is helpful to you, you are welcome to give a Star. Thank you!

Github.com/gozhuyinglo…

7. Recommended reading

  • Hash table