Java implementation of common cryptographic algorithms--one-way encryption algorithm MD5 and Sha_java

Source: Internet
Author: User
Tags md5 md5 encryption stringbuffer

This paper mainly introduces the Java implementation of the common encryption algorithm-one-way encryption algorithm MD5 and Sha, as follows:

1, the Java security architecture

Introduction to 1.1 Java security architecture

provides classes and interfaces for the security framework in Java. The JDK security API is the core API for the Java programming language, located in the package (and its child packages), and in the SUN.SECURITYAPI package (and its child packages). Designed to help developers use both low-level and advanced security features in their programs.

The first release of JDK security in JDK 1.1 introduces the "Java Encryption Architecture" (JCA), which refers to the architecture for accessing and developing the Java Platform Password functionality. In JDK 1.1, JCA includes APIs for digital signatures and reporting abstracts. JDK 1.2 greatly expands the Java encryption architecture, it also upgrades the certificate management infrastructure to support X.509 V3 certificates, and introduces a new Java security architecture for fine-grained, configurable, flexible, extensible access control.

The Java encryption architecture contains password-related portions of the JDK 1.2 security APIs, as well as a set of conventions and specifications provided in this document. It also provides a "provider" architecture for multiple, interoperable passwords.

The Java Password extension (JCE) extends the JCA APIs, including APIs for encryption, key exchange, and information authentication codes (MACS). The JCE and JDK passwords together provide a platform-independent, complete password API. JCE as a JDK extension will be released independently to conform to U.S. export control constraints.

1.2 Source code associated with JDK in eclipse

For a deeper understanding of the one-way encryption algorithm MD5 and SHA's implementation in Java, you can use the source of the JDK associated with the Eclipse IDE (the author uses JDK6.0).

After the JDK6.0 installation is complete, there is a directory in the JDK root directory (eg. C:\Java\jdk1.6.0_21). You can extract the directory to another directory (eg. D:\amigo\study\ Technical essay \201405). The does not contain all the JDK source code, for example, the child packages under Sun are not present in (eg. the package and its child packages used in this article are not in it).

To download these packets, you need to download the OPENJDK source code, OPENJDK is the JDK's open version of the original code, released in the form of a GPL protocol. In JDK7, OPENJDK has become the backbone of JDK7 development, Sun Jdk7 is published on the basis of OPENJDK7, most of the original code is the same, only a small number of original code was replaced. Published using the JRL (Javaresearch License,java Research Licensing Protocol).

OPENJDK's download Address:

After downloading, all the files and folders in the Openjdk-6-src-b27-26_oct_2012\jdk\src\share\classes directory will be copied to the SRC directory just extracted.

Next, configure the associated source in eclipse: click on "Windows"-> "Preferences", select "Java"-> "Installed JREs" on the left menu, and if you have already configured the local JRE, you may not need to configure it. If not configured, click on the "Add" button on the right, and select the JDK6.0 path (eg) in the pop-up "Add JRE" window. C:\JAVA\JDK1.6.0_21). Click the "OK" button to complete the JRE settings.

Select the JRE you have set up, click the "Edit ..." button on the right, click the "Source attachment ..." button in the pop-up window and click the "External Folder ..." button in the pop-up window Rt.jar Point the source path to the path just src (eg. D:\amigo\study\ Technical essay \201405). See figure below:

When you click the "OK" button setting, and then when you write the implementation of MD5 and SHA, you can use debug mode F5 Single Step debugging to view the MD5 and Sha one-way cryptographic algorithms in Java where you invoke MessageDigest related methods.

Main classes for MD5 and SHA encryption in the 1.3 JDK
in JDK6.0, the class diagram of several classes closely related to the MD5 and Sha is as follows:

where "Messagedigestspi" is the top-level abstract class, and the "MessageDigest" and "Digestbase" under the same package are subclass abstract classes.

