码迷,mamicode.com
首页 > 编程语言 > 详细

CBC之php java兼容版本

时间:2016-07-25 14:36:08      阅读:258      评论:0      收藏:0      [点我收藏+]

标签:

网上搜了N多代码,都是你抄我的,我抄你的,着实让人无语对苍天。经过多番资料的查找,php与java的cbc加密、解密结果终于一致了,代码如下:

Java加密解密类:

package main;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;

public class AESUtil {
    // 加密
    public static String Encrypt(String sSrc, String sKey) throws Exception {
        if (sKey == null) {
            System.out.print("Key为空null");
            return null;
        }
        // 判断Key是否为16位
        if (sKey.length() != 16) {
            System.out.print("Key长度不是16位");
            return null;
        }
        byte[] raw = sKey.getBytes();
        SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");//"算法/模式/补码方式"
        //Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");//"算法/模式/补码方式"
        IvParameterSpec iv = new IvParameterSpec("1234567890123456".getBytes());//使用CBC模式,需要一个向量iv,可增加加密算法的强度
        
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
        //cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
        byte[] encrypted = cipher.doFinal(sSrc.getBytes("UTF-8"));
        
        return new String(Base64.encodeBase64(encrypted));
    }

    // 解密
    public static String Decrypt(String sSrc, String sKey) throws Exception {
        try {
            // 判断Key是否正确
            if (sKey == null) {
                System.out.print("Key为空null");
                return null;
            }
            // 判断Key是否为16位
            if (sKey.length() != 16) {
                System.out.print("Key长度不是16位");
                return null;
            }
            byte[] raw = sKey.getBytes("UTF-8");
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            //Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            IvParameterSpec iv = new IvParameterSpec("1234567890123456"
                    .getBytes());
            cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
            //cipher.init(Cipher.DECRYPT_MODE, skeySpec);
            Base64.decodeBase64(sSrc.getBytes());
            byte[] encrypted1 = Base64.decodeBase64(sSrc.getBytes());
            try {
                byte[] original = cipher.doFinal(encrypted1);
                String originalString = new String(original);
                return originalString;
            } catch (Exception e) {
                System.out.println(e.toString());
                return null;
            }
        } catch (Exception ex) {
            System.out.println(ex.toString());
            return null;
        }
    }
}

Java调用:

public static void main(String[] args) {
        // TODO Auto-generated method stub

        String cKey = "1234567890123456";
        // 需要加密的字串
        String cSrc = "test string";
        System.out.println(cSrc);
        
        String enString;
        String deString;
        try {
            enString = AESUtil.Encrypt(cSrc, cKey);
            System.out.println("加密后的字串是:" + enString);
            
            deString=AESUtil.Decrypt(enString, cKey);
            System.out.println("解密后的字串是:" + deString);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        

    }

要注意,AESUtil类中,有个iv变量,要和php中的iv对应起来。

 

PHP加密解密类:

class MyAES { 
 public function encryptString($input, $key,$iv) {
   $size = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
   $input = MyAES::pkcs5_pad($input, $size);
   $td = mcrypt_module_open(MCRYPT_RIJNDAEL_128, ‘‘, MCRYPT_MODE_CBC, ‘‘);
   //$iv = mcrypt_create_iv (mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
   mcrypt_generic_init($td, $key, $iv);
   $data = mcrypt_generic($td, $input);
   mcrypt_generic_deinit($td);
   mcrypt_module_close($td);
   $data = base64_encode($data);
   return $data;
  }
  
  private static function pkcs5_pad ($text, $blocksize) {
    $pad = $blocksize - (strlen($text) % $blocksize);
    return $text . str_repeat(chr($pad), $pad);
  }
 
 public function decryptString($sStr, $sKey,$iv) {
    $td = mcrypt_module_open(MCRYPT_RIJNDAEL_128, ‘‘, MCRYPT_MODE_CBC, ‘‘);
    //$iv = mcrypt_create_iv (mcrypt_enc_get_iv_size($td), MCRYPT_RAND); 
    $decrypted= @mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $sKey, base64_decode($sStr), MCRYPT_MODE_CBC, $iv);
    $dec_s = strlen($decrypted);
    $padding = ord($decrypted[$dec_s-1]);
    $decrypted = substr($decrypted, 0, -$padding);
    return $decrypted;
  }
 }  

PHP调用:

$msg = ‘test string‘;
$key=‘1234567890123456‘;
$iv=$key;
$x=new MyAES();

$en=$x->encryptString($msg, $key,$iv);
echo $en,‘<br />‘;

echo $x->decryptString($en,$key,$iv);

 

参考资料:http://blog.163.com/fan_xy_qingyuan/blog/static/188987748201391124728740/

 

CBC之php java兼容版本

标签:

原文地址:http://www.cnblogs.com/ddcoder/p/5703152.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!