Android 和 PHP 之间进行数据加密传输

Android 和 PHP 之间进行数据加密传输
Android 和 PHP 之间进行数据加密传输
[代码] [Java]代码
1    mcrypt = new MCrypt();
2    /* Encrypt */
3    String encrypted = MCrypt.bytesToHex( mcrypt.encrypt("Text to Encrypt") );
4    /* Decrypt */
5    String decrypted = new String( mcrypt.decrypt( encrypted ) );
[代码] [PHP]代码
1    $mcrypt = new MCrypt();
2    #Encrypt
3    $encrypted = $mcrypt->encrypt("Text to encrypt");
4    #Decrypt
5    $decrypted = $mcrypt->decrypt($encrypted);
[代码] MCrypt.java
001    /***********/
002    /**JAVA**/
003     
004        import java.security.NoSuchAlgorithmException;
005     
006        import javax.crypto.Cipher;
007        import javax.crypto.NoSuchPaddingException;
008        import javax.crypto.spec.IvParameterSpec;
009        import javax.crypto.spec.SecretKeySpec;
010     
011        public class MCrypt {
012     
013            private String iv = "fedcba9876543210";//Dummy iv (CHANGE IT!)
014            private IvParameterSpec ivspec;
015            private SecretKeySpec keyspec;
016            private Cipher cipher;
017            
018            private String SecretKey = "0123456789abcdef";//Dummy secretKey (CHANGE IT!)
019            
020            public MCrypt()
021            {
022                ivspec = new IvParameterSpec(iv.getBytes());
023     
024                keyspec = new SecretKeySpec(SecretKey.getBytes(), "AES");
025                
026                try {
027                    cipher = Cipher.getInstance("AES/CBC/NoPadding");
028                } catch (NoSuchAlgorithmException e) {
029                    // TODO Auto-generated catch block
030                    e.printStackTrace();
031                } catch (NoSuchPaddingException e) {
032                    // TODO Auto-generated catch block
033                    e.printStackTrace();
034                }
035            }
036            
037            public byte[] encrypt(String text) throws Exception
038            {
039                if(text == null || text.length() == 0)
040                    throw new Exception("Empty string");
041                
042                byte[] encrypted = null;
043     
044                try {
045                    cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec);
046     
047                    encrypted = cipher.doFinal(padString(text).getBytes());
048                } catch (Exception e)
049                {          
050                    throw new Exception("[encrypt] " + e.getMessage());
051                }
052                
053                return encrypted;
054            }
055            
056            public byte[] decrypt(String code) throws Exception
057            {
058                if(code == null || code.length() == 0)
059                    throw new Exception("Empty string");
060                
061                byte[] decrypted = null;
062     
063                try {
064                    cipher.init(Cipher.DECRYPT_MODE, keyspec, ivspec);
065                    
066                    decrypted = cipher.doFinal(hexToBytes(code));
067                } catch (Exception e)
068                {
069                    throw new Exception("[decrypt] " + e.getMessage());
070                }
071                return decrypted;
072            }
073            
074     
075            
076            public static String bytesToHex(byte[] data)
077            {
078                if (data==null)
079                {
080                    return null;
081                }
082                
083                int len = data.length;
084                String str = "";
085                for (int i=0; i<len; i++) {
086                    if ((data[i]&amp;0xFF)&lt;16)
087                        str = str + "0" + java.lang.Integer.toHexString(data[i]&amp;0xFF);
088                    else
089                        str = str + java.lang.Integer.toHexString(data[i]&amp;0xFF);
090                }
091                return str;
092            }
093            
094                
095            public static byte[] hexToBytes(String str) {
096                if (str==null) {
097                    return null;
098                } else if (str.length() &lt; 2) {
099                    return null;
100                } else {
101                    int len = str.length() / 2;
102                    byte[] buffer = new byte[len];
103                    for (int i=0; i&lt;len; i++) {
104                        buffer[i] = (byte) Integer.parseInt(str.substring(i*2,i*2+2),16);
105                    }
106                    return buffer;
107                }
108            }
109            
110            
111     
112            private static String padString(String source)
113            {
114              char paddingChar = ‘ ‘;
115              int size = 16;
116              int x = source.length() % size;
117              int padLength = size - x;
118     
119              for (int i = 0; i &lt; padLength; i++)
120              {
121                  source += paddingChar;
122              }
123     
124              return source;
125            }
126        }
[代码] mcrypt.php
 
01    /**********/
02    /**PHP**/
03     
04    &lt;?php
05     
06    class MCrypt
07    {
08        private $iv = ‘fedcba9876543210‘; #Same as in JAVA
09        private $key = ‘0123456789abcdef‘; #Same as in JAVA
10     
11     
12        function __construct()
13        {
14        }
15     
16        function encrypt($str) {
17     
18          //$key = $this->hex2bin($key);   
19          $iv = $this-&gt;iv;
20     
21          $td = mcrypt_module_open(‘rijndael-128‘, ‘‘, ‘cbc‘, $iv);
22     
23          mcrypt_generic_init($td, $this-&gt;key, $iv);
24          $encrypted = mcrypt_generic($td, $str);
25     
26          mcrypt_generic_deinit($td);
27          mcrypt_module_close($td);
28     
29          return bin2hex($encrypted);
30        }
31     
32        function decrypt($code) {
33          //$key = $this-&gt;hex2bin($key);
34          $code = $this-&gt;hex2bin($code);
35          $iv = $this-&gt;iv;
36     
37          $td = mcrypt_module_open(‘rijndael-128‘, ‘‘, ‘cbc‘, $iv);
38     
39          mcrypt_generic_init($td, $this-&gt;key, $iv);
40          $decrypted = mdecrypt_generic($td, $code);
41     
42          mcrypt_generic_deinit($td);
43          mcrypt_module_close($td);
44     
45          return utf8_encode(trim($decrypted));
46        }
47     
48        protected function hex2bin($hexdata) {
49          $bindata = ‘‘;
50     
51          for ($i = 0; $i &lt; strlen($hexdata); $i += 2) {
52            $bindata .= chr(hexdec(substr($hexdata, $i, 2)));
53          }
54     
55          return $bindata;
56        }
57     
58    }
59    // see http://androidsnippets.com/encrypt-decrypt-between-android-and-php
Android 和 PHP 之间进行数据加密传输

 

上一篇:android 通过广播监听网络连接状况


下一篇:Android运行时异常“Binary XML file line # : Error inflating class”