You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
pdd-order-api/app/libs/tool/Crypt.php

59 lines
1.9 KiB
PHTML

11 months ago
<?php
class Crypt {
private $key = NULL;
private $iv = NULL;
private $iv_size = NULL;
private $iterations = 999;
public function Crypt($key = '') {
$this->init($key);
}
public function init($key = "") {
$this->key = ($key != "") ? $key : "";
$this->algorithm = MCRYPT_DES;
$this->mode = MCRYPT_MODE_ECB;
$this->iv_size = mcrypt_get_iv_size($this->algorithm, $this->mode);
$this->iv = mcrypt_create_iv($this->iv_size, MCRYPT_RAND);
}
public function encrypt($data) {
$size = mcrypt_get_block_size($this->algorithm, $this->mode);
$data = $this->pkcs5_pad($data, $size);
return base64_encode(mcrypt_encrypt($this->algorithm, $this->key, $data, $this->mode, $this->iv));
}
public function decrypt($data) {
return $this->pkcs5_unpad(rtrim(mcrypt_decrypt($this->algorithm, $this->key, base64_decode($data), $this->mode, $this->iv)));
}
public function encryptV2($plainText) {
$key = hash_pbkdf2("sha256", $this->key, '', $this->iterations, 64);
$encryptedData = openssl_encrypt($plainText, 'AES-256-CBC', hex2bin($key), OPENSSL_RAW_DATA);
return base64_encode($encryptedData);
}
public function decryptV2($encryptedTextBase64) {
$encryptedText = base64_decode($encryptedTextBase64);
$key = hash_pbkdf2("sha256", $this->key, '', $this->iterations, 64);
$decryptedText = openssl_decrypt($encryptedText, 'AES-256-CBC', hex2bin($key), OPENSSL_RAW_DATA);
return $decryptedText;
}
private function pkcs5_pad($text, $blocksize) {
$pad = $blocksize - (strlen($text) % $blocksize);
return $text . str_repeat(chr($pad), $pad);
}
private function pkcs5_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);
}
}