mputer''s memory.)
// (b) Still be reasonably efficient.
//
// We assume p, q and r are all positive, and that r is non-zero.
//
// Note that the more simple algorithm of multiplying $p by itself $q times, and
// applying "mod $r" at every step is also valid, but is O($q), whereas this
// algorithm is O(log $q). Big difference.
//
// As far as I can see, the algorithm I use is optimal; there is no redundancy
// in the calculation of the partial results.
//--
function pow_mod($p, $q, $r)
{
// Extract powers of 2 from $q
$factors = array();
$div = $q;
$power_of_two = 0;
while(bccomp($div, "0") == BCCOMP_LARGER)
{
$rem = bcmod($div, 2);
$div = bcdiv($div, 2);
if($rem) array_push($factors, $power_of_two);
$power_of_two++;
}
// Calculate partial results for each factor, using each partial result as a
// starting point for the next. This depends of the factors of two being
// generated in increasing order.
$partial_results = array();
$part_res = $p;
$idx = 0;
foreach($factors as $factor)
{
while($idx < $factor)
{
$part_res = bcpow($part_res, "2");
$part_res = bcmod($part_res, $r);
$idx++;
}
array_push($partial_results, $part_res);
}
// Calculate final result
$result = "1";
foreach($partial_results as $part_res)
{
$result = bcmul($result, $part_res);
$result = bcmod($result, $r);
}
return $result;
}
//--
// Function to add padding to a decrypted string
// We need to know if this is a private or a public key operation
//--
function add_PKCS1_padding($data, $isPublicKey, $blocksize)
{
$pad_length = $blocksize - 3 - strlen($data);
if($isPublicKey)
{
$block_type = "\x02";
$padding = "";
for($i = 0; $i < $pad_length; $i++)
{
$rnd = mt_rand(1, 255);
$padding .= chr($rnd);
}
}
else
{
$block_type = "\x01";
$padding = str_repeat("\xFF", $pad_length);
}
return "\x00" . $block_type . $padding . "\x00" . $data;
}
//--
// Remove padding from a decrypted string
// See for more details.
//--
function remove_PKCS1_padding($data, $blocksize)
{
//以下部分于原版的RSA有所不同,修复了原版的一个BUG
//assert(strlen($data) == $blocksize);
$data = substr($data, 1);
// We cannot deal with block type 0
if($data{0} == ''\0'')
die("Block type 0 not implemented.");
// Then the block type must be 1 or 2
//assert(($data{0} == "\x01") || ($data{0} == "\x02"));
// echo $data;
// Remove the padding
$i=1;
while (1){
$offset = strpos($data, "\0", $i);
if(!$offset){
$offset=$i;
break;
}
$i=$offset+1;
}
//$offset = strpos($data, "\0", 100);
return substr($data, $offset);
}
//--
// Remove "kyp" padding
// (Non standard)
//--
function remove_KYP_padding($data, $blocksize)
{
assert(strlen($data) == $blocksize);
$offset = strpos($data, "\0");
return substr($data, 0, $offset);
}
//--
// Convert binary data to a decimal number
//--
function binary_to_number($data)
{
$base = "256";
$radix = "1";
$result = "0";
for($i = strlen($data) - 1; $i >= 0; $i--)
{
$digit = ord($data{$i});
$part_res = bcmul($digit, $radix);
$result = bcadd($result, $part_res);
$radix = bcmul($radix, $base);
}
return