Implementation and application of MD, SHA, Mac Message Summary Algorithm

1. Message Digest Overview

Message Digest is also called Digital Digest. It is a fixed-length value that uniquely corresponds to a message or text, and it is generated by a one-way Hash encryption function acting on the message. If the message is changed on the way, the receiver can know whether the message has been changed by comparing the newly generated digest of the received message with the original digest. So the message digest guarantees the integrity of the message. [ Finger Print), it has a fixed length, and different plaintext summaries into ciphertext, the results are always different, and the same plaintext summary must be the same. In this way, this string of abstracts can become a “fingerprint” for verifying whether the plaintext is the “real body”.

The message digest is irreversible. In the process of generating the message digest, a lot of original information will be lost and cannot be retrieved. A good digest algorithm is extremely difficult to generate Hash collisions, that is, find another piece of plaintext to generate the same digest after calculation.

2. Message Digest Algorithm-MD2, MD4, MD5

MD is a very widely used algorithm family, especially MD5 (Message- Digest Algorithm 5, message digest algorithm version 5), it was developed from MD2, MD3, MD4, and was proposed by Ron Rivest (RSA) in 1992. It is currently widely used in data integrity verification, data (message) digest , Data encryption, etc. MD2, MD4, and MD5 all generate a 16-byte (128-bit) check value, which is generally represented by a 32-bit hexadecimal number. The algorithm of MD2 is slower but relatively safe. MD4 is fast, but its safety is reduced. MD5 is safer and faster than MD4.

At present, when large files are transferred on the Internet, MD5 algorithm must be used to generate a text file (with the suffix .md5 or .md5sum) that matches the file and stores the MD5 value, so that the recipient After receiving the file, you can use a method similar to SFV to check the integrity of the file. At present, most large software companies or open source organizations use this method to check the integrity of the data, and some operating systems also use this method. Algorithms are used to encrypt user passwords. In addition, it is also the most commonly used algorithm for data forensics in computer crimes. There are many tools related to MD5, such as WinMD5.

Implementation of MD algorithm

Algorithm Summary length< /th>

implementer
MD2 128 JDK
MD4 128 Bouncy Castle
MD5 128 JDK

All the following Java programs are running Before, you need to introduce the dependencies of Bouncy Castle and Commons Codec:

 org.bouncycastle bcprov-jdk15 1.46 commons-codec commons-codec 1.10

< p>Java code implementation:

import java.security.MessageDigest;import java.security.NoSuchAlgorithmException;import java.security.Security;import org.apache.commons.codec.digest. DigestUtils;import org.bouncycastle.crypto.digests.MD4Digest;import org.bouncycastle.crypto.digests.MD5Digest;import org.bouncycastle.jce.provider.BouncyCastleProvider;public class MD5 {public static final String src = "md5 test"; public static void main(String[] args) throws NoSuchAlgorithmException {jdkMD5 (); jdkMD2(); ccMD5(); ccMD2(); bcMD5(); bcMD4(); bc2jdkMD4();} // Implemented with jdk: MD5 public static void jdkMD5() throws NoSuchAlgorithmException {MessageDigest md = MessageDigest.getInstance ("MD5"); byte[] md.digest(src.getBytes()); System.out.println("JDK MD5:" + bytesToHexString(md5Bytes));} // Implemented by jdk: MD2 public static void jdkMD2() throws NoSuchAlgorithmException {MessageDigest md = MessageDigest.getInstance("MD2"); byte[] md2Bytes = md.digest(src.getBytes()); System.out.println("JDK MD2:" + bytesToHexString(md2Bytes ));} // Implemented with bouncy castle: MD5 public static void bcMD5() {MD5Digest digest = new MD5Digest(); digest.update(src.getBytes(), 0, src.getBytes().length); byte[ ] md5Byt es = new byte[digest.getDigestSize()]; digest.doFinal(md5Bytes, 0); System.out.println("bouncy castle MD5:" + bytesToHexString(md5Bytes));} // Implemented with bouncy castle: MD4 public static void bcMD4() {MD4Digest digest = new MD4Digest(); digest.update(src.getBytes(), 0, src.getBytes().length); byte[] md4Bytes = new byte[digest.getDigestSize()]; digest.doFinal(md4Bytes, 0); System.out.println("bouncy castle MD4:" + bytesToHexString(md4Bytes));} // Use bouncy castle and jdk to implement: MD4 public static void bc2jdkMD4() throws NoSuchAlgorithmException {Security .addProvider(new BouncyCastleProvider()); MessageDigest md = MessageDigest.getInstance("MD4"); byte[] md4Bytes = md.digest(src.getBytes()); System.out.println("bc and JDK MD4:" + bytesToHexString(md4Bytes));} // Realize with common codes: MD5 public static void ccMD5() {System.out.println("common codes MD5:" + DigestUtils.md5Hex(src.getBytes()));} // Realize with common codes: MD2 public static void ccMD2() {System. out.println("common codes MD2:" + DigestUtils.md2Hex(src.getBytes()));} /** * byte[] to hexadecimal*/ private static String bytesToHexString(byte[] src) {StringBuilder stringBuilder = new StringBuilder(); if (src == null || src.length <= 0) {return null;} for (int i = 0; i  

3. Message Digest Algorithm-SHA

SHA (Secure Hash Algorithm) is the American National Standard Technology, which is a standard organization that specially formulates cryptographic algorithms by the United States According to the Institute (NIST), the abstract lengths of the SHA series algorithms are: 20 bytes (160 bits) for SHA-1, 32 bytes (224 bits) for SHA-224, 32 bytes for SHA-256 (256 bits) Bit), SHA-384 is 48 bytes (384 bits), and SHA-512 is 64 bytes (512 bits). Because the length of the data digest generated by it is longer, it is more difficult to collide, so it is safer. It is the development direction of future data summarization algorithms. Due to the long data digest length of the SHA series algorithms, its operation speed is relatively slow compared with MD5.

