> php教程 > PHP源码 > 본문

PHP aes算法

PHP中文网
풀어 주다: 2016-05-25 17:05:47
원래의
923명이 탐색했습니다.

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.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
최신 이슈
인기 추천
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!