Java Basic encryption algorithm

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:

 Packagecom.cn. One-way encryption;ImportSun.misc.BASE64Decoder;ImportSun.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, 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 classBASE64 {/*** BASE64 Decryption * *@paramKey *@return       * @throwsException*/       Public Static byte[] decryptBASE64 (String key)throwsException {return(NewBase64decoder ()). Decodebuffer (key); }             /*** BASE64 Encryption * *@paramKey *@return       * @throwsException*/       Public StaticString encryptBASE64 (byte[] key)throwsException {return(NewBase64encoder ()). Encodebuffer (key); }       Public Static voidMain (string[] args) {String str= "12345678"; Try{String result1=base64.encryptbase64 (Str.getbytes ()); System.out.println ("result1===== Encrypted data ==========" +RESULT1); byteresult2[]=base64.decryptbase64 (RESULT1); String str2=NewString (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, 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 implementations:

 Packagecom.cn. One-way encryption;ImportJava.math.BigInteger;Importjava.security.MessageDigest;/*MD5 (Message Digest algorithm 5, Information Digest algorithm) usually we do not use the above MD5 encryption directly. Usually the byte array produced by the MD5 is given to BASE64 and then encrypted to get the corresponding string digest: assembly*/ Public classMD5 { Public Static FinalString key_md5 = "MD5";  Public Staticstring 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=NewBigInteger (Md.digest ()); } Catch(Exception e) {e.printstacktrace ();} System.out.println ("MD5 after encryption:" + biginteger.tostring (16)); returnBiginteger.tostring (16); }         Public Static voidMain (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:

 Packagecom.cn. One-way encryption;ImportJava.math.BigInteger;Importjava.security.MessageDigest;/*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, Sha is still recognized as a secure cryptographic algorithm that is more secure than MD5*/ Public classSHA { Public Static FinalString Key_sha = "SHA";  Public Staticstring 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=NewBigInteger (Messagedigest.digest ()); System.out.println ("Sha Encrypted:" + sha.tostring (32)); } Catch(Exception e) {e.printstacktrace ();} returnSha.tostring (32); }         Public Static voidMain (String args[]) {Try{String Inputstr= "Simple Encryption";        GetResult (INPUTSTR); } Catch(Exception e) {e.printstacktrace (); }                    }    }  
comparison of SHA-1 and MD5Because 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 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:

 Packagecom.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. */ImportJavax.crypto.KeyGenerator;ImportJavax.crypto.Mac;ImportJavax.crypto.SecretKey;ImportJavax.crypto.spec.SecretKeySpec;ImportCom.cn.comm.Tools; /*** Basic Cryptographic Components*/   Public Abstract classHMAC { Public Static FinalString Key_mac = "HmacMD5"; /*** Initialize HMAC key * *@return       * @throwsException*/       Public StaticString Initmackey ()throwsException {keygenerator keygenerator=keygenerator.getinstance (KEY_MAC); Secretkey Secretkey=Keygenerator.generatekey (); returnbase64.encryptbase64 (secretkey.getencoded ()); }         /*** HMAC Encryption: Main Method * *@paramData *@paramKey *@return       * @throwsException*/       Public StaticString Encrypthmac (byte[] data, String key)throwsException {secretkey Secretkey=NewSecretkeyspec (Base64.decryptbase64 (key), KEY_MAC); Mac Mac=mac.getinstance (Secretkey.getalgorithm ());           Mac.init (Secretkey); return NewString (mac.dofinal (data)); }                        Public Staticstring 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 key to file*/Tools.writemyfile (Filesource,key); Result=Hmac.encrypthmac (Inputdata, key); System.out.println ("After HMAC encryption: = = =" +result); } Catch(Exception e) {e.printstacktrace ();} returnresult.tostring (); }         Public Staticstring 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 the data*/result=Hmac.encrypthmac (Inputdata, key); System.out.println ("After HMAC encryption: = = =" +result); } Catch(Exception e) {e.printstacktrace ();} returnresult.tostring (); }         Public Static voidMain (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 (); }                    }    }  

Java Basic encryption algorithm

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.