encrypt

$blockSize = 4; //區塊大小
if(empty($plainText))
return '';
$cipherText = '';
$counterBlock = '';
$nonce = floor(microtime(true)*1000); // timestamp: milliseconds since 1-Jan-1970 [floor]Returns the next lowest integer value by rounding down value if necessary.
$nonceRnd = floor(rand(0, 0xffff));
$counterBlock = substr(dechex($nonceRnd),0,1).substr(dechex($nonce),-1,1);//產生nonce

$ctrTxt = '';
$ctrTxt = $counterBlock;//開頭nonce

$blockCount = ceil(strlen($plainText)/$blockSize);
for ($b=0; $b<$blockCount; $b++) {
//conter最後的值counterBlock共4byte
$counterBlock = '';
$counterBlock = $ctrTxt. str_pad(dechex($b), 2, "0", STR_PAD_LEFT);//最後2碼為編號
//echo nl2br("$counterBlock\n");
$cipherTextToken = '';
$cipherTextToken = blockprocess($counterBlock,$cipherKey);
//echo nl2br("$cipherTextToken\n");
$blockLength = $b<$blockCount-1 ? $blockSize : (strlen($plainText)-1)%$blockSize+1;

for ($i=0; $i<$blockLength; $i++) {
$XORcipherTextToken = substr($cipherTextToken, $i, 1) ^ ord(substr($plainText, $b*$blockSize+$i, 1));
$cipherText .= chr($XORcipherTextToken);
}
}
//echo $ctrTxt.$cipherText;
return base64_encode($ctrTxt.$cipherText);

 

decrypt

$blockSize = 4;

if(empty($cipherText))
return '';
$plainText = '';
$cipherText = base64_decode($cipherText);
$ctrTxt = substr($cipherText,0,2);//前20為nonce
$cipherText = substr($cipherText,2,strlen($cipherText));//剩下的

$blockCount = ceil(strlen($cipherText)/$blockSize);
for ($b=0; $b<$blockCount; $b++) {
//conter最後的值counterBlock共4byte
$counterBlock = '';
$counterBlock = $ctrTxt. str_pad(dechex($b), 2, "0", STR_PAD_LEFT);//最後4碼為編號

$cipherTextToken = blockprocess($counterBlock,$cipherKey);

$blockLength = $b<$blockCount-1 ? $blockSize : (strlen($cipherText)-1)%$blockSize+1;

for ($i=0; $i<$blockLength; $i++) {
$XORcipherTextToken = substr($cipherTextToken, $i, 1) ^ ord(substr($cipherText, $b*$blockSize+$i, 1));
$plainText .= chr($XORcipherTextToken);
}
}

return $plainText;

arrow
arrow
    全站熱搜

    abort 發表在 痞客邦 留言(0) 人氣()