Basic Java encryption algorithm MD5 and so on.

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

The simple Java encryption algorithm is: BASE64 strictly speaking, it belongs to the encoding format, not the encryption algorithm MD5 (Message Digest algorithm 5, Information Digest algorithm) SHA (Secure Hash algorithm, security hashing algorithm) HMAC (Hash message authentication code, hash messages authentication code)Analysis of 4 basic encryption algorithms in Java 1. BASE64Base64 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 One-way encryption; import Sun.misc.base64decoder;import sun.misc.base64encoder;/* The encryption and decryption of BASE64 is bidirectional and can be reverse-solved. 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, not the encryption algorithm   is mainly Base64encoder, base64decoder two classes, we just need to know how to use the corresponding method. 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 code is designed to describe any sequence of 8 bytes as a form that is not easily recognizable by humans. (The Base64 content-transfer-encoding is designed to represent arbitrary sequences of octets in a form that need not being HU Manly readable.)   commonly used 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 {&NBsp  /**       * BASE64 decryption       *        * @param key & nbsp;     * @return       * @throws Exception       */     public static byte[] decryptBASE64 (String key) throws Exception {          return ( New Base64decoder ()). Decodebuffer (key);             /**       * BASE64 encryption      & nbsp;*        * @param key       * @return       * @throw s Exception       */     public static String encryptBASE64 (byte[] key) throws Excepti On {          return (new Base64encoder ()). Encodebuffer (key);      } & nbsp;     public static void main (string[] args) {      string &NBSp;str= "12345678";         Try {        String  result1= Base64.encrypt BASE64 (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 ();   } &N Bsp  } }  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, and 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 implementation:  package 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 (+);   }     public static V OID Main (String args[])     {        Try {             STR ing INPUTSTR = "simple encryption 8888888888888888888";                getresult (INPUTSTR);       } catch (Excep tion e) {            e.printstacktrace ();       }    }& nbsp;} The  MD5 algorithm has the following characteristics:  1, compressibility: Any length of data, the calculated 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 values are 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 The   Secure Hash Algorithm (algorithm) is primarily used for digital signature algorithms (digitally Signature algorithm) defined in the digital Signature standard DSS. DSA). 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 implementation:  package One-way encryption;  import Java.math.biginteger;import;  /*sha (Secure Hash algorithm, secure Hash 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,  but Sha is still recognized as a secure cryptographic 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);  & nbsp     byte[] Inputdata = Inputstr.getbytes ();           Try {             messagedigest messagedigest = Messagedigest.getinstanc E (Key_sha);               messagedigest.update (inputdata);             sha = new BigInteger (Messagedigest.digest ());                SYSTEM.OUT.PRINTLN ("Sha after encryption:" + sha.tostring (32));          } catch (Exception e) {e.printstacktrace ();}         return sha.tostring (+);   }     public static void main (String args [])     {        Try {             string INPUTSTR = "Simple encryption ";                getresult (INPUTSTR);       } catch (Excep tion e) {            e.printstacktrace ();       }    }& NBSP;} 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: l 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 messages authentication code, hash message 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 One-way encryption,/*HMAC HMAC (hash message authentication code, hash messages authentication code, The authentication protocol of hash algorithm based on key. 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; /**   * Basic cryptographic Components   */  Public abstract class HMAC {      public static final String Key_mac = "HmacMD5";    & nbsp  /**       * initialize HMAC key       *        * @return &NB sp;     * @throws Exception       */     public static String InitmackeY () throws Exception {          Keygenerator keygenerator = keygenerator.getinstance (key_m AC);           Secretkey Secretkey = Keygenerator.generatekey ();           return base64.encryptbase64 (secretkey.getencoded ());      }       /**       * HMAC encryption  : Main methods   &NBS P  *        * @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 fi lesource=path+ "/file/hmac_key.txt";        SYSTEM.OUT.PRINTLN ("Data before ======= Encryption:" +INPUTSTR);         String  result=null;        Try {          & nbsp byte[] Inputdata = inputstr.getbytes ();             String key = Hmac.initmackey (); /* Generate key */             SYSTEM.OUT.PRINTLN ("mac key: = = =" + key);             /* Write key file */            Tools.writemyfile (file Source,key);            result= Hmac.encrypthmac (Inputdata, key); &NBSp           SYSTEM.OUT.PRINTLN ("HMAC encrypted: = = = =" + result);        } catch (E Xception e) {e.printstacktrace ();}         return result.tostring ();   }      public static  string  getresult2 (String inputstr)     {        Syste M.out.println ("======= Data before Encryption:" +INPUTSTR);         string Path=tools.getclasspath ();         string filesource=path+ "/file/hmac_key.txt";         string key= null;;         Try {             /* to read a key from a file */             key=tools.readmyfile (filesource);              System.out.println ("getResult2 key: = = = =" + key);         } catch (Exception E1) {            e1.printstacktrace ();}   &NBSp     String  result=null;        Try {            byte[] I Nputdata = Inputstr.getbytes ();             /* Data encryption */            result= hmac.encrypth MAC (Inputdata, key);            SYSTEM.OUT.PRINTLN ("after HMAC encryption: = = = =" + result);   & nbsp    } catch (Exception e) {e.printstacktrace ()}         return result.tostring (); &nbs P  }     public static void Main (String args[])     {        Try {  & nbsp          string INPUTSTR = "Simple Encryption";              /* Use the same key: Encrypt data: See if two encryption results are the same */             GETRESULT1 (INPUTSTR);              GETRESULT2 (INPUTSTR);        } catch (Exception E) {            e.printstacktrace ();       }    } }

Basic Java encryption algorithm MD5 and so on

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: 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.