<?php
namespace ticky\crypt\driver;
use ticky\crypt\contract;
class geetest extends contract {
private $token;
public function __construct($config) {
$this->token = $config['token'];
}
public function encrypt($str) {
$cipher = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_ECB, '');
$iv = $this->createIv($cipher);
if (mcrypt_generic_init($cipher, $this->pad2Length($this->token, 16), $iv) != -1) {
$cipherText = mcrypt_generic($cipher, $this->pad2Length($str, 16));
mcrypt_generic_deinit($cipher);
mcrypt_module_close($cipher);
return bin2hex($cipherText);
}
}
public function decrypt($str) {
$padkey = $this->pad2Length($this->token, 16);
$td = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_ECB, '');
$iv = $this->createIv($td);
if (mcrypt_generic_init($td, $padkey, $iv) != -1) {
$p_t = mdecrypt_generic($td, $this->hexToStr($str));
mcrypt_generic_deinit($td);
mcrypt_module_close($td);
return $this->trimEnd($p_t);
}
}
private function createIv($td) {
$ivSize = mcrypt_enc_get_iv_size($td);
$iv = mcrypt_create_iv($ivSize, MCRYPT_RAND);
return $iv;
}
private function pad2Length($text, $padlen) {
$len = strlen($text) % $padlen;
$res = $text;
$span = $padlen - $len;
for ($i = 0; $i < $span; $i++) {
$res .= chr($span);
}
return $res;
}
private function trimEnd($text) {
$len = strlen($text);
$c = $text[$len - 1];
if (ord($c) < $len) {
for ($i = $len - ord($c); $i < $len; $i++) {
if ($text[$i] != $c) {
return $text;
}
}
return substr($text, 0, $len - ord($c));
}
return $text;
}
private function hexToStr($hex) {
$bin = "";
for ($i = 0; $i < strlen($hex) - 1; $i += 2) {
$bin .= chr(hexdec($hex[$i] . $hex[$i + 1]));
}
return $bin;
}
}