First, hash function
A hash function is a function that maps data of any length to fixed-length data. The value returned by the hash function is called a hash value, hash code, hash, or directly called a hash.
Second, the message digest will be the length of the information (message) as an input parameter, run a specific hash function, generate a fixed-length output, this output is a hash, also known as this message digest message (message Digest)
The Information digest algorithm is a kind of hash algorithm, which has the following characteristics:
- No matter how long the message is entered, the length of the computed message digest is always fixed, the longer the computed result, the more secure the digest algorithm is generally considered, MD5 128-bit SHA-1 160-bit
- Different messages are generated, the message digest must be different, the message is the same, the resulting message digest must be the same
- Unidirectional non-reversible
Third, MessageDigest
In Java, the ability to provide a message-digest algorithm to a program through messagedigest, such as MD5 and SHA, is often used, and there's not much to explain
Tag interpretation
- Get the MessageDigest instance by the algorithm name of the incoming parameter, such as: MD2 MD5 SHA-1 SHA-256 SHA-384 SHA-512
- The provider of the specified algorithm summary, which can be obtained by means of the
Security.getProviders()
- Updates the digest with the specified byte array
- The hash calculation is completed, called only once,
digest()方法
after the call, the MessageDigest object is reset to its initial state
- Reset Summary
Iv. Use of
Since some of the methods used are already encapsulated in the Commons-codec package, a dependency can be invoked directly
4.1. Reliance
<dependency> <groupId>commons-codec</groupId> <artifactid>commons-codec</ artifactid> <version>1.4</version> </dependency>
4.2. Tool class
Package Com.geenk.web.util;import Org.apache.commons.codec.binary.base64;import Org.apache.commons.codec.digest.digestutils;import Java.io.file;import Java.io.fileinputstream;import Java.io.ioexception;import java.math.biginteger;import java.security.messagedigest;/** * @author DUCHONG * @since 2018-05-02 9:18 **/public class Encryptionutils {public static string Base64Encode (String data) {return Base64. Encodebase64string (Data.getbytes ()); } public static byte[] Base64decode (String data) {return base64.decodebase64 (Data.getbytes ()); } public static string MD5 (string data) {return Digestutils.md5hex (data); } public static string SHA1 (string data) {return Digestutils.shahex (data); } public static string Sha256hex (String data) {return Digestutils.sha256hex (data); }//calculate the hash value of the file, you can compare whether the file has the Modify public static String getmd5file (file file) {try {return Digestutils.md5hex (New FileInputStream (file)); } catch (IOException e) {e.printstacktrace (); } return null; }}
hash function and message digest algorithm