跳转到帖子
登录关注  
墨香年少

PHP和JAVA通用加密代码

已推荐帖子

php代码:

<?php
class Javas {
    static public $key = "a32f9c44xbx2018z";
    public static function encrypt($input, $key) {
        $size = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_ECB);
        $input = Javas::pkcs5_pad($input, $size);
        $td = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_ECB, '');
        $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 static function decrypt($sStr, $sKey) {
        $decrypted= mcrypt_decrypt(
            MCRYPT_RIJNDAEL_128,
            $sKey,
            base64_decode($sStr),
            MCRYPT_MODE_ECB
        );

        $dec_s = strlen($decrypted);
        $padding = ord($decrypted[$dec_s-1]);
        $decrypted = substr($decrypted, 0, -$padding);
        return $decrypted;
    }
}

JAVA代码

package com.bluebirdme.mes.publicFun;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

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

public class AesSecurity {
	/**
	 * 加密kEY值
	 */
	public static String key="a32f9c44xbx2018z";
	/**
	 * 加密
	 * @param input
	 * @param key
	 * @return
	 */
	 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));  
		}  
		   
	  /**
	   * 解密
	   * @param input
	   * @param key
	   * @return
	   */
	 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);  
		}  
}

 


目之所及,皆是回忆,心之所想,皆是过往

分享这篇帖子


链接帖子
分享到其他站点

创建帐户或登录来提出意见

你需要成为会员才能提出意见

创建帐户

注册成为会员。只要几个简单步骤!

注册帐户

登录

已有帐户? 请登录。

现在登录
登录关注  

×
×
  • 创建新的...

重要信息

注册必须使用2-8个中文汉字作为账号