首页 > php教程 > PHP源码 > 正文

PHP aes算法

PHP中文网
发布: 2016-05-25 17:05:47
原创
1337人浏览过

php代码

function aes128cbcEncrypt($key, $text)
{
    /**
     * Open the cipher
     */
    $td = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_CBC, '');
    if (! $td)
    {
        throw new GeneralSecurityException('Invalid mcrypt cipher, check your libmcrypt library and php-mcrypt extention');
    } 
    // replaced MCRYPT_DEV_RANDOM with MCRYPT_RAND since windows doesn't have /dev/rand :)
    srand((double)microtime() * 1000000);
    $iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
    /**
     * Intialize encryption
     */
    mcrypt_generic_init($td, $key, $iv);
    /**
     * Encrypt data
     */
    $encrypted = mcrypt_generic($td, $text);
    /**
     * Terminate encryption handler
     */
    mcrypt_generic_deinit($td);
    /**
     * AES-128-CBC encryption.  The IV is returned as the first 16 bytes  
     * of the cipher text.
     */
    return $iv . $encrypted;
} 

function aes128cbcDecrypt($key, $encrypted_text)
{
    /**
     * Open the cipher
     */
    $td = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_CBC, '');
    if (is_callable('mb_substr'))
    {
        $iv = mb_substr($encrypted_text, 0, Crypto_CIPHER_BLOCK_SIZE, 'latin1');
    } 
    else
    {
        $iv = substr($encrypted_text, 0, Crypto_CIPHER_BLOCK_SIZE);
    } 
    /**
     * Initialize encryption module for decryption
     */
    mcrypt_generic_init($td, $key, $iv);
    /**
     * Decrypt encrypted string
     */
    if (is_callable('mb_substr'))
    {
        $encrypted = mb_substr($encrypted_text, Crypto_CIPHER_BLOCK_SIZE, mb_strlen($encrypted_text, 'latin1'), 'latin1');
    } 
    else
    {
        $encrypted = substr($encrypted_text, Crypto_CIPHER_BLOCK_SIZE);
    } 
    $decrypted = mdecrypt_generic($td, $encrypted);
    /**
     * Terminate decryption handle and close module
     */
    mcrypt_generic_deinit($td);
    mcrypt_module_close($td);
    /**
     * Show string
     */
    return trim($decrypted);
} 
define('Crypto_CIPHER_BLOCK_SIZE', 16);
$a = aes128cbcEncrypt('pass', 'this is text');
echo base64_encode($a) . "/r/n";
$b = aes128cbcDecrypt('pass', $a);
echo $b . "/r/n";
$c = aes128cbcDecrypt('pass', base64_decode(base64_encode($a)));
echo $c . "/r/n";
?>
登录后复制
PHP速学教程(入门到精通)
PHP速学教程(入门到精通)

PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号