PHP 7.2 OpenSSL实现DES算法 代替mcrypt_encrypt支持pkcs5Pad

 <?php
// php 7.2
class CryptDes
{
var $key;
var $iv; //偏移量

function CryptDes( $key, $iv=0 ) {
//key长度8例如:1234abcd
$this->key = $key;
if( empty($iv) ) {
$this->iv = $key; //默认以$key 作为 iv
} else {
$this->iv = $iv;
}
}

function encrypt($data) {
$data = $this->pkcs5Pad ( $data, 8 );
return base64_encode(openssl_encrypt ($data, ‘des-cbc’, $this->key, OPENSSL_RAW_DATA|OPENSSL_ZERO_PADDING, $this->iv));
}

function decrypt($data) {
return $this->pkcs5Unpad(openssl_decrypt (base64_decode($data), ‘des-cbc’, $this->key, OPENSSL_RAW_DATA|OPENSSL_ZERO_PADDING, $this->iv));
}

function hex2bin($hexData) {
$binData = "";
for($i = 0; $i < strlen ( $hexData ); $i += 2) {
$binData .= chr ( hexdec ( substr ( $hexData, $i, 2 ) ) );
}
return $binData;
}

function pkcs5Pad($text, $blocksize) {
$pad = $blocksize – (strlen ( $text ) % $blocksize);
return $text . str_repeat ( chr ( $pad ), $pad );
}

function pkcs5Unpad($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 );
}
}
?>

1个评论 to “PHP 7.2 OpenSSL实现DES算法 代替mcrypt_encrypt支持pkcs5Pad”

  • jack 说:

    牛逼了 谢谢

  • 留下评论:

    昵称(必须):
    邮箱地址 (不会被公开) (必须):
    站点
    评论 (必须)
    XHTML: 您可以使用这些标记: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>