Android DES AES MD5 Encryption

Source: Internet
Author: User
Tags binary to decimal decrypt md5 encryption

AES Encryption:

<span style= "FONT-SIZE:18PX;" >package Com.example.encrypdate.util;import Java.io.unsupportedencodingexception;import Java.security.invalidkeyexception;import Java.security.nosuchalgorithmexception;import Java.security.securerandom;import Javax.crypto.badpaddingexception;import Javax.crypto.cipher;import Javax.crypto.illegalblocksizeexception;import Javax.crypto.keygenerator;import Javax.crypto.nosuchpaddingexception;import Javax.crypto.secretkey;import Javax.crypto.spec.secretkeyspec;public  Class AES {/** * encryption * * @param content * requires encrypted contents * @param password * encrypted password * @return */public static Byte[] Encrypt (string content, string password) {try {keygenerator KGen = keygenerator.getinstance ("AES"); Kgen.init (128 , New SecureRandom (Password.getbytes ())); Secretkey Secretkey = Kgen.generatekey (); byte[] Encodeformat = secretkey.getencoded (); Secretkeyspec key = new Secretkeyspec (Encodeformat, "AES"); Cipher Cipher = cipher.getinstance ("AES");//Create cipher byte[] Bytecontent = Content.getbytes ("Utf-8"); Cipher.init (Cipher.encrypt_mode, key);//Initialize byte[] result = cipher.dofinal (bytecontent); return result; Encryption} catch (NoSuchAlgorithmException e) {e.printstacktrace ();} catch (Nosuchpaddingexception e) {e.printstacktrace ();} catch (InvalidKeyException e) {e.printstacktrace ();} catch (Unsupportedencodingexception e) {e.printstacktrace ();} catch (Illegalblocksizeexception e) {e.printstacktrace ();} catch (Badpaddingexception e) {e.printstacktrace ();} return null;} /** * Decrypt * * @param content * to decrypt contents * @param password * Decryption key * @return */public static byte[] Decry PT (byte[] content, String password) {try {keygenerator KGen = keygenerator.getinstance ("AES"); Kgen.init (+), new SecureRandom (Password.getbytes ())); Secretkey Secretkey = Kgen.generatekey (); byte[] Encodeformat = secretkey.getencoded (); Secretkeyspec key = new Secretkeyspec (Encodeformat, "AES"); Cipher Cipher = cipher.getinstance ("AES");//Create cipher Cipher.init (Cipher.decrypt_mode, key);//Initialize BYte[] result = cipher.dofinal (content); return result; Encryption} catch (NoSuchAlgorithmException e) {e.printstacktrace ();} catch (Nosuchpaddingexception e) {e.printstacktrace ();} catch (InvalidKeyException e) {e.printstacktrace ();} catch (Illegalblocksizeexception e) {e.printstacktrace ();} catch ( Badpaddingexception e) {e.printstacktrace ();} return null;} /** * Convert Decimal to 16 binary * * @param buf * @return */public static String parsebyte2hexstr (byte buf[]) {stringbuffer sb = new STR Ingbuffer (); for (int i = 0; i < buf.length; i++) {String hex = integer.tohexstring (Buf[i] & 0xFF); if (Hex.length () = = 1) {hex = ' 0 ' + hex;} Sb.append (Hex.touppercase ());} return sb.tostring ();}  /** * Convert 16 binary to decimal * * @param hexstr * @return */public static byte[] Parsehexstr2byte (String hexstr) {if (Hexstr.length () < 1) return null;byte[] result = new Byte[hexstr.length ()/2];for (int i = 0; i < hexstr.length ()/2; i++) {int hi GH = Integer.parseint (hexstr.substring (i * 2, I * 2 + 1); int low = Integer.parsEint (Hexstr.substring (i * 2 + 1, I * 2 + 2),); Result[i] = (byte) (high * + low);} return result;}} </span>
des encryption:

<span style= "FONT-SIZE:18PX;" >package Com.example.encrypdate.util;import Javax.crypto.cipher;import Javax.crypto.spec.IvParameterSpec; Import Javax.crypto.spec.secretkeyspec;import Android.util.base64;public class DES {//initialization vector, random fill of private static byte[] IV = {1, 2, 3, 4, 5, 6, 7, 8};/** * @param encryptstring * require encrypted plaintext * @param encryptkey * keys * @ret Urn Encrypted ciphertext * @throws Exception */public static string Encryptdes (String encryptstring, String encryptkey) throws Exception {//Instantiate the Ivparameterspec object, use the specified initialization vector ivparameterspec ZEROIV = new Ivparameterspec (iv);//Instantiate the Secretkeyspec class, Constructs Secretkeysecretkeyspec key = new Secretkeyspec (Encryptkey.getbytes (), "DES") based on a byte array;//create cipher cipher cipher = Cipher.getinstance ("des/cbc/pkcs5padding");//Initialize Cipher object Cipher.init (Cipher.encrypt_mode, Key, ZEROIV) with secret key;// Perform cryptographic operation byte[] EncryptedData = cipher.dofinal (Encryptstring.getbytes ()); return base64.encodetostring (EncryptedData, Base64.default);}          /**** * * @param decrypstring *  Ciphertext * @param decryptkey * Decryption key * @return * @throws Exception */public static string Decryptdes (String decrypst Ring, String Decryptkey) throws Exception {byte[] Bytemi = Base64.decode (decrypstring, Base64.default);// Instantiates a Ivparameterspec object, using the specified initialization vector ivparameterspec ZEROIV = new Ivparameterspec (iv);//Instantiate the Secretkeyspec class, Constructs Secretkeysecretkeyspec key = new Secretkeyspec (Decryptkey.getbytes (), "DES") based on a byte array;//create cipher cipher cipher = Cipher.getinstance ("des/cbc/pkcs5padding");//Initialize Cipher object Cipher.init (Cipher.decrypt_mode, Key, ZEROIV) with secret key;// Perform decryption operation byte[] Decrypteddata = cipher.dofinal (Bytemi); return new String (Decrypteddata);}} </span>
MD5 Encryption:

<span style= "FONT-SIZE:18PX;" >package Com.example.encrypdate.util;import Java.security.messagedigest;import Java.security.nosuchalgorithmexception;public class MD5 {/*** * @param data * @return */public static string ToMD5 (string Data) {try {//Instantiate a MessageDigest object that specifies the digest algorithm as MD5 messagedigest algorithm = messagedigest.getinstance ("MD5");// Reset the summary for Reuse Algorithm.reset ();//Use bytes to update the digest Algorithm.update (Data.getbytes ());//Use the specified byte array to update the digest most, Then complete the summary to calculate return tohexstring (Algorithm.digest (), ""); catch (NoSuchAlgorithmException e) {//TODO auto-generated catch block E.printstacktrace ();} Return "";} Converts each character in a string to a hexadecimal private static string tohexstring (byte[] bytes, string separator) {StringBuilder hexstring = new Strin Gbuilder (); for (byte b:bytes) {String hex = integer.tohexstring (0xFF & B); if (hex.length () = = 1) {hexstring.append (' 0 ');} Hexstring.append (hex);} return hexstring.tostring ();}} </span>

Test file:

<span style= "FONT-SIZE:18PX;" >package Com.example.encrypdate;import Com.example.encrypdate.util.aes;import Com.example.encrypdate.util.DES; Import Android.os.bundle;import android.app.activity;import Android.util.log;import Android.widget.textview;import Com.example.encrypdate.util.md5;public class Mainactivity extends Activity {private TextView TV; @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (r.layout.activity_ Main); TV = (TextView) This.findviewbyid (r.id.tv);//Destest ();//Md5test (); Aestest ();} public void Destest () {//Specifies that the key can only be a 8-bit string key = "12345678";//Specifies the plaintext string text = "How much" that needs to be encrypted; LOG.I ("des", "des cipher plaintext:" + text + "\ n Encryption Key:" + key);//Call DES encryption try {String Encryptresult = des.encryptdes (text, key); String Decryptresult = Des.decryptdes (Encryptresult, key); Tv.settext ("Encrypted result:" + Encryptresult + "\ nthe decryption Result:" + Decryptresult ); LOG.I ("DES", "Encrypted result:" + Encryptresult + "\ n decryption Result:" + Decryptresult);} catch (Exception e) {//TODO auto-generated Catch block E.printstacktrace ();}} private void Aestest () {String content = "test3444"; String Password = "11";//encryption byte[] Encryptresult = aes.encrypt (content, password); String encryptresultstr = Aes.parsebyte2hexstr (Encryptresult);//decryption byte[] Decryptfrom = Aes.parsehexstr2byte ( ENCRYPTRESULTSTR); String decryptresult = new String (Aes.decrypt (decryptfrom, password)); LOG.I ("AES", "Password:" + password + "\ n" before encryption: "+ content +" \ n after encryption: "+ encryptresultstr +" \ n decrypted: "+ Decryptresult); Tv.settext (" Password : "+ password +" \ n before encryption: "+ content +" \ n after encryption: "+ encryptresultstr +" \ n decrypted: "+ Decryptresult);} private void Md5test () {String str = "1NAKJNVJANBDVJK female guest that lease V Pride can't be wasted where convenient v Ah don't v pride can't waste where convenient v Ah don't v pride can't waste where convenient v ah don't waste vu Lou disease v Arabian Wind V "; String Md5result = md5.tomd5 (str); LOG.I ("MD5", str + "MD5 encryption Result:" + Md5result); Tv.settext (str + "MD5 encryption Result:" + Md5result);}} </span>

Complete Project Address:

http://download.csdn.net/detail/u014071669/7930951


Android DES AES MD5 Encryption

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.