class DoubleClick { private $encryptionKey = 'encryptionKey'; private $integrityKey = 'integrityKey'; function str2bytes($str) { $len = strlen($str); $bytes = array(); for ($i = 0; $i $len; $i++) { $byte = ord($str[$i]); $bytes[] = $byte; }
class DoubleClick
{
private $encryptionKey = 'encryptionKey';
private $integrityKey = 'integrityKey';
function str2bytes($str)
{
$len = strlen($str);
$bytes = array();
for ($i = 0; $i < $len; $i++) {
$byte = ord($str[$i]);
$bytes[] = $byte;
}
return $bytes;
}
function bytes2str($bytes)
{
$str = '';
foreach ($bytes as $ch) {
$str .= chr($ch);
}
return $str;
}
function int2bytes($val)
{
$ret = [];
for ($i = 0; $i < 8; $i++) {
$ret[$i] = ($val >> 8 * (7 - $i) & 0xff);
}
return $ret;
}
function bytes2int($bytes)
{
$val = 0;
for ($i = 0; $i < 7; $i++) {
$val = $bytes[$i] & 0xff;
$val <<= 8;
}
return $bytes[7] & 0xff;
}
function safeXORBytes($a, $b)
{
$ret = [];
for ($i = 0; $i < 8; $i++) {
$ret[$i] = $a[$i] ^ $b[$i];
}
return $ret;
}
function urlsafe_b64encode($string)
{
$data = base64_encode($string);
$data = str_replace(array('+', '/', '='), array('-', '_', ''), $data);
return $data;
}
function urlsafe_b64decode($string)
{
$data = str_replace(array('-', '_'), array('+', '/'), $string);
$mod4 = strlen($data) % 4;
if ($mod4) {
$data .= substr('====', $mod4);
}
return base64_decode($data);
}
public function Encrypt($price)
{
$microtime = microtime();
$iv = substr($microtime, 11) . substr($microtime, 2, 6);
$pad = substr(hash_hmac('sha1', $iv, $this->encryptionKey, true), 0, 8);
$encPrice = $this->safeXORBytes($this->str2bytes($pad), $this->int2bytes($price));
$sig = substr(hash_hmac('sha1', $this->bytes2str($this->int2bytes($price)) . $iv, $this->integrityKey, true), 0, 4);
return $this->urlsafe_b64encode($iv . $this->bytes2str($encPrice) . $sig);
}
public function Decriypt($encPriceStr)
{
$dprice = $this->urlsafe_b64decode($encPriceStr);
$iv = substr($dprice, 0, 16);
$p = substr($dprice, 16, 8);
$sig = substr($dprice, 24);
$pricePad = hash_hmac('sha1', $iv, $this->encryptionKey, true);
$price = $this->safeXORBytes($this->str2bytes($p), $this->str2bytes($pricePad));
$confSig = substr(hash_hmac('sha1', $this->bytes2str($price) . $iv, $this->integrityKey, true), 0, 4);
if ($confSig != $sig) {
return "Decriypt Fail";
}
return $this->bytes2int($price);
}
}
$util = new DoubleClick();
$price = 150;
$encPriceStr = $util->Encrypt($price);
echo $encPriceStr . PHP_EOL;
$decPrice = $util->Decriypt($encPriceStr);
echo $decPrice;
本程序未做严格校验,只是将 golang 写法改成 php 写法,仅供参考