English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java implementation of commonly used encryption algorithms - one-way encryption algorithm MD5and SHA

This article mainly introduces the commonly used encryption algorithm implemented in Java——one-way encryption algorithm MD5and SHA, as follows:

1Java's security architecture

1.1 Introduction to the Java security architecture

Java provides classes and interfaces for the security framework. The JDK Security API is a core API of the Java programming language, located in the java.security package (and its sub-packages), as well as the sun.security API package (and its sub-packages). It is designed to help developers use both low-level and high-level security features in their programs.

JDK 1.1 The first JDK security released introduced the 'Java Cryptography Architecture' (JCA), which refers to the framework for accessing and developing password functions of the Java platform. In JDK 1.1 JCA includes APIs for digital signature and message digest. JDK 1.2 Greatly expanded the Java Cryptography Architecture, and also upgraded the certificate management infrastructure to support X.509 v3 certificates, and introduces a new Java security architecture with fine-grained, configurable, flexible, and extensible access control. version

The Java Cryptography Architecture includes JDK 1.2 The parts related to cryptography in the Security API, as well as a set of conventions and specifications provided in this document. It also provides a 'provider' architecture to achieve multiple, interoperable cryptography.

Java Cryptography Extension (JCE) extends the JCA API, including APIs for encryption, key exchange, and message authentication code (MAC). JCE and JDK cryptography provide a complete, platform-independent cryptography API. As an extension of JDK, JCE will be released independently to comply with US export control constraints.

1.2 Associate the JDK source code in Eclipse

To have a deeper understanding of the one-way encryption algorithm MD5and SHA implementation in Java, you can use Eclipse IDE to associate the JDK source code (the one used by the author is JDK6.0).

JDK6.0 after the installation is completed in the root directory of JDK (eg. C:\Java\jdk1.6.0_21There is a src.zip directory. You can unzip this directory to another directory (eg. D:\amigo\study\技术随笔\201405The src.zip does not contain all the JDK source code, for example, the sub-packages under sun do not exist in src.zip (eg. the sun.security package and its sub-packages used in this article are not included).

To download these sub-packages, you need to download the source code of OpenJDK, which is the open-source code version of JDK released in the form of the GPL agreement. In JDK7at the time, openjdk has become jdk7, sun jdk7is on the main trunk development of openjdk7Based on the release, most of the original code is the same, only a small part of the original code has been replaced. It is released under the JRL (Java Research License, Java Research Authorization Agreement).

The download address of OpenJDK: https://www.oldtoolbag.com/softs/75724.html

After the download is complete, decompress the openjdk-6-src-b27-26_oct_2012\jdk\src\share\classes directory copy all files and folders to the just unpacked src directory.

Next, configure the associated source code in Eclipse: click 'Windows'-> 'Preferences', select 'Java' in the left menu-> 'Installed JREs', if the JRE on this machine has been configured, there is no need to configure it. If not configured, click the 'Add' button on the right, and select the installed JDK in the 'Add JRE' window that pops up6.0 path (eg. C:\Java\jdk1.6.0_21)). Click the 'OK' button to complete the JRE setting.

Select the JRE that has been set, click the 'Edit...' button on the right, select the rt.jar package in the pop-up window, click the 'Source Attachment...' button, click the 'External Folder...' button in the pop-up window, and point the source code path to the just src path (eg. D:\amigo\study\技术随笔\201405)). See the figure below:

After clicking the 'OK' button to set up, write MD5and the implementation of SHA, at the place where the MessageDigest related methods are called, you can use the debugging mode F5Step-by-step debugging to view the MD in Java5and the main classes involved in the implementation of the SHA one-way encryption algorithm.

1.3 JDK's MD5and the main classes of SHA encryption
In JDK6.0, related to MD5The class diagram of several classes closely related to SHA is as follows:

Among them, 'MessageDigestSpi' is the top-level abstract class, and 'MessageDigest' and 'DigestBase' in the same package are subclasses.

In the above class diagram, the Delegate design pattern is used. The principle of this pattern is that class B (here the Delegate internal class) and class A (here the MessageDigestSpi class) are two classes that have no relationship with each other, B has the same methods and properties as A; and calling the methods and properties of B is equivalent to calling the methods and properties of A with the same name. B seems to be a mediator authorized by A. Third-party code does not need to know the existence of A and its subclasses, nor does it need to have direct contact with A and its subclasses. Through B, it can directly use the functions of A, which can not only use all the functions of A, but also protect A and its subclasses very well.

MD5and related code of SHA are all in MD5and SHA, but the MessageDigest abstract class for customers does not need to deal with each implementation class, but only through the delegate class to deal with it.

