AES 加密 PHP 和 JAVA 互通

PHP代码:

 1 <?php
 2 class Security {
 3     public static function encrypt($input, $key) {
 4     $size = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_ECB);
 5     $input = Security::pkcs5_pad($input, $size);
 6     $td = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_ECB, '');
 7     $iv = mcrypt_create_iv (mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
 8     mcrypt_generic_init($td, $key, $iv);
 9     $data = mcrypt_generic($td, $input);
10     mcrypt_generic_deinit($td);
11     mcrypt_module_close($td);
12     $data = base64_encode($data);
13     return $data;
14     }
15  
16     private static function pkcs5_pad ($text, $blocksize) {
17         $pad = $blocksize - (strlen($text) % $blocksize);
18         return $text . str_repeat(chr($pad), $pad);
19     }
20  
21     public static function decrypt($sStr, $sKey) {
22         $decrypted= mcrypt_decrypt(
23         MCRYPT_RIJNDAEL_128,
24         $sKey,
25         base64_decode($sStr),
26         MCRYPT_MODE_ECB
27     );
28  
29         $dec_s = strlen($decrypted);
30         $padding = ord($decrypted[$dec_s-1]);
31         $decrypted = substr($decrypted, 0, -$padding);
32         return $decrypted;
33     }    
34 }
35  
36  
37  
38 $key = "1234567891234567";
39 $data = "example";
40  
41 $value = Security::encrypt($data , $key );
42 echo $value.'<br/>';
43 echo Security::decrypt($value, $key );

 

---------------

java 代码

 

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
 
import org.apache.commons.codec.binary.Base64;
 
public class Security {
    public static String encrypt(String input, String key){
    byte[] crypted = null;
    try{
    SecretKeySpec skey = new SecretKeySpec(key.getBytes(), "AES");
    Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
    cipher.init(Cipher.ENCRYPT_MODE, skey);
    crypted = cipher.doFinal(input.getBytes());
    }catch(Exception e){
    System.out.println(e.toString());
    }
    return new String(Base64.encodeBase64(crypted));
}
 
public static String decrypt(String input, String key){
    byte[] output = null;
    try{
    SecretKeySpec skey = new SecretKeySpec(key.getBytes(), "AES");
    Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
    cipher.init(Cipher.DECRYPT_MODE, skey);
    output = cipher.doFinal(Base64.decodeBase64(input));
    }catch(Exception e){
    System.out.println(e.toString());
    }
    return new String(output);
}
 
    public static void main(String[] args) {
        String key = "1234567891234567";
        String data = "example";
        
        System.out.println(Security.encrypt(data, key));
        
        System.out.println(Security.decrypt(Security.encrypt(data, key), key));
        
            
    }    
}

转载于:http://jickcai.iteye.com/blog/1742481

posted @ 2017-04-20 11:30  张志健  阅读(1957)  评论(0编辑  收藏  举报