Java implementation of common encryption Algorithm (i)--one-way encryption algorithm MD5 and SHA

Source: Internet
Author: User
Tags md5 digest md5 encryption

1. Java Security Architecture 1.1 Introduction to Java Security architecture

Java provides classes and interfaces for the security framework. The JDK security API is the core API for the Java programming language, located in the Java.security 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 Cryptography Architecture (JCA), which refers to the architecture used to access and develop the Java platform Password functionality. In JDK 1.1, JCA includes APIs for digital signatures and for Digest. JDK 1.2 greatly expands the Java encryption architecture, and it also upgrades the certificate management infrastructure to support the V3 certificate, and introduces a new Java security architecture for granular, configurable, flexible, and scalable access control.

The Java encryption architecture contains the password-related sections of the JDK 1.2 security API, along with a set of conventions and specifications provided in this document. It also provides a "provider" architecture for implementing multiple, interoperable passwords.

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

1.2 Source code associated with JDK in eclipse

In order to further understand the implementation of the one-way encryption algorithm MD5 and Sha in Java, you can use the Eclipse IDE to associate the JDK source code (the author uses JDK6.0).

JDK6.0 the root directory of the JDK (eg. C:\Java\jdk1.6.0_21) has a src.zip directory after the installation is complete. This directory can be extracted to another directory (eg. D:\amigo\study\ Technical essay \201405). Src.zip does not contain all JDK source code, such as the child package under Sun is not present in src.zip (eg. the sun.security package and its child packages used in this article are not included).

To download these sub-packages, you need to download the source code for OPENJDK, OPENJDK is the open version of the JDK, released in the form of a GPL protocol. In the JDK7, OPENJDK has become the backbone of JDK7 development, Sun Jdk7 was released on the basis of OPENJDK7, most of the original code is the same, only a small part of the original code is replaced. Published using JRL (javaresearch License,java Research License Agreement).

OPENJDK: http://download.java.net/openjdk/jdk6/

After the download is finished, all files and folders under the extracted openjdk-6-src-b27-26_oct_2012\jdk\src\share\classes directory are copied to the SRC directory just extracted.

Next, configure the associated source code in eclipse: Click "Windows", "Preferences", on the left menu choose "Java", "Installed JREs", if you have configured the native JRE, can not be configured. If not configured, click on the "Add" button on the right to select the path of the installed JDK6.0 in the "Add JRE" window that pops up (eg. C:\JAVA\JDK1.6.0_21). Click the "OK" button to complete the JRE settings.

Select the JRE that you have set, 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, Point the source path to the path just src (eg. D:\amigo\study\ Technical essay \201405). See:

When the "OK" button is set, after you write the implementation of MD5 and SHA, you can use Debug mode F5 single-step debugging to see the classes that are primarily involved in MD5 and SHA one-way cryptographic algorithms in Java, where the relevant methods of messagedigest are called.

Main classes for MD5 and SHA encryption in 1.3 JDK

In JDK6.0, the class diagram of several classes that are closely related to MD5 and Sha are as follows:

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

In the class diagram above, the delegate (delegate) design pattern is used. The principle of this pattern is Class B (where the Delegage inner class is) and Class A (the Messagedigestspi class here) is 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 call B are the methods and properties that call the same name in a. b seems to be an intermediary entrusted by a mandate. The third-party code does not need to know the existence of a and its subclasses, and does not need to have a direct contact with a and its subclasses, B can directly use the function of a, which can be used to the various functions of a, but also good to the protection of a and its subclasses.

The relevant code for MD5 and SHA is in classes such as MD5 and Sha, but the client-facing MessageDigest abstract class does not need to deal with each implementation class, as long as it is dealt with by the delegate class.

2, MD5 Encryption 2.1 overview

Message Digest algorithm MD5 (Chinese named message Digest Algorithm version fifth) 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).

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

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

MD5 's role is to allow bulk information to be "compressed" into a confidential format before signing a private key with a digital signature software (that is, converting an arbitrary-length byte string into a long hexadecimal string).

2.2 Algorithm principle

The brief description of the MD5 algorithm can be: MD5 with 512-bit grouping to process the input information, and each grouping is divided into 16 32-bit sub-groups, after a series of processing, the output of the algorithm is composed of four 32-bit groupings, the four 32-bit grouping cascade will generate a 128-bit hash value.

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

2.3 Implementation of MD5 in Java

The Java implementation of the MD5 encryption algorithm is as follows:

Package amigo.endecrypt;

Import Java.security.MessageDigest;