2predecessor is MD5Encryption

2.1 Overview

Message Digest Algorithm MD5The fifth version, known in Chinese as Message Digest Algorithm fifth version, is a widely used hash function in the field of computer security, used to provide message integrity protection. The file number of the algorithm is RFC 1321(R.Rivest, MIT Laboratory for Computer Science and RSA Data Security Inc. April 1992).

MD5The full name is Message-Digest Algorithm 5(Information-Digest Algorithm9Digest Algorithm), in2predecessor is MD3and MD4In the early 2000s, developed by Ronald L. Rivest of MIT Laboratory for Computer Science and RSA Data Security Inc., after MD

MD5has developed from mainstream programming languages.5is used to ensure the integrity of information transmission. It is one of the widely used hash algorithms in computers (also translated as digest algorithm, hash algorithm), and MD5implementation. The operation of data (such as Chinese characters) into another fixed length value is the basic principle of hash algorithms, MD2predecessor is MD3and MD4MD

MD5.

2.2 is to "compress" large capacity information into a secret format before it is signed with a digital signature software (which is to transform a byte string of arbitrary length into a hexadecimal number string of a certain length).

Principle of MD5The function of MD5The brief description of the algorithm can be: MD512bit group to process the input information, and each group is further divided into16Each32groups32bit subgroups are processed in a series of operations, and the output of the algorithm is composed of four32bit groupings are formed, and these four128After the bit grouping cascade, a

bit hash value.5In the algorithm, the first step is to pad the information so that its bit length is a multiple of512The remainder of the division is equal to448. Therefore, the bit length (Bits Length) of the information will be extended to N*512+448, where N is a non-negative integer, N can be zero. The method of padding is as follows, a1and numerous 0s, until the condition above is met before stopping padding the information with 0s. Then, an additional64The bit length of the information before padding is represented in binary. After these two steps of processing, the bit length of the information is N*512+448+64=(N+1)*512i.e., the length is exactly512is an integer multiple. The reason for doing this is to meet the requirements of information length for subsequent processing.

2.3 MD in Java5Implementation

MD5The Java implementation of the MD encryption algorithm is as follows:

package amigo.endecrypt;
import java.security.MessageDigest;
/** 
 * Using MD5Encryption
 * @author Xingxing,Xie
 * @datetime 2014-5-31 
 */
public class MD5Util {
  /*** 
   * MD5Encryption Generation32Position md5code
   * @param The string to be encrypted
   * @return Returns32Position md5code
   */
  public static String md5Encode(String inStr) throws Exception {
    MessageDigest md5 = null;
    try {
      md5 = MessageDigest.getInstance("MD5");
    } catch (Exception e) {
      System.out.println(e.toString());
      e.printStackTrace();
      return "";
    }
    byte[] byteArray = inStr.getBytes("UTF-8");-8");
    byte[] md5Bytes = md5.digest(byteArray);
    StringBuffer hexValue = new StringBuffer();
    for (int i = 0; i < md5Bytes.length; i++) {
      int val = ((int) md5Bytes[i]) & 0xff;
      if (val < 16) {
        hexValue.append("0");
      }
      hexValue.append(Integer.toHexString(val));
    }
    return hexValue.toString();
  }
  /**
   * Test main function
   * @param args
   * @throws Exception
   */
  public static void main(String args[]) throws Exception {
    String str = new String("amigoxiexiexingxing");
    System.out.println("Original: " + str);
    System.out.println("MD5After: " + md5Encode(str));
  }
}

Test results:

Original: amigoxiexiexingxing

MD5After: e9ac094091b96b84cca48098bc21b1d6

3, SHA encryption

3.1 Overview

SHA is a data encryption algorithm. After years of development and improvement by encryption experts, it has become increasingly perfect and is now recognized as one of the safest hash algorithms and is widely used. The idea of this algorithm is to receive a segment of plaintext, then convert it into a segment (usually smaller) of ciphertext in an irreversible way, or simply understand it as taking a string of input codes (referred to as pre-mapping or information), and converting them into a shorter, fixed-length output sequence, namely the hash value (also known as message digest or message authentication code). The hash function value can be said to be a 'fingerprint' or 'summary' of the plaintext, so the digital signature of the hash value can be regarded as a digital signature of the plaintext.

Secure Hash Algorithm SHA (Secure Hash Algorithm, SHA) is a national standard published by the National Institute of Standards and Technology in the United States, FIPS PUB 180, and the latest standard has been2008year was updated to FIPS PUB 180-3. It stipulates that SHA-1, SHA-224, SHA-256, SHA-384, and SHA-512these one-way hash algorithms. SHA-1, SHA-224and SHA-256binary messages. SHA2^64binary messages. SHA-384and SHA-512binary messages. SHA2^128binary message.