Currently, SHA1 is widely used, mainly in CA and digital certificates. In addition, in the current popular BT software on the Internet, SHA1 is also used for file verification.

Realization of SHA algorithm

< td>JDK
Algorithm Summary length< /th> Implementing party
SHA-1 160
SHA-224 224 Bouncy Castle
SHA-256 256 JDK
SHA -384 384 JDK
SHA-512 512 JDK

Java code implementation:

import java.io.UnsupportedEncodingException;import java .math.BigInteger;import java.security.MessageDigest;import java.security.NoSuchAlgorithmException;import java.security.Security;import org.apache.commons.codec.digest.DigestUtils;import org.bouncycastle.crypto.Digest;import org .bouncycastle.crypto.digests.SHA1Digest;import org.bouncycastle.crypto.digests.SHA224Digest;import org.boun cycastle.jce.provider.BouncyCastleProvider;public class SHA {public static final String src = "sha test"; public static void main(String[] args) throws UnsupportedEncodingException, NoSuchAlgorithmException {jdkSHA1(); bcSHA1(); bcSHA224(); bcSHA224b(); generateSha256(); ccSHA1();} // Implemented with jdk: SHA1 public static void jdkSHA1() throws NoSuchAlgorithmException {MessageDigest md = MessageDigest.getInstance("SHA"); md.update(src.getBytes() ); byte[] bytes = md.digest(); //byte[] to hexadecimal BigInteger bigInt = new BigInteger(1, bytes); System.out.println("jdk sha-1:" + bigInt.toString (16));} // Implemented with jdk: SHA256 public static void generateSha256() throws UnsupportedEncodingException, NoSuchAlgorithmException {MessageDigest md = MessageDigest.getInstance("SHA-256"); md.update(src.getBytes("UTF-8 ")); // Change this to "UTF-16" if needed byte[] digest = md.digest(); BigInteger bigInt = new BigInteger(1, digest); System.out.println(" Sha256 hash: "+ bigInt.toString(16));} // Implemented with bouncy castle: SHA1 public static void bcSHA1() {Digest digest = new SHA1Digest(); digest.update(src.getBytes(), 0, src .getBytes().length); byte[] sha1Bytes = new byte[digest.getDigestSize()]; digest.doFinal(sha1Bytes, 0); BigInteger bigInt = new BigInteger(1, sha1Bytes); System.out.println(" bc sha-1:" + bigInt.toString(16));} // Implemented with bouncy castle: SHA224 public static void bcSHA224() {Digest digest = new SHA224Digest(); digest.update(src.getBytes(), 0 , src.getBytes().length); byte[] sha224Bytes = new byte[digest.getDigestSize()]; digest.doFinal(sha224Bytes, 0); BigInteger bigInt = new BigInteger(1, sha224Bytes); System.out.println ("bc sha-224:" + bigInt.toString(16));} // Use bouncy castle and jdk to implement: SHA224 public static void bcSHA224b() throws NoSuchAlgorithmException {Security.addProvider(new BouncyCastleProvider()); MessageDigest md = MessageDigest.getInstance("SHA224"); md.update(src.g etBytes()); BigInteger bigInt = new BigInteger(1, md.digest()); System.out.println("bc and JDK sha-224:" + bigInt.toString(16));} // use common codes Realization: SHA1 public static void ccSHA1() {System.out.println("common codes SHA1-1 :" + DigestUtils.sha1Hex(src.getBytes())); System.out.println("common codes SHA1-2 :" + DigestUtils.sha1Hex(src)); }}

Message identification:

Share pictures

4. Message Digest Algorithm-MAC

MAC Algorithm (Message Authentication Codes (Message Authentication Code Algorithm) Contains the key hash function algorithm, compatible with the characteristics of the MD and SHA algorithms, and adds a key on this basis. Therefore, the MAC algorithm is often referred to as the HMAC algorithm. The hash value of the message is controlled by a key that only the communicating parties know. At this time, the hash value is called MAC.

The digest value obtained by the MAC algorithm can also be expressed in hexadecimal encoding, and the length of the digest value is the same as that of the implemented algorithm. For example, the digest length obtained by the HmacSHA algorithm is the digest length obtained by the SHA1 algorithm, which are all 160-bit binary numbers, and the code converted to hexadecimal is 40 bits. [ It is to specify the name of the digest algorithm to be used)

2. Both parties construct the key according to the agreement, and both parties have the same key (usually one party constructs the key and then informs the other party. This process does not require a program Realization means that the two parties agree on a string, but this string is not randomly set, but also obtained through related algorithms)

3. Party A uses the key to digest the message, and then the message Send it to Party B along with the generated digest message

4. After Party B receives the message, it uses the digest algorithm that Party A has announced + the agreed key to digest the received message. Then compare your own summary message with the summary message sent by Party A. Check whether the message is sent by Party A.

The realization of MAC algorithm:

Algorithm Summary length Remarks
HmacMD5 128 JAVA6 implementation
HmacSHA1 160 JAVA6 implementation
HmacSHA256 256 JAVA6 implementation
HmacSHA384 384 JAVA6 implementation
HmacSHA512 512 JAVA6 implementation
HmacMD2 128 BouncyCastle implementation
HmacMD4 128 BouncyCastle implementation
HmacSHA224 224 BouncyCastle implementation

Java code implementation:

import java.math .BigInteger;import javax.crypto.KeyGenerator;import javax.crypto.Mac;import javax.crypto.SecretKey;import javax.crypto.spec.SecretKeySpec;import org.apache.commons.codec.binary.Hex;import org.bouncycastle.crypto.digests.MD5Digest;import org.bouncycastle.crypto.macs.HMac; import org.bouncycastle.crypto.params.KeyParameter; public class HMAC {public static final String src = "hmac test"; public static void main(String[] args) {jdkHmacMD5(); bcHmacMD5();} // Use jdk Implementation: public static void jdkHmacMD5() {try {// Initialize KeyGenerator KeyGenerator keyGenerator = KeyGenerator.getInstance("HmacMD5"); // Generate key SecretKey secretKey = keyGenerator.generateKey(); // Get key // byte[ ] key = secretKey.getEncoded(); byte[] key = Hex.decodeHex(new char[]{'1', '2', '3', '4', '5', '6', '7' , '8', '9','a','b','c','d','e'}); // restore key SecretKey restoreSecretKey = new SecretKeySpec(key, "HmacMD5"); / / Instantiate MAC Mac mac = Mac.getInstance(restoreSecretKey.getAlgorithm()); // Initialize MAC mac.init(restoreSecretKey); // Executive summary byte[] hmacMD5Bytes = mac.doFinal(src.getBytes()); System.out.println("jdk hmacMD5:" + Hex.encodeHexString(hmacMD5Bytes));} catch (Exception e) {e.printStackTrace ();}} // Realize with bouncy castle: public static void bcHmacMD5() {HMac hmac = new HMac(new MD5Digest()); // Must be a hexadecimal character, and the length must be a multiple of 2 hmac.init (new KeyParameter(org.bouncycastle.util.encoders.Hex.decode("123456789abcde"))); hmac.update(src.getBytes(), 0, src.getBytes().length); // Executive summary byte[ ] hmacMD5Bytes = new byte[hmac.getMacSize()]; hmac.doFinal(hmacMD5Bytes, 0); BigInteger bigInteger = new BigInteger(1,hmacMD5Bytes); System.out.println("bc hmacMD5:" + bigInteger.toString(16 )); }}

Reference Article

Introduction to Common Message Digest Algorithms

Message Digest Algorithm-MAC Series

< /p>

Leave a Comment

Your email address will not be published.