Java Encryption and decryption __java

Source: Internet
Author: User
Overview:
For security reasons, transport data is often encrypted and encoded in the transmission of the network, which involves the following:

1, MD5 encryption, the encryption algorithm is one-way encryption, that is, the encrypted data can no longer be restored by decryption. The related classes are included in the Java.security.MessageDigest package.

2, 3-des encryption, the encryption algorithm is reversible, the decryption party can be encrypted by the agreement with the secret key to decrypt. The related classes are included in the javax.crypto.* package.

3. Base64 encoding is the most commonly used encoding method for transmitting 8bit byte code. Related classes are in Sun.misc.BASE64Decoder and Sun.misc.BASE64Encoder.

4, Urlencoder code, is a character encoding, to ensure that the parameters are transmitted by following the specification of the text composition. The related class is in the Java.net.URLEncoder package.

Details:
1, to carry out MD5 encryption, get byte[]/** * MD5 encryption * @param String of the original Spkey * @return byte[] Specify the encryption mode MD5 after byte[]/private byte[] MD5 (string STRSRC) {byte[] returnbyte = null; try {messagedigest MD5 = messagedigest.getinstance ("MD5"); returnbyte = Md5.digest (s Trsrc.getbytes ("GBK")); catch (Exception e) {e.printstacktrace ();} return returnbyte; 2, Get 3-des key/** * Get the 3-des key * According to the need, such as the secret key is 24 bytes, MD5 encryption is 16 bytes, so after 8 bytes of 0 * @param String original Spkey * @return byte[] Specifies that the encryption method is MD5 byte[]/private byte[] Getenkey (String spkey) {byte[] deskey=null; try {byte[] desKey1 = MD5 (spkey); DesK EY = new BYTE[24]; int i = 0; while (I < deskey1.length && I <) {Deskey[i] = Deskey1[i]; i++} if (I <) {Deskey[i] = 0; i++;} catch (Exception e) {e.printstacktrace ();} return deskey; } 3, 3-des encryption/** * 3-des encryption * @param byte[] src to 3-des encrypted byte[] * @param byte[] enkey 3-des encryption key * @return byte[] 3-des encrypted byte[] */public byte[] Encrypt (byte[] src,byte[] enkey) {byte[] EncryptedData = null;try {desedekeyspec DKs = new Desedekeyspec (Enkey); Secretkeyfactory keyfactory = secretkeyfactory.getinstance ("Desede"); Secretkey key = Keyfactory.generatesecret (DKS); Cipher Cipher = cipher.getinstance ("Desede"); Cipher.init (Cipher.encrypt_mode, key); EncryptedData = cipher.dofinal (src); catch (Exception e) {e.printstacktrace ();} return EncryptedData; 4. BASE64 Encoding of Strings/** * BASE64 encoding of Strings * @param byte[] src the character to encode * * * @return string to encode the strings/public string getbase 64Encode (byte[] src) {String requestvalue= ""; try{base64encoder base64en = new Base64encoder (); requestvalue=base64en.e Ncode (SRC); System.out.println (Requestvalue); catch (Exception e) {e.printstacktrace ();} return requestvalue; 5, according to the need to remove the string of newline symbol/** * Remove the string line symbol * Base64 encoded 3-des data, the resulting string has a newline symbol, as required can be removed * * * private string filter (String str) {Stri NG output = null; StringBuffer sb = new StringBuffer (); for (int i = 0; i < str.length (); i++) {int ASC = Str.charat (i); if (ASC!= && ASC!=) SB. Append (Str.subsequence (i, i + 1)); Output = new String (SB); return output; 6. Urldecoder.encode (strencoding) Encoding of Strings/** * Urldecoder.encode (strencoding) Encoding of strings * @param string src strings to encode * * String encoded by @return String */public string Geturlencode (string src) {string requestvalue= ""; try{Requestvalue = Urlencod Er.encode (SRC); catch (Exception e) {e.printstacktrace ();} return requestvalue; 7. Urldecoder.decode (strencoding) Decoding of Strings/** * Urldecoder.decode (strencoding) Decoding of Strings * @param string src strings to be decoded * * The string that is decoded @return String */public string Geturldecoderdecode (string src) {string requestvalue= ""; try{Requestvalue = U Rldecoder.decode (SRC); catch (Exception e) {e.printstacktrace ();} return requestvalue; 8, carry out 3-des decryption (the key is equivalent to the encryption key)/** * * for 3-des decryption (the secret key is equivalent to the encryption key). * @param byte[] src to be 3-des decrypted byte[] * @param string Spkey Allocated Spkey * @return string 3-des decrypted string/public string decry PT (byte[] debase64,string spkey) {String strde = null; Cipher Cipher = null; try { Cipher=cipher.getinstance ("Desede"); byte[] key = Getenkey (Spkey); Desedekeyspec DKs = new Desedekeyspec (key); Secretkeyfactory keyfactory = secretkeyfactory.getinstance ("Desede"); Secretkey SKey = Keyfactory.generatesecret (DKS); Cipher.init (Cipher.decrypt_mode, SKey); byte ciphertext[] = cipher.dofinal (debase64); Strde = new String (ciphertext, "utf-16le"); catch (Exception ex) {Strde = ""; Ex.printstacktrace (); return Strde; After the above steps can be completed MD5 encryption, 3-des encryption, base64 encoding transmission, base64 decoding, 3-des decryption get the original text. The full text of the procedure is as follows: Package com.neusoft.test.util.crypt; Import java.io.IOException; Import java.io.UnsupportedEncodingException; Import Java.net.URLDecoder; Import Java.net.URLEncoder; Import Java.security.MessageDigest; Import Java.text.SimpleDateFormat; Import Java.util.Calendar; Import Javax.crypto.Cipher; Import Javax.crypto.SecretKey; Import Javax.crypto.SecretKeyFactory; Import Javax.crypto.spec.DESedeKeySpec; Import Sun.misc.BASE64Decoder; Import Sun.misc.BASE64Encoder; /** * <p>title: Encryption and decryption Test </p> * * <p>description: Encryption and Decryption </p> * *<p>date:2005-08-11</p> * * <p>copyright:copyright (c) 20 neusoft</p> * * <p>Company:neusoft</p> * * * @author MENGK * @version 1.00 * * <p>--------------(* * * * * * * * * ----------------------------------------------</p> * <p> modification History </p> * <p> serial number date modification reason </p > * <p> 1 </p>/public class Endecrypt {/** * MD5 encryption * @param String Original Spkey * @return byte[] Specify the encryption method as M D5 byte[] * * Private byte[] MD5 (String strsrc) {byte[] returnbyte = null; try {messagedigest = MD5 Tance ("MD5"); Returnbyte = Md5.digest (Strsrc.getbytes ("GBK")); catch (Exception e) {e.printstacktrace ();} return returnbyte; /** * Get 3-des Key * According to the interface specification, the secret key is 24 bytes, the MD5 is 16 bytes encrypted, so the 0 * @param String of 8 bytes is followed by the original Spkey * @return byte[] Specifies the encryption method is MD5 by te[] */private byte[] Getenkey (String spkey) {byte[] deskey=null; try {byte[] desKey1 = MD5 (spkey); deskey = new byte[2 4]; int i = 0; while (i < deskey1.length && I <) {Deskey[i] = Deskey1[i]; i++} if (I <) {Deskey[i] = 0; i++;}} catch (Exception e) {e.printstacktrace ();} return deskey; }/** * 3-des encryption * @param byte[] src 3-des encrypted byte[] * @param byte[] enkey 3-des encryption key * @return byte[] 3-des encrypted byte[] * * * Public byte[] Encrypt (byte[] src,byte[] enkey) {byte[] EncryptedData = null; try {desedekeyspec dks = new Desedekeyspec ( Enkey); Secretkeyfactory keyfactory = secretkeyfactory.getinstance ("Desede"); Secretkey key = Keyfactory.generatesecret (DKS); Cipher Cipher = cipher.getinstance ("Desede"); Cipher.init (Cipher.encrypt_mode, key); EncryptedData = cipher.dofinal (src); catch (Exception e) {e.printstacktrace ();} return EncryptedData; /** * BASE64 Encoding of Strings * @param byte[] SRC character * * encoded by @return string/public string Getbase64encode (byte[] s RC) {String requestvalue= ""; try{base64encoder base64en = new Base64encoder (); Requestvalue=base64en.encode (SRC);//Sys Tem.out.println (requesTValue); catch (Exception e) {e.printstacktrace ();} return requestvalue; /** * Remove string newline symbol * Base64 encoded 3-des data, the resulting string has a newline symbol *, must be removed, otherwise uni-wise platform resolution stub will not succeed, * prompts "SP authentication failed." In the process of development, because this problem let me at a loss, * A friend told me to ask Unicom to want a piece of encrypted text, and then to compare with their own generated strings, * This is a good debugging method. My last comparison found that the only difference between the strings I generated was the number of newline. * I also wrote a stub request in C # language, and I didn't find this problem. * */private string filter (String str) {string output = null; StringBuffer sb = new StringBuffer (); for (int i = 0; i < str.length (); i++) {int ASC = Str.charat (i); if (ASC!= && ASC!=) sb.append (str.subse Quence (i, i + 1)); Output = new String (SB); return output; /** * Urldecoder.encode (strencoding) Encoding of strings * @param string SRC strings to be encoded * * @return string encoded strings/public string Geturlencode (string src) {string requestvalue= ""; try{requestvalue = Urlencoder.encode (src);} catch (Exception e) {E.PR Intstacktrace (); return requestvalue; /** * 3-des Encryption * @param string src to be 3-des encrypted String * @param string Spkey Allocated Spkey * @return string 3-des Encrypted String */PU Blic StriNg Get3desencrypt (String src,string spkey) {string requestvalue= ""; try{//3-des secret key byte[] Enkey = Getenkey (Spkey); The content to be 3-des encrypted is in progress/"utf-16le/" byte byte[] src2 = src.getbytes ("Utf-16le"); Bytes byte[] EncryptedData = Encrypt (src2,enkey) for 3-des encrypted content; The contents of 3-des encryption are BASE64 encoded String base64string = Getbase64encode (EncryptedData); BASE64 code to remove line breaks after String Base64encrypt = filter (base64string); The process of escaping the HTML control code in BASE64 encoding Requestvalue=geturlencode (base64encrypt); System.out.println (Requestvalue); catch (Exception e) {e.printstacktrace ();} return requestvalue; /** * Urldecoder.decode (strencoding) Decoding of Strings * @param string src strings to be decoded * * * @return String for decoding strings/public string Geturldecoderdecode (string src) {string requestvalue= ""; try{requestvalue = Urldecoder.decode (src);} catch (Exception E ) {e.printstacktrace ();} return requestvalue; /** * * 3-des decryption (The secret key is equivalent to the encryption key). * @param byte[] src to be 3-des decrypted byte[] * @param string Spkey Allocated Spkey * @return string 3-des decrypted String */PUblic string DeCrypt (byte[] debase64,string spkey) {string strde = null; Cipher Cipher = null; try {cipher=cipher.getinstance ("Desede"); byte[] key = Getenkey (Spkey); Desedekeyspec DKs = new Desedekeyspec (key); Secretkeyfactory keyfactory = secretkeyfactory.getinstance ("Desede"); Secretkey SKey = Keyfactory.generatesecret (DKS); Cipher.init (Cipher.decrypt_mode, SKey); byte ciphertext[] = cipher.dofinal (debase64); Strde = new String (ciphertext, "utf-16le"); catch (Exception ex) {Strde = ""; Ex.printstacktrace (); return Strde; /** * 3-des decryption * @param string src to be 3-des decrypted String * @param string Spkey Allocated Spkey * @return string 3-des Encrypted String */PU Blic string Get3desdecrypt (String src,string spkey) {string requestvalue= ""; try{//Get 3-des key// Urldecoder.decodetml control code to escape the process String Urlvalue=geturldecoderdecode (SRC); The contents of 3-des encryption are BASE64 encoded base64decoder Base64decode = new Base64decoder (); byte[] Base64dvalue = Base64decode.decodebuffer (Urlvalue); The content to be 3-des encrypted is in the/"utf-16le/" byte reQuestvalue = DeCrypt (Base64dvalue,spkey); catch (Exception e) {e.printstacktrace ();} return requestvalue; public static void Main (string[] args) {endecrypt test = new Endecrypt (); String oldstring = "toxin hair"; String Spkey = "1234"; System.out.println ("1"). The assigned Spkey is: "+spkey"; System.out.println ("2"). The content is: "+oldstring); String revalue = Test.get3desencrypt (Oldstring,spkey); Revalue = Revalue.trim (). Intern (); System.out.println ("3-des after the encrypted content:" +revalue); String reValue2 = Test.get3desdecrypt (Revalue,spkey); System.out.println ("3-des decrypted content:" +revalue2);}

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.