Data encryption transfer between Android and PHP

Source: Internet
Author: User
Tags decrypt mcrypt

Data encryption transfer between Android and PHP [code] [Java] Code1 MCrypt =NewMCrypt ();2/*Encrypt*/3 String encrypted = Mcrypt.bytestohex (Mcrypt.encrypt ("Text to Encrypt") );4/*Decrypt*/5 String decrypted =NewString (Mcrypt.decrypt (encrypted)); Code [PHP] Code1 $mcrypt =NewMCrypt ();2#Encrypt3 $encrypted = $mcrypt->encrypt ("Text to Encrypt");4#Decrypt5 $decrypted = $mcryptdecrypt ($encrypted); Code Mcrypt.java001/***********/002/**java**/003 004Importjava.security.NoSuchAlgorithmException;005 006ImportJavax.crypto.Cipher;007Importjavax.crypto.NoSuchPaddingException;008ImportJavax.crypto.spec.IvParameterSpec;009ImportJavax.crypto.spec.SecretKeySpec;010 011 Public classMCrypt {012 013PrivateString IV = "FEDCBA9876543210";//Dummy IV (change it!)014PrivateIvparameterspec Ivspec;015PrivateSecretkeyspec Keyspec;016PrivateCipher Cipher;017 018PrivateString Secretkey = "0123456789abcdef";//Dummy Secretkey (change it!)019 020 PublicMCrypt ()021            {022 Ivspec =NewIvparameterspec (Iv.getbytes ());023 024 Keyspec =NewSecretkeyspec (Secretkey.getbytes (), "AES");025 026Try {027 cipher = cipher.getinstance ("aes/cbc/nopadding");028}Catch(nosuchalgorithmexception e) {029//TODO auto-generated Catch block030e.printstacktrace ();031}Catch(nosuchpaddingexception e) {032//TODO auto-generated Catch block033e.printstacktrace ();034                }035            }036 037 Public byte[] Encrypt (String text)throwsException038            {039if(Text = =NULL|| Text.length () = = 0)040Throw NewException ("Empty string");041 042byte[] encrypted =NULL;043 044Try {045Cipher.init (Cipher.encrypt_mode, Keyspec, ivspec);046 047 encrypted =cipher.dofinal (padstring (text). GetBytes ());048}Catch(Exception e)049                {          050Throw NewException ("[Encrypt]" +e.getmessage ());051                }052 053returnencrypted;054            }055 056 Public byte[] Decrypt (String code)throwsException057            {058if(Code = =NULL|| Code.length () = = 0)059Throw NewException ("Empty string");060 061byte[] decrypted =NULL;062 063Try {064Cipher.init (Cipher.decrypt_mode, Keyspec, ivspec);065 066 decrypted =cipher.dofinal (hextobytes (code));067}Catch(Exception e)068                {069Throw NewException ("[Decrypt]" +e.getmessage ());070                }071returndecrypted;072            }073 074 075 076 Public StaticString Bytestohex (byte[] data)077            {078if(data==NULL)079                {080return NULL;081                }082 083intLen =data.length;084 String str = "";085 for(inti=0; i<len; i++) {086if((DATA[I]&AMP;AMP;0XFF) &lt;16)087 str = str + "0" + java.lang.Integer.toHexString (data[i]&amp;0xff);088Else089 str = str + java.lang.Integer.toHexString (data[i]&amp;0xff);090                }091returnstr;092            }093 094 095 Public Static byte[] hextobytes (String str) {096if(str==NULL) {097return NULL;098}Else if(Str.length () &lt; 2) {099return NULL;100}Else {101intLen = Str.length ()/2;102byte[] buffer =New byte[Len];103 for(inti=0; i&lt;len; i++) {104 Buffer[i] = (byte) Integer.parseint (str.substring (i*2,i*2+2), 16);105                    }106returnbuffer;107                }108            }109 110 111 112Private Staticstring padstring (string source)113            {114CharPaddingchar = ' ';115intsize = 16;116intx = source.length ()%size;117intPadlength = Size-x;118 119 for(inti = 0; I &lt; Padlength; i++)120              {121 Source + =Paddingchar;122              }123 124returnSource;125            }126}[Code] mcrypt.php01/**********/02/**php**/&lt;?PHP05 06classMCrypt07    {08Private$iv = ' fedcba9876543210 '; #Same as in JAVA09Private$key = ' 0123456789abcdef '; #Same as in JAVA10 11 12function __construct ()13        {14        }15 16function Encrypt ($str) {17 18//$key = $this->hex2bin ($key); $iv = $ This-&Gt;iv;$TD = Mcrypt_module_open (' rijndael-128 ', ', ' CBC ', $IV);Mcrypt_generic_init ($TD, $ This-&Gt;key, $iv);$encrypted =mcrypt_generic ($TD, $str);25 26Mcrypt_generic_deinit ($TD);27Mcrypt_module_close ($TD);28 29returnBin2Hex ($encrypted);30        }31 32function Decrypt ($code) {33//$key = $this-&gt;hex2bin ($key);$code = $ This-&Gt;hex2bin ($code);$iv = $ This-&Gt;iv;PNS $td = Mcrypt_module_open (' rijndael-128 ', ', ' CBC ', $IV);Mcrypt_generic_init ($TD, $ This-&Gt;key, $iv);$decrypted =mdecrypt_generic ($TD, $code);41 42Mcrypt_generic_deinit ($TD);43Mcrypt_module_close ($TD);44 45returnUtf8_encode (Trim ($decrypted));46        }47 48protectedfunction Hex2bin ($hexdata) {$bindata = ";50 51 for($i = 0; $i &lt; strlen ($hexdata); $i + = 2) {$bindata. = Chr (Hexdec (substr ($hexdata, $i, 2)));53          }54 55return$bindata;56        }57 58    }59// Seehttp://androidsnippets.com/encrypt-decrypt-between-android-and-php

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.