1. 程式人生 > >workerman中使用aes加密

workerman中使用aes加密



在ubuntu中,安裝mcrypt擴充套件

apt-get install php5-mcrypt  libmcrypt-dev

aes.php

<?php

define('SECRETKEY', 'key');
define('SECRETIV', 'iv');
class aes{
/**
 * 加密方法
 * @param string $str
 * @return string
 */
function encrypt($str) {
    //AES, 128 ECB模式加密資料
    $str = aes::addPKCS7Padding($str);
    $iv = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC), MCRYPT_RAND);
    $encrypt_str = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, SECRETKEY, $str, MCRYPT_MODE_CBC, SECRETIV);
    return base64_encode($encrypt_str);
}

/**
 * 解密方法
 * @param string $str
 * @return string
 */
function decrypt($str) {
    //AES, 128 CBC模式加密資料
    $str = base64_decode($str);
    
    $iv = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC), MCRYPT_RAND);
    $encrypt_str = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, SECRETKEY, $str, MCRYPT_MODE_CBC, SECRETIV);
    $encrypt_str = aes::stripPKSC7Padding($encrypt_str);
    return $encrypt_str;
}

/**
 * 填充演算法
 * @param string $source
 * @return string
 */
function addPKCS7Padding($source) {
    //$source = trim($source);
    $block = mcrypt_get_block_size('rijndael-128', 'cbc');
    $pad = $block - (strlen($source) % $block);
    if ($pad <= $block) {
        $char = chr($pad);
        $source .= str_repeat($char, $pad);
    }
    return $source;
}

/**
 * 移去填充演算法
 * @param string $source
 * @return string
 */
function stripPKSC7Padding($source) {
    $char = substr($source, -1);
    $num = ord($char);
    $source = substr($source, 0, -$num);
    return $source;
}
}

?>

在workerman中的引用
include 'aes.php';
在workerman中的使用
$aes = new aes();
	$enc =$aes -> encrypt($msg);//加密

	$dec =$aes -> decrypt($enc);//解密