This article mainly introduces the commonly used encryption algorithms for Java implementation - one-way encryption algorithms MD5 and SHA, as follows:
1. Java's security architecture
1.1 Introduction to Java's security architecture
Provide classes and interfaces for security frameworks in Java. The JDK Security API is the core API of the Java programming language, located in the java.security package (and its subpackages), as well as the sun.securityAPI package (and its subpackages). Designed to help developers use both low-level and advanced security features in their programs.
The first release of JDK in JDK 1.1 introduced the "Java Encryption Architecture" (JCA), which refers to the architecture used to access and develop Java platform password functions. In JDK 1.1, JCA includes an API for digital signatures and message digests. JDK 1.2 greatly extends 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 and extensible access control.
The Java encryption architecture includes the password-related parts of the JDK 1.2 security API, as well as a set of conventions and specifications provided in this document. To implement multiple, interoperable passwords, it also provides a "provider" architecture.
Java Password Extension (JCE)) extends the JCA API, including APIs for encryption, key exchange, and information authentication codes (MAC). JCE and JDK passwords together provide a complete password API that is not related to the platform. JCE as an extension of JDK will be released independently to comply with US export control constraints.
1.2 Related source code of JDK in Eclipse
In order to have a deeper understanding of the implementation of the one-way encryption algorithms MD5 and SHA in Java, the source code of the JDK can be associated with using the Eclipse IDE (the author uses JDK6.0).
After the installation of JDK6.0 is completed, there is the src.zip directory in the root directory of JDK (eg. C:/Java/jdk1.6.0_21). This directory can be decompressed to another directory (eg. D:/amigo/study/Technical Essay/201405). src.zip does not contain all JDK source code. For example, the subpackages under sun do not exist in src.zip (eg. The sun.security package and its subpackages used in this article are not included).
To download these subpackages, you need to download the source code of OpenJDK. openjdk is the open source version of jdk and is released in the form of GPL protocol. At JDK7, openjdk had become the backbone development of jdk7. Sun jdk7 was released on the basis of openjdk7. Most of its original codes are the same, and only a small part of the original codes were replaced. Published using JRL (JavaResearch License, Java Research License Agreement).
OpenJDK download address: //www.VeVB.COM/softs/75724.html
After downloading, copy all the files and folders in the unzipped openjdk-6-src-b27-26_oct_2012/jdk/src/share/classes directory to the unzipped src directory.
Next, configure the associated source code in Eclipse: click "Windows"-> "Preferences", and select "Java"-> "Installed JREs" in the left menu. If the JRE of this machine has been configured, you do not need to configure it. If not configured, click the "Add" button on the right and select the path of the installed JDK6.0 in the pop-up "Add JRE" window (eg. C:/Java/jdk1.6.0_21). Click the "OK" button to complete the settings of JRE.
Select the set JRE, 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 path of the src just now (eg. D:/amigo/study/Technical Essay/201405). See the figure below:
After clicking the "OK" button to set it up, when writing the implementation of MD5 and SHA, when calling the relevant methods of MessageDigest, you can use debug mode F5 single-step debugging to view the classes mainly involved in the implementation of MD5 and SHA one-way encryption algorithms in Java.
1.3 The main classes of MD5 and SHA encryption in JDK
In JDK6.0, the class diagrams of several classes closely related to MD5 and SHA are as follows:
Among them, "MessageDigestSpi" is the top-level abstract class, and "MessageDigest" and "DigestBase" under the same package are sub-abstract classes.
In the class diagram above, the Delegate design pattern is used. The principle of this pattern is that class B (here is the Delegage inner class) and class A (here is the MessageDigestSpi class) are two classes that have no relationship with each other. B has exactly the same methods and attributes as A; and calling methods and attributes in B is to calling methods and attributes with the same name in A. B seems to be an intermediary authorized by A. Third-party code does not need to know the existence of A and its subclasses, nor does it need to have a direct connection with A and its subclasses. Through B, the functions of A can be directly used, which can not only use various functions of A, but also protect A and its subclasses well.
The relevant codes for MD5 and SHA are all in classes such as MD5 and SHA, but the customer-facing MessageDigest abstract class does not need to deal with various implementation classes, just deal with them through the delegate class.
2. MD5 encryption
2.1 Overview
Message Digest Algorithm MD5 (Chinese name is Message Digest Algorithm Fifth Edition) is a hash function widely used in the field of computer security to provide message integrity protection. The file number of this algorithm 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-Abstract Algorithm), developed by Ronald L. Rivest of MIT Laboratory for Computer Science and RSA Data Security Inc in the early 1990s, and developed by MD2, MD3 and MD4.
MD5 is used to ensure complete and consistent information transmission. It is one of the hash algorithms widely used by computers (also translated as abstract algorithm and hash algorithm). The mainstream programming languages are generally implemented by MD5. Calculating data (such as Chinese characters) into another fixed-length value is the basic principle of the hash algorithm. The predecessors of MD5 were MD2, MD3 and MD4.
The function of MD5 is to allow large-capacity information to be "compressed" into a confidential format before signing a private key with digital signature software (that is, to convert a byte string of any length into a hexadecimal string of a certain length).
2.2 Algorithm Principles
A brief description of the MD5 algorithm can be as follows: MD5 processes the input information in 512-bit packets, and each packet is divided into 16 32-bit sub-packets. After a series of processing, the output of the algorithm consists of four 32-bit packets. After cascading these four 32-bit packets, a 128-bit hash value will be generated.
In the MD5 algorithm, the information needs to be filled first, so that the result of the remaining balance of its bit length pair 512 is equal to 448. Therefore, the bit length of the information will be extended to N*512+448, N is a non-negative integer, and N can be zero. The filling method is as follows: fill a 1 and countless 0s behind the information, and stop filling the information with 0 until the above conditions are met. Then, an upper-fill information length is attached in 64-bit binary. After these two steps of processing, the bit length of the information = N*512+448+64=(N+1)*512, that is, the length is exactly an integer multiple of 512. The reason for this is to meet the requirements for information length in the subsequent processing.
2.3 MD5 implementation in Java
The Java implementation of MD5 encryption algorithm is as follows:
package amigo.endecrypt;import java.security.MessageDigest;/** * Use MD5 encryption* @author Xingxing,Xie * @datetime 2014-5-31 */public class MD5Util { /*** * MD5 encryption generates 32-bit md5 code* @param 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
Post-MD5: e9ac094091b96b84cca48098bc21b1d6
3. SHA encryption
3.1 Overview
SHA is a data encryption algorithm. This algorithm has been developed and improved by encryption experts over the years and has become increasingly perfect. It has now become one of the most secure hashing algorithms recognized and has been widely used. The idea of this algorithm is to receive a plain text and then convert it into a (usually smaller) cipher text in an irreversible way. It can also be simply understood as the process of taking a string of input codes (called premapping or information) and converting them into a shorter-length, fixed-digit output sequence, i.e. hash values (also known as information digest or information authentication code). The hash function value can be said to be a kind of "fingerprint" or "summary" of the plaintext, so the digital signature of the hash value can be regarded as the digital signature of the plaintext.
The Secure Hash Algorithm (SHA) is the national standard FIPS PUB 180 released by the National Institute of Standards and Technology. The latest standard has been updated to FIPS PUB 180-3 in 2008. Among them, several unidirectional hashing algorithms such as SHA-1, SHA-224, SHA-256, SHA-384, and SHA-512 are specified. SHA-1, SHA-224 and SHA-256 are suitable for messages with a length of no more than 2^64 binary bits. SHA-384 and SHA-512 are suitable for messages with a length of no more than 2^128 binary bits.
3.2 Principle
SHA-1 is a data encryption algorithm. The idea of this algorithm is to receive a plain text and then convert it into a (usually smaller) cipher text in an irreversible way. It can also be simply understood as the process of taking a string of input codes (called premapping or information) and converting them into a shorter-length, fixed-digit output sequence, i.e. hash values (also known as information digest or information authentication code).
The safety of a one-way hash function lies in the strong one-way nature of its operation process of generating hash values. If a password is embedded in the input sequence, no one can generate the correct hash value without knowing the password, thus ensuring its security. SHA blocks the input streams in 512 bits (64 bytes) per block and produces 20 bytes of output called information authentication code or information digest.
The length of the input packets of this algorithm is unlimited, and the output generated is a 160-bit message digest. The input is processed in 512-bit packets. SHA-1 is irreversible, conflict-proof, and has a good avalanche effect.
Digital signature can be implemented through a hash algorithm. The principle of digital signature is to convert the plain text to be transmitted into a message digest through a function operation (hash) (different plain texts correspond to different message digests). The message digest is encrypted and sent to the recipient together with the plain text. The recipient generates a new message digest to decrypt and compares the message digest sent by the sender. The comparison result is consistent, which means that the plain text has not been changed. If it is inconsistent, it means that the plain text has been tampered with.
MAC (Information Authentication Code) is a hash result, in which part of the input information is a password. Only participants who know this password can calculate and verify the legitimacy of the MAC code again.
3.3 SHA implementation in Java
The Java implementation of SHA is similar to MD5, and the reference code is as follows:
package amigo.endecrypt;import java.security.MessageDigest;/** * Use SHAA encryption* @author Xingxing,Xie * @datetime 2014-6-1 */public class SHAUtil { /*** * SHA encryption generates 40-bit SHA code* @param 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:" + shaEncode(str)); }}The test results are as follows:
Original: amigoxiexiexingxing
After SHA: 04f79f496dd6bdab3439511606528a4ad9caac5e
3. Comparison between SHA-1 and MD5
Because both are derived from MD4, SHA-1 and MD5 are very similar to each other. Correspondingly, their strength and other characteristics are similar, but there are also differences in the following points:
1) Security against forced attacks: The most significant and important difference is that the SHA-1 digest is 32 bits longer than the MD5 digest. Using forced technology, the difficulty of generating any message so that its digest is equal to a given digest is an operation of the order of 2^128 for MD5 and an operation of 2^160 for SHA-1. In this way, SHA-1 has greater strength for forcibly attacks.
2) Security of password analysis: Due to the design of MD5, it is vulnerable to password analysis, and SHA-1 seems to be less susceptible to such attacks.
3) Speed: On the same hardware, SHA-1 runs slowly than MD5.
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.