bcpowmod

(PHP 5)

bcpowmod --  Raise an arbitrary precision number to another, reduced by a specified modulus

Description

string bcpowmod ( string x, string y, string modulus [, int scale] )

Use the fast-exponentiation method to raise x to the power y with respect to the modulus modulus. The optional scale can be used to set the number of digits after the decimal place in the result.

注: Because this method uses the modulus operation, non-natural numbers may give unexpected results. A natural number is any positive non-zero integer.

范例

The following two statements are functionally identical. The bcpowmod() version however, executes in less time and can accept larger parameters.

<?php
$a
= bcpowmod($x, $y, $mod);

$b = bcmod(bcpow($x, $y), $mod);

// $a and $b are equal to each other.

?>

参见

bcpow()bcmod().


add a note add a note User Contributed Notes
rrasss at gmail dot com
16-May-2006 05:46
However, if you read his full note, you see this paragraph:
"The function bcpowmod(v, e, m) is supposedly equivalent to bcmod(bcpow(v, e), m).  However, for the large numbers used as keys in the RSA algorithm, the bcpow function generates a number so big as to overflow it.  For any exponent greater than a few tens of thousands, bcpow overflows and returns 1."

So you still can, and should (over bcmod(bcpow(v, e), m) ), use his function if you are using larger exponents, "any exponent greater than a few tens of thousand."
ewilde aht bsmdevelopment dawt com
28-Sep-2005 12:46
Versions of PHP prior to 5 do not have bcpowmod in their repertoire.  This routine simulates this function using bcdiv, bcmod and bcmul.  It is useful to have bcpowmod available because it is commonly used to implement the RSA algorithm.
 
The function bcpowmod(v, e, m) is supposedly equivalent to bcmod(bcpow(v, e), m).  However, for the large numbers used as keys in the RSA algorithm, the bcpow function generates a number so big as to overflow it.  For any exponent greater than a few tens of thousands, bcpow overflows and returns 1.

This routine will iterate through a loop squaring the result, modulo the modulus, for every one-bit in the exponent.  The exponent is shifted right by one bit for each iteration.  When it has been reduced to zero, the calculation ends.

This method may be slower than bcpowmod but at least it works.

function PowModSim($Value, $Exponent, $Modulus)
  {
  // Check if simulation is even necessary.
  if (function_exists("bcpowmod"))
   return (bcpowmod($Value, $Exponent, $Modulus));

  // Loop until the exponent is reduced to zero.
  $Result = "1";

  while (TRUE)
   {
   if (bcmod($Exponent, 2) == "1")
     $Result = bcmod(bcmul($Result, $Value), $Modulus);

   if (($Exponent = bcdiv($Exponent, 2)) == "0") break;

   $Value = bcmod(bcmul($Value, $Value), $Modulus);
   }

  return ($Result);
  }