加入收藏 | 设为首页 | 会员中心 | 我要投稿 安卓应用网 (https://www.0791zz.com/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > PHP > 正文

php写的AES加密解密类分享

发布时间:2020-05-25 17:53:36 所属栏目:PHP 来源:互联网
导读:这篇文章主要介绍了php写的AES加密解密类,实际是为YII框架写的,不在YII框架时只需替换其中的两句代码即可使用,需要的朋友可以参考下

今天写了一个php的AES加密类。适用于Yii的扩展。 如果不用在Yii框架中,把代码中Yii::app()->params['encryptKey'] 换成你对应的默认key就可以了。 类代码:

params['encryptKey'] : $key,mcrypt_enc_get_key_size($module)); /* Create the IV and determine the keysize length,use MCRYPT_RAND * on Windows instead */ $iv = substr(md5($key),mcrypt_enc_get_iv_size($module)); /* Intialize encryption */ mcrypt_generic_init($module,$key,$iv);
    /* Encrypt data */
    $encrypted = mcrypt_generic($module,$plaintext);

    /* Terminate encryption handler */
    mcrypt_generic_deinit($module);
    mcrypt_module_close($module);
    return base64_encode($encrypted);
}

/**
 * This was AES-128 / CBC / NoPadding decrypted.
 * @author Terry
 * @param string $encrypted     base64_encode encrypted string
 * @param string $key
 * @throws CException
 * @return string
 */
public static function AesDecrypt($encrypted,$key = null)
{
    if ($encrypted == '') return '';
    if(!extension_loaded('mcrypt'))
        throw new CException(Yii::t('yii','AesDecrypt requires PHP mcrypt extension to be loaded in order to use data encryption feature.'));

    $ciphertext_dec = base64_decode($encrypted);
    $module = mcrypt_module_open(MCRYPT_RIJNDAEL_128,mcrypt_enc_get_key_size($module));

    $iv = substr(md5($key),mcrypt_enc_get_iv_size($module));

    /* Initialize encryption module for decryption */
    mcrypt_generic_init($module,$iv);

    /* Decrypt encrypted string */
    $decrypted = mdecrypt_generic($module,$ciphertext_dec);

    /* Terminate decryption handle and close module */
    mcrypt_generic_deinit($module);
    mcrypt_module_close($module);
    return rtrim($decrypted,"");
}

/**
 * Returns the length of the given string.
 * If available uses the multibyte string function mb_strlen.
 * @param string $string the string being measured for length
 * @return integer the length of the string
 */
private static function strlen($string)
{
    return extension_loaded('mbstring') ? mb_strlen($string,'8bit') : strlen($string);
}

/**
 * Returns the portion of string specified by the start and length parameters.
 * If available uses the multibyte string function mb_substr
 * @param string $string the input string. Must be one character or longer.
 * @param integer $start the starting position
 * @param integer $length the desired portion length
 * @return string the extracted part of string,or FALSE on failure or an empty string.
 */
private static function substr($string,$start,$length)
{
    return extension_loaded('mbstring') ? mb_substr($string,$length,'8bit') : substr($string,$length);
}

}

(编辑:安卓应用网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读