/**
* With MD5 encryption
* @author Xingxing,xie
* @datetime 2014-5-31
*/
public class Md5util{
/***
* MD5 encryption generates 32-bit MD5 code
* @param the string to be encrypted
* @return return 32-bit MD5 code
*/
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");
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 ("MD5:" + 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 cryptographic experts for many years, and has now become one of the most secure hashing algorithms and is widely used. The idea of the algorithm is to receive a piece of plaintext, and then convert it into a paragraph (usually smaller) ciphertext in an irreversible way, or simply to take a string of input codes (called Pre-mapping or information) and convert them to shorter lengths, A fixed number of bits of output sequence is the process of hashing values (also known as information digests or information authentication codes). 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 regarded as the digital signature of this plaintext.

The Secure Hash algorithm SHA (Secure hash Algorithm,sha) is a national standard FIPS pub 180 released by the National Institute of Standards and Technology, and the latest standards have been updated in 2008 to FIPS pub 180-3. It stipulates the sha-1,sha-224,sha-256,sha-384, and the SHA-512 one-way hashing algorithm. sha-1,sha-224 and SHA-256 are suitable for messages that do not exceed 2^64 bits in length. SHA-384 and SHA-512 are suitable for messages that do not exceed 2^128 bits in length.

3.2 principle

SHA-1 is a data encryption algorithm, the idea of the algorithm is to receive a piece of plaintext, and then in an irreversible way to convert it into a paragraph (usually smaller) ciphertext, can also be easily understood as a string of input code (called Pre-mapping or information), and convert them to a shorter length, A fixed number of bits of output sequence is the process of hashing values (also known as information digests or information authentication codes).

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

The input message length of the algorithm is unlimited, the output is a 160-bit message digest. The input is processed in 512-bit groupings. SHA-1 is irreversible, conflict-proof and has a good avalanche effect.

The digital signature is realized by hashing algorithm, the principle of the digital signature is to transfer the plaintext through a function operation (Hash) to the report digest (different clear text corresponding to different message digest), the digest to be encrypted and sent to the receiver with the clear text, The receiving party will accept the clear text generated by the new digest to be decrypted with the sender of the digest to decrypt the comparison, the comparison results uniformly indicate that the plaintext has not been altered, if inconsistent, indicating that the plaintext has been tampered with.

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

3.3 Implementation of Sha in Java

The implementation of SHA in Java is similar to MD5, and the reference code is as follows:

Package amigo.endecrypt;

Import Java.security.MessageDigest;

/**
* with Shaa encryption
* @author Xingxing,xie
* @datetime 2014-6-1
*/
public class Shautil{
/***
* SHA encryption generates 40-bit SHA code
* @param the string to be encrypted
* @return return 40-bit 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");
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 Hou:" + shaencode (str));
}
}

The test results are as follows:

Original: Amigoxiexiexingxing

After Sha: 04f79f496dd6bdab3439511606528a4ad9caac5e

3. Comparison of SHA-1 and MD5

Because both are exported 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 security for brute force attacks : the most significant and important difference is that the SHA-1 digest is 32 bits longer than the MD5 digest. Using the brute force technique, generating any message to make its digest equal to the difficulty of a given report digest is a 2^128 order of magnitude, while for SHA-1 it is a 2^160 order of magnitude of operation. MD5 In this way, the SHA-1 has greater strength for brute force attacks.

2 Security for password Analysis : Because of the MD5 design, vulnerable to password analysis attacks, SHA-1 appear to be vulnerable to such attacks.

3 ) Speed : On the same hardware, the SHA-1 runs slower than MD5.

4. Reference documents

"MD5 Encryption _ Baidu Encyclopedia": Http://baike.baidu.com/view/1039631.htm?fr=aladdin

"Md5_ Baidu Encyclopedia": Http://baike.baidu.com/view/7636.htm?fr=aladdin

"MD5 decryption website": http://www.cmd5.com/

"Sha_ Baidu Encyclopedia":

Http://baike.baidu.com/link?url=FmqSdqu1CxQXDnQPxCD3hTdepu0RWV6N5dec5ZNWSC_U4WWle4a1h0E6744FnCRI

Encryption and decryption online testing website: http://tripledes.online-domain-tools.com/

openjdk:http://download.java.net/openjdk/jdk6/

"OpenJDK and JDK differences and connections": http://blog.csdn.net/kiyoki/article/details/8777744

Java implementation of common encryption Algorithm (i)--one-way encryption algorithm MD5 and SHA

Related Article

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

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.