Analysis of 4 basic encryption algorithms in Java

Source: Internet
Author: User
Tags base64 hmac md5 digest md5 encryption

The simple Java encryption algorithm is:

    1. BASE64 strictly speaking, it belongs to the encoding format, not the encryption algorithm
    2. MD5 (Message Digest algorithm 5, Information Digest algorithm)
    3. SHA (Secure Hash algorithm, security hashing algorithm)
    4. HMAC (Hash message authentication code, hash messages authentication code)
1. BASE64

Base64 is one of the most common encoding methods for transmitting 8Bit bytes of code on the network, and you can view rfc2045~rfc2049, which has a detailed specification of MIME. BASE64 encoding can be used to pass longer identity information in an HTTP environment. For example, in the Java Persistence System hibernate, Base64 is used to encode a long unique identifier (typically 128-bit uuid) as a string that is used as a parameter in an HTTP form and an HTTP GET URL. In other applications, it is often necessary to encode binary data as appropriate in the form of URLs (including hidden form fields). At this time, the use of BASE64 encoding is not readable, that is, the encoded data will not be directly visible to the naked 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 is bidirectional, you can find the inverse solution. Base64encoder and Base64decoder are unofficial JDK implementation classes. Although it can be found and used in the JDK, it is not available in the API. The classes in the JRE, Sun and Com.sun, are not documented, they belong to the Java, Javax Class library, where implementations are mostly related to the underlying platform and are generally deprecated. BASE64 strictly speaking, belong to the encoding format, but not the encryption algorithm is mainly Base64encoder, base64decoder two classes, we just need to know the corresponding method can be used. Also, the number of bytes generated after base encryption is a multiple of 8 if the number of digits is not enough to be populated with the = sign. BASE64 as defined by RFC2045, Base64 is defined as: the Base64 content transfer encoding is designed to describe any sequence of 8 bytes as a form that is not easy to be recognized directly. (The Base64 content-transfer-encoding is designed to represent arbitrary sequences of octets in a form that need not being HU Manly readable.) common in mail, HTTP encryption, interception of HTTP information, you will find the login operation of the user name, password field through BASE64 encryption.       */public class BASE64 {/** * BASE64 decryption * * @param key * @return * @throws Exception */public static byte[] decryptBASE64 (String key) throws Exception {return (new Base64decoder ()). Decodeb       Uffer (key);     }/** * BASE64 encryption * * @param key * @return * @throws Exception  */public static String encryptBASE64 (byte[] key) throws Exception {return (new Base64encoder ()). Encodeb       Uffer (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======== decryption Data ========" +STR2);    } catch (Exception e) {e.printstacktrace (); }    }}
2. MD5

MD5 is message-digest algorithm 5 (Information-Digest algorithm 5), which is used to ensure complete and consistent 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, the predecessor of MD5 is MD2, MD3 and MD4. Widely used in encryption and decryption technology, often used for file verification. Check? No matter how large the file is, a unique MD5 value can be generated after MD5. Like now the ISO check, all is MD5 check. How to use it? It is of course the value of MD5 after the ISO has been MD5. General Download Linux-iso friends have seen the download link next to the MD5 string. is used to verify that the files are consistent.

Java implementations:

Package com.cn. One-way encryption, import Java.math.biginteger;import java.security.messagedigest;/*md5 (Message Digest algorithm 5, Information digest algorithm) usually we do not use the above MD5 encryption directly.       The MD5 generated byte array is usually given to BASE64 and then encrypted, to get the corresponding string digest: assembly */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 ("MD5 after 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 characteristics:

1, compressibility: Any length of data, calculated the length of the MD5 value is fixed.
2, easy to calculate: It is easy to calculate the MD5 value from the original data.
3, anti-modification: Any changes to the original data, even if only 1 bytes modified, the resulting MD5 value is very different.
4, weak anti-collision: known raw data and its MD5 value, it is very difficult to find a data with the same MD5 value (that is, falsification of data).
5, strong anti-collision: To find two different data, so that they have the same MD5 value, is very difficult.
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). In addition to MD5, among them the more famous are sha-1, Ripemd and Haval and so on.

3.SHA

Secure Hash algorithm is primarily intended for digital Signature algorithm DSA, which is defined in the digital Signature standard DSS. For messages that are less than 2^64 bits in length, SHA1 produces a 160-bit message digest. The algorithm has been developed and improved by cryptographic experts for many years 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.

Java implementations:

Package com.cn. One-way encryption, import Java.math.biginteger;import Java.security.messagedigest;/*sha (Secure Hash algorithm, Security hashing algorithm), digital signature and other cryptographic applications of important tools, is widely used in e-commerce and other information security fields.       Although both Sha and MD5 have been cracked by the collision method, Sha is still recognized as a secure cryptographic algorithm that is 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 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:
• 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.
Security of password Analysis: Because of the MD5 design, vulnerable to password analysis attacks, SHA-1 appear to be vulnerable to such attacks.
L Speed: On the same hardware, the SHA-1 runs slower than MD5.

4.HMAC

HMAC (Hash message authentication code, hash messages identification code, cryptographic hash algorithm based on the key authentication protocol. The principle of authentication of message identification code is to use public functions and keys to generate a fixed-length value as a certification identifier, which is used to identify the integrity of the message. Use a key to generate a small, fixed-size block of data, the Mac, and add it to the message and transfer it. The receiver uses the key shared with the sender for authentication, and so on.

Java implementation code:

Package com.cn. One-way encryption,/*hmac HMAC (hash message authentication code, hash messages identification code, cryptographic hash algorithm based on the key authentication protocol. The principle of authentication of message identification code is to use public functions and keys to generate a fixed-length value as a certification identifier, which is used to identify the integrity of the message. Use a key to generate a small, fixed-size block of data, the Mac, and add it to the message and transfer it. The receiver uses the key shared with the sender for authentication, and so on. */import Javax.crypto.keygenerator;import Javax.crypto.mac;import Javax.crypto.secretkey;import Javax.crypto.spec.secretkeyspec;import com.cn.comm.tools;/** * Basic Cryptographic component */public abstract class HMAC {public St       atic final String Key_mac = "HmacMD5"; /** * Initialize HMAC key * * @return * @throws Exception */public static String Initmackey () t           Hrows Exception {Keygenerator keygenerator = keygenerator.getinstance (KEY_MAC);           Secretkey Secretkey = Keygenerator.generatekey ();       Return Base64.encryptbase64 (secretkey.getencoded ());       }/** * HMAC encryption: Primary 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 file */Tools.writemyfile (Filesource,key);            result= Hmac.encrypthmac (Inputdata, key);         SYSTEM.OUT.PRINTLN ("HMAC encrypted: = = = =" + 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 {/* will 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 ("HMAC encrypted: = = = =" + result);         } catch (Exception e) {e.printstacktrace ();}    return result.tostring ();              } public static void Main (string args[]) {try {string inputstr = "Simple Encryption";              /* Use the same key: Encrypt the data: see if the results of two encryption are the same */GETRESULT1 (INPUTSTR);        GETRESULT2 (INPUTSTR);        } catch (Exception e) {e.printstacktrace (); }    }}

This paper draws on http://www.codeceo.com/article/java-4-encryption.html

Analysis of 4 basic encryption algorithms in Java

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.