AES/ECB/PKCS5Padding

49 篇文章 0 订阅
<?php
/**
 * 
 * AES/ECB/PKCS5Padding 
 * @author robert198837
 *
 */
class PKCS5 {
    protected $cipher = MCRYPT_RIJNDAEL_128;
    protected $mode = MCRYPT_MODE_ECB;
    protected $pad_method = NULL;
    protected $secret_key = '';
    protected $iv = '';
    
    public function set_cipher($cipher) {
        $this->cipher = $cipher;
    }
    
    public function set_mode($mode) {
        $this->mode = $mode;
    }
    
    public function set_iv($iv) {
        $this->iv = $iv;
    }
    
    public function set_key($key) {
        $this->secret_key = $key;
    }
    
    public function pad($text) {
        $blocksize = mcrypt_get_block_size ( $this->cipher, $this->mode );
        $pad = $blocksize - (strlen ( $text ) % $blocksize);
        return $text . str_repeat ( chr ( $pad ), $pad );
    }
    
    protected function unpad($text) {
        
        $pad = ord ( $text {strlen ( $text ) - 1} );
        if ($pad > strlen ( $text )) {
            return false;
        }
        if (strspn ( $text, chr ( $pad ), strlen ( $text ) - $pad ) != $pad) {
            return false;
        }
        return substr ( $text, 0, - 1 * $pad );
    }
    
    public function encrypt($str) {
        $str = $this->pad ( $str );
        $td = mcrypt_module_open ( $this->cipher, '', $this->mode, '' );
        
        if (empty ( $this->iv )) {
            $iv = @mcrypt_create_iv ( mcrypt_enc_get_iv_size ( $td ), MCRYPT_RAND );
        } else {
            $iv = $this->iv;
        }
        
        mcrypt_generic_init ( $td, $this->secret_key, $iv );
        $cyper_text = mcrypt_generic ( $td, $str );
        mcrypt_generic_deinit ( $td );
        mcrypt_module_close ( $td );
        return $cyper_text;
    }
    
    public function decrypt($str) {
        $td = mcrypt_module_open ( $this->cipher, '', $this->mode, '' );
        
        if (empty ( $this->iv )) {
            $iv = @mcrypt_create_iv ( mcrypt_enc_get_iv_size ( $td ), MCRYPT_RAND );
        } else {
            $iv = $this->iv;
        }
        mcrypt_generic_init ( $td, $this->secret_key, $iv );
        $decrypted_text = mdecrypt_generic ( $td, $str );
        $rt = $decrypted_text;
        mcrypt_generic_deinit ( $td );
        mcrypt_module_close ( $td );
        return $this->unpad ( $decrypted_text );
    }
    
  
    
    public function generate_text($str) {
        $str = $this->encrypt ( $str );
        return base64_encode ( $str );
    }
}


$aes = new PKCS5 ();
$aes->set_key ( 'test );
$text = $aes->generate_text ( "plain text'" );
echo $text;


//echo $aes->decrypt ( base64_decode ( $text ) );
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值