3.2 Principle

SHA-1is a data encryption algorithm. The idea of this algorithm is to receive a segment of plaintext, then convert it into a segment (usually smaller) of ciphertext in an irreversible way, or simply understand it as taking a string of input codes (referred to as pre-mapping or information), and converting them into a shorter, fixed-length output sequence, namely the hash value (also known as message digest or message authentication code).

The security of one-way hash functions lies in the strong unidirectional nature of the operation process of generating hash values. If a password is embedded in the input sequence, then no one can generate the correct hash value without knowing the password, thereby ensuring its security. SHA divides the input stream into blocks of512bits (64bytes) and generates2output called the Message Authentication Code or Message Digest. It is a byte

The algorithm does not limit the length of the input message and generates an output that is a160 bits of the message digest. The input is divided into512 grouped for processing. SHA-1It is irreversible, conflict-free, and has a good avalanche effect.

Digital signatures can be implemented through hash algorithms, the principle of which is to convert the plaintext to be transmitted into a message digest (Hash) through a function operation (Hash), and the message digest is encrypted and sent together with the plaintext to the recipient. The recipient generates a new message digest from the received plaintext and compares it with the message digest sent by the sender. If the comparison result is consistent, it means that the plaintext has not been changed; if it is inconsistent, it means that the plaintext has been tampered with.

MAC (Message Authentication Code) is a hash result, part of which is the password, and only participants who know this password can recalculate and verify the legality of the MAC code again.

3.3 Java SHA implementation

The implementation of SHA in Java is similar to MD5Similarly, refer to the following code:

package amigo.endecrypt;
import java.security.MessageDigest;
/** 
 * Using SHAA encryption
 * @author Xingxing,Xie
 * @datetime 2014-6-1 
 */
public class SHAUtil {
  /*** 
   * SHA Encryption Generation40th SHA code
   * @param The string to be encrypted
   * @return Returns40th SHA code
   */
  public static String shaEncode(String inStr) throws Exception {
    MessageDigest sha = null;
    try {
      sha = MessageDigest.getInstance("SHA");
    } catch (Exception e) {
      System.out.println(e.toString());
      e.printStackTrace();
      return "";
    }
    byte[] byteArray = inStr.getBytes("UTF-8");-8");
    byte[] md5Bytes = sha.digest(byteArray);
    StringBuffer hexValue = new StringBuffer();
    for (int i = 0; i < md5Bytes.length; i++) {
      int val = ((int) md5Bytes[i]) & 0xff;
      if (val < 16) { 
        hexValue.append("0");
      }
      hexValue.append(Integer.toHexString(val));
    }
    return hexValue.toString();
  }
  /**
   * Test main function
   * @param args
   * @throws Exception
   */
  public static void main(String args[]) throws Exception {
    String str = new String("amigoxiexiexingxing");
    System.out.println("Original: " + str);
    System.out.println("SHA after: " + shaEncode(str));
  }
}

The test results are as follows:

Original: amigoxiexiexingxing

SHA after: 04f79f496dd6bdab3439511606528a4ad9caac5e

3, SHA-1and MD5comparison

because both are derived from MD4export, SHA-1and MD5are very similar. Correspondingly, their strength and other characteristics are also similar, but there are also the following differences:

1)Security against brute force attacks: The most significant and important difference is that SHA-1Digest is longer than MD5Digest Length32 bits. Using brute force techniques, the difficulty of generating any message that makes the digest equal to the given digest is for MD5is2^128level operations, while SHA-1is2^160-level operations. Thus, SHA-1has greater strength against brute force attacks.

2)Password Analysis Security: Due to MD5is vulnerable to password analysis attacks, SHA-1seems less vulnerable to such attacks.

3)Speed: On the same hardware, SHA-1has a running speed faster than MD5Slow.

That's all for this article. Hope it will be helpful to everyone's learning, and also hope everyone will support the Yelling Tutorial more.

Declaration: The content of this article is from the Internet, and the copyright belongs to the original author. The content is contributed and uploaded by Internet users spontaneously. This website does not own the copyright, has not been manually edited, and does not assume any relevant legal liability. If you find any content suspected of copyright infringement, please send an email to: notice#oldtoolbag.com (Please replace # with @ when sending an email to report violations, and provide relevant evidence. Once verified, this site will immediately delete the content suspected of infringement.)

You May Also Like