Analysis of four basic encryption algorithms in Java

Source: Internet
Author: User
Tags hmac md5 digest

Analysis of four basic encryption algorithms in Java

 

Simple java encryption algorithms include:

1. BASE64

Base64 is one of the most common encoding methods used to transmit 8-bit code on the network. For details, refer to RFC2045 ~ RFC2049, which has the MIME detailed specification. Base64 encoding can be used to transmit long identification information in the HTTP environment. For example, in Java Persistence system Hibernate, Base64 is used to encode a long, unique identifier (generally 128-bit UUID) into a string, used as parameters in HTTP forms and http get URLs. In other applications, binary data is often encoded in the form of a URL including a hidden form field. At this time, Base64 encoding is not readable, that is, the encoded data is not directly seen by the human eye. Source: Baidu encyclopedia)

Java implementation code:

Package com.cn. one-way encryption; import sun. misc. BASE64Decoder; import sun. misc. BASE64Encoder;/* BASE64 encryption and decryption are bidirectional and can be reversed. BASE64Encoder and BASE64Decoder are unofficial JDK implementation classes. Although it can be found and used in JDK, it cannot be found in API. Sun and com. classes starting with sun packages are not documented. They belong to the foundation of java and javax class libraries. Most implementations are related to the underlying platform and are generally not recommended. BASE64 strictly speaking, it belongs to the encoding format, rather than the encryption algorithm mainly includes BASE64Encoder and BASE64Decoder. We only need to know how to use the corresponding method. In addition, the number of BITs generated after BASE encryption is a multiple of 8. If the number of BITs is not enough, fill the bits with =. BASE64, according to RFC2045, is defined as Base64 content Transfer Encoding. It is designed to describe the 8-bit bytes of any sequence as a form that is not easily recognized by people. The Base64 Content-Transfer-Encoding is designed to represent arbitrary sequences of octets in a form that need not be humanly readable .) common in mail and http encryption, intercepting http information, you will find that the username and password fields for login operations are encrypted by base64. */Public class BASE64 {/*** BASE64 decryption ** @ param key * @ return * @ throws Exception */public static byte [] decryptBASE64 (String key) throws Exception {return (new BASE64Decoder ()). decodeBuffer (key);}/*** BASE64 encryption ** @ param key * @ return * @ throws Exception */public static String encryptBASE64 (byte [] key) throws Exception {return (new BASE64Encoder ()). encodeBuffer (key);} public static void main (String [] args) {String str = "12345678"; try {String result1 = BASE64.encryptBASE64 (str. getBytes (); System. out. println ("result1 ===== encrypted data ==========" + result1); byte result2 [] = BASE64.decryptBASE64 (result1 ); string str2 = new String (result2); System. out. println ("str2 ========= decrypt data ========" + str2);} catch (Exception e) {e. printStackTrace ();}}}

2. MD5

MD5That is, Message-Digest Algorithm 5 Information-Digest Algorithm 5) is used to ensure the integrity and consistency of information transmission. It is one of the most widely used Hash Algorithms in computers. It also translates digest algorithms and hash algorithms. mainstream programming languages generally have MD5 implementations. Computes data such as Chinese characters) into another fixed length value, which is the basic principle of the hash algorithm. The predecessor of MD5 is MD2, MD3, and MD4. It is widely used in encryption and decryption technology and is often used for file verification. Verification? No matter how large the file is, the unique MD5 value can be generated after MD5. For example, the current ISO verification is MD5 verification. How to use it? Of course, the ISO is generated after MD5. A friend who downloads linux-ISO has seen the MD5 string next to the download link. Is used to verify whether the files are consistent.

Java implementation:

Package com.cn. one-way encryption; import java. math. bigInteger; import java. security. messageDigest;/* MD5 (Message Digest algorithm 5, information Digest algorithm) we usually do not directly use the above MD5 encryption. Usually, the byte array generated by MD5 is handed over to BASE64 and then encrypted to obtain the corresponding String Digest: Compile */public class MD5 {public static final String KEY_MD5 = "MD5 "; public static String getResult (String inputStr) {System. out. println ("======= data before encryption:" + inputStr); BigInteger bigInteger = null; try {MessageDigest md = MessageDigest. getInstance (KEY_MD5); byte [] inputData = inputStr. getBytes (); md. update (inputData); bigInteger = new BigInteger (md. digest ();} catch (Exception e) {e. printStackTrace ();} System. out. println ("after MD5 encryption:" + bigInteger. toString (16); return bigInteger. toString (16);} public static void main (String args []) {try {String inputStr = "simple encryption 8888888888888888888"; getResult (inputStr);} catch (Exception e) {e. printStackTrace ();}}}

The MD5 algorithm has the following features:

1. Compression: Data of any length, the calculated MD5 value length is fixed.
2. Easy Calculation: it is easy to calculate the MD5 value from the original data.
3. Anti-modification: Any modification to the original data, even if only one byte is modified, the MD5 value obtained is very different.
4. Weak anti-collision: it is very difficult to know the original data and its MD5 value, and to find a data with the same MD5 value, that is, to forge the data.
5. Strong anti-collision: it is very difficult to find two different data so that they have the same MD5 value.
The role of MD5 is to "compress" large-capacity information before signing a private key using digital signature software into a confidential format, which is to convert a byte string of any length into a certain length of hexadecimal number string ). In addition to MD5, sha-1, RIPEMD, and Haval are well-known.

3. SHA

Secure Hash Algorithm) is mainly applicable to Digital Signature Algorithm DSA defined in Digital Signature Standard DSS ). For messages with a length less than 2 ^ 64-bit, SHA1 generates a 160-bit message digest. This algorithm has been developed and improved by encryption experts for many years and is widely used. The idea of this algorithm is to receive a piece of plain text, and then convert it into a section of usually smaller ciphertext in an irreversible way, it can also be understood as a string of input codes called pre- ing or information ), and convert them into a short length, fixed number of digits of the output sequence, namely, the hash value is also known as information digest or information Authentication Code) process. The hash function value is a type of "fingerprint" or "abstract" of the plaintext. Therefore, the digital signature of the hash value can be considered as the digital signature of the plaintext.