In the class diagram above, the delegate (delegate) design pattern is used. The principle of this pattern is Class B (where Delegage inner Class) and Class A (where Messagedigestspi Class) are two classes that have nothing to do with each other, B has the same methods and properties as a, and the methods and properties in B are called methods and properties of the same name in a. b seems to be an intermediary entrusted by a delegation. Third-party code does not need to know the existence of a and its subclasses, there is also no need to have direct contact with a and its subclasses, which can be used directly by B, so that both the functions of a and the A and its subclasses can be well protected.

The relevant code for MD5 and SHA is in classes such as MD5 and Sha, but customer-facing MessageDigest abstract classes do not need to deal with various implementation classes, as long as they are dealt with by a delegate class.

2, MD5 encryption

2.1 Overview

Message Digest algorithm MD5 (Chinese name is the fifth edition of the Message Digest algorithm) is a hash function widely used in the field of computer security to provide integrity protection for messages. The algorithm's file number is RFC 1321 (R.rivest,mit Laboratory for Computer Science and RSA Data Security Inc. April 1992).

The full name of MD5 is message-digest algorithm 5 (Information-Digest algorithm), in the early 90 by MIT Laboratory for Computer and RSA Data Security Inc, Ronald L. Riv EST developed and developed by MD2, MD3 and MD4.

MD5 is used to ensure complete consistency of information transmission. is one of the most widely used hashing algorithms (also translated digest algorithm, hashing algorithm), the mainstream programming language has been MD5 realized. The basic principle of hashing algorithm is to calculate data (such as Chinese characters) as another fixed length value, and the predecessor of MD5 is MD2, MD3 and MD4.

The role of MD5 is to allow bulk information to be "compressed" into a confidential format (that is, to transform an arbitrary length of a byte string into a certain length of hexadecimal numbers) before signing the private key with the digital signature software.

2.2 Algorithm principle

A brief description of the MD5 algorithm can be: MD5 512-bit grouping to process the input information, and each grouping is divided into 16 32-bit subgroups, after a series of processing, the output of the algorithm is composed of four 32-bit, the four-bit group will be cascaded after this will generate a 32-bit hash value.

In the MD5 algorithm, it is necessary to fill the information first, so that the result of the bit length to 512 is equal to 448. Therefore, the bit length of the information (BITS length) is extended to N*512+448,n as a non-negative integer, and n can be zero. The method of filling is as follows, filling a 1 and countless 0 after the information, until the above conditions are met to stop the fill of 0 pairs of information. Then, after this result, append a 64-bit binary representation of the padding information length. After these two steps, the bit length =n*512+448+64= (n+1) *512 of the information, that is, the length is exactly 512 times the integer. The reason for this is to meet the requirements for the length of information in subsequent processing.

Implementation of MD5 in 2.3 java

The Java implementation of the MD5 encryption algorithm looks like this:

Package amigo.endecrypt;

   /** * Using MD5 encryption * @author Xingxing,xie * @datetime 2014-5-31/public class Md5util {/*** * MD5 encryption generates 32-bit MD5 code * @param to be encrypted String * @return return 32-bit MD5 code */public static String Md5encode (String inStr) throws Exception {Messag
    Edigest MD5 = NULL;
    try {MD5 = messagedigest.getinstance ("MD5");
      catch (Exception e) {System.out.println (e.tostring ());
      E.printstacktrace ();
    Return "";
    } byte[] ByteArray = instr.getbytes ("UTF-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 <) {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 ("MD5 after:" + Md5encode (str));


Test results:

Original: Amigoxiexiexingxing

After MD5: e9ac094091b96b84cca48098bc21b1d6

3. SHA Encryption

3.1 Overview

SHA is a data encryption algorithm, which has been developed and improved by encryption experts for many years and has become one of the most secure hashing algorithms, and is widely used. The idea of the algorithm is to receive a clear passage, it is then converted into a paragraph (usually smaller) cipher in an irreversible manner, and can be simply understood to take a string of input codes (called Pre-maps or information) and convert them to a shorter, fixed number of output sequences that are hashed (also A process called an information digest or information authentication code. The hash function value can be said to be a "fingerprint" or "digest" of the plaintext, so the digital signature of the hash value can be considered a digital signature on the plaintext.

Secure Hash algorithm SHA (Secure hash Algorithm,sha) is a national standard FIPS pub 180 issued by the National Institute of Standards and Technology, the latest standard has been updated in 2008 to FIPS pub 180-3. It prescribes the sha-1,sha-224,sha-256,sha-384, and SHA-512 these one-way hashing algorithms. sha-1,sha-224 and SHA-256 apply to messages that are not longer than 2^64 bits. SHA-384 and SHA-512 apply to messages that are not longer than 2^128 bits.

3.2 principle

SHA-1 is a data encryption algorithm, the idea of the algorithm is to receive a clear text and then convert it into a paragraph (usually smaller) cipher in an irreversible way, or simply to take a string of input codes (called Pre-maps or information) and convert them to a shorter, The process of a fixed number of digits in the output sequence that is the hash value (also known as Information Digest or information authentication code).

The safety of one-way hash function is that the operation process of producing hash value has a strong one-way. If the password is embedded in the input sequence, then no one can produce the correct hash value without knowing the password, thus ensuring its security. The SHA blocks the input stream by 512 bits (64 bytes) per block and produces 20 bytes of output called the Information authentication Code or information digest.

This algorithm input the length of the message is not limited, produces the output is a 160-bit message digest. The input is processed by a 512-bit grouping. SHA-1 is irreversible, conflict-proof, and has a good avalanche effect.

Through hashing algorithm can realize digital signature, the principle of digital signature is to transmit the clear text through a function operation (Hash) conversion to the newspaper digest (different clear text corresponding to different message digest), the newspaper digest to be encrypted with plaintext sent to the receiver, The recipient will accept the clear text to produce a new digest to be sent to the sender of the digest to decrypt the comparison, the results of the comparison are consistent to indicate that the plaintext has not been altered, if it is inconsistent that the plaintext has been tampered with.

Mac (information authentication code) is a hash result, where some of the input information is a password, only those who know the password can again calculate and verify the legality of the MAC code.

Implementation of SHA in 3.3 Java

The implementation of SHA in Java is similar to MD5, as the reference code looks like this:

Package amigo.endecrypt;

   /** * Using SHAA encryption * @author Xingxing,xie * @datetime 2014-6-1/public class Shautil {/*** * SHA encryption generated 40-bit SHA code * @param to be encrypted String * @return return 40-bit SHA code */public static String Shaencode (String inStr) throws Exception {Messag
    Edigest sha = null;
    try {sha = Messagedigest.getinstance ("Sha");
      catch (Exception e) {System.out.println (e.tostring ());
      E.printstacktrace ();
    Return "";
    } byte[] ByteArray = instr.getbytes ("UTF-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 <) {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 ("After Sha:" + shaencode (str));


The test results are as follows:

Original: Amigoxiexiexingxing

After Sha: 04f79f496dd6bdab3439511606528a4ad9caac5e

3, Comparison of SHA-1 and MD5

Because both are derived by MD4, SHA-1 and MD5 are very similar to each other. Correspondingly, their strength and other characteristics are similar, but there are several differences:

1 The security of brute force attacks: the most significant and important difference is that the SHA-1 summary is 32 bits longer than the MD5 summary. The use of forced technology to produce any message to make its summary equal to the given report summary of the difficulty of MD5 is a 2^128 order of magnitude of operations, and SHA-1 is 2^160 order of magnitude of operations. In this way, SHA-1 has a greater strength for brute force attacks.

2 The security of cryptanalysis: Because of MD5 design, easy to be attacked by password analysis, SHA-1 appears not easy to be attacked by this.

3 speed: On the same hardware, SHA-1 run slower than MD5.

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

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: and provide relevant evidence. A staff member will contact you within 5 working days.