Java implementation:

Package com.cn. one-way encryption; import java. math. bigInteger; import java. security. messageDigest;/* SHA (Secure Hash Algorithm, Security Hash Algorithm), digital signature, and other important cryptographic tools are widely used in e-commerce and other information security fields. Although SHA and MD5 are cracked through the collision method, SHA is still a recognized security encryption algorithm, more secure than MD5 */public class SHA {public static final String KEY_SHA = "SHA"; public static String getResult (String inputStr) {BigInteger sha = null; System. out. println ("======= data before encryption:" + inputStr); byte [] inputData = inputStr. getBytes (); try {MessageDigest messageDigest = MessageDigest. getInstance (KEY_SHA); messageDigest. update (inputData); sha = new BigInteger (messageDigest. digest (); System. out. println ("SHA encrypted:" + sha. toString (32);} catch (Exception e) {e. printStackTrace ();} return sha. toString (32);} public static void main (String args []) {try {String inputStr = "simple encryption"; getResult (inputStr);} catch (Exception e) {e. printStackTrace ();}}}

Comparison between SHA-1 and MD5

Because both are exported from MD4, SHA-1 and MD5 are similar to each other. Correspondingly, their strength is similar to other features, but there are several differences:
L security of forcible attacks: the most significant and important difference is that the SHA-1 digest is 32-bit longer than the MD5 Digest. Using forcible technology, it is difficult to generate any message so that its digest is equal to the given report. MD5 is an operation of 2 ^ 128 orders of magnitude, and SHA-1 is an operation of 2 ^ 160 orders of magnitude. In this case, SHA-1 has a greater intensity for forcible attacks.
L security of password analysis: Due to the MD5 design, SHA-1 is vulnerable to password analysis attacks.
L speed: SHA-1 is slower than MD5 on the same hardware.

4. HMAC

HMAC (Hash Message Authentication Code, Hash Message Authentication Code, and key-based Hash algorithm Authentication protocol. The message authentication code uses a public function and a key to generate a fixed-length value as the authentication identifier, which identifies the integrity of the message. Use a key to generate a small data block of a fixed size, that is, MAC, and add it to the message for transmission. The receiver uses the key shared with the sender for authentication.

Java implementation code:

Package com.cn. unidirectional encryption;/* HMAC (Hash Message Authentication Code, Hash Message Authentication Code, and key-based Hash algorithm Authentication protocol. The message authentication code uses a public function and a key to generate a fixed-length value as the authentication identifier, which identifies the integrity of the message. Use a key to generate a small data block of a fixed size, that is, MAC, and add it to the message for transmission. The receiver uses the key shared with the sender for authentication. */Import javax. crypto. keyGenerator; import javax. crypto. mac; import javax. crypto. secretKey; import javax. crypto. spec. secretKeySpec; import com.cn. comm. tools;/*** basic encryption component */public abstract class HMAC {public static final String KEY_MAC = "HmacMD5 "; /*** initialize the HMAC key ** @ return * @ throws Exception */public static String initMacKey () throws Exception {KeyGenerator keyGenerator = KeyGenerator. getInstance (KEY_MAC); SecretKey secretKey = keyGenerator. generateKey (); return BASE64.encryptBASE64 (secretKey. getEncoded ();}/*** HMAC encryption: main method ** @ param data * @ param key * @ return * @ throws Exception */public static String encryptHMAC (byte [] data, String key) throws Exception {SecretKey secretKey = new SecretKeySpec (BASE64.decryptBASE64 (key), KEY_MAC); Mac mac = Mac. getInstance (secretKey. getAlgorithm (); mac. init (secretKey); return new String (mac. doFinal (data);} public static String getResult1 (String inputStr) {String path = Tools. getClassPath (); String fileSource = path + "/file/HMAC_key.txt"; System. out. println ("======= data before encryption:" + inputStr); String result = null; try {byte [] inputData = inputStr. getBytes (); String key = HMAC. initMacKey ();/* generate key */System. out. println ("Mac key: =" + key);/* write the key to the file */Tools. writeMyFile (fileSource, key); result = HMAC. encryptHMAC (inputData, key); System. out. println ("after HMAC encryption: =" + result);} catch (Exception e) {e. printStackTrace ();} return result. toString ();} public static String getResult2 (String inputStr) {System. out. println ("======= data before encryption:" + inputStr); String path = Tools. getClassPath (); String fileSource = path + "/file/HMAC_key.txt"; String key = null; try {/* read the key from the file */key = Tools. readMyFile (fileSource); System. out. println ("getResult2 key: =" + key);} catch (Exception e1) {e1.printStackTrace ();} String result = null; try {byte [] inputData = inputStr. getBytes ();/* encrypt data */result = HMAC. encryptHMAC (inputData, key); System. out. println ("after HMAC encryption: =" + result);} catch (Exception e) {e. printStackTrace ();} return result. toString ();} public static void main (String args []) {try {String inputStr = "simple encryption";/* use the same key to encrypt data: check whether the encryption results are the same */getResult1 (inputStr); getResult2 (inputStr);} catch (Exception e) {e. printStackTrace ();}}}

 

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.