Search code examples
phppearbcmath

Error using BCMath - Call to undefined method PEAR_Error::int2bin()


I am having this error while using BCMath -

Fatal error: Call to undefined method PEAR_Error::int2bin() in login.php on line 23

I am trying to use Crypt_RSA and BCMath together. Here is my code -

require_once("Crypt/RSA/MathLoader.php");
$wrapper_name = “BCMath”;
$math_obj = &Crypt_RSA_MathLoader::loadWrapper($wrapper_name);

$a = $math_obj->int2bin("6465130539297209249500692895930266194225707667564124686892613724438982507603215802636578141547940687986170708901198917318074984831856438115515743080726101");

Solution

  • So i ran into a similar issue when I was doing some crypto in php just a few days ago. I needed to convert a decimal number into its binary equivalent. What I did was convert it to hex and then unpack it as hex encoded data.

    <?php 
    
    $a = pack("H*", convBase('6465130539297209249500692895930266194225707667564124686892613724438982507603215802636578141547940687986170708901198917318074984831856438115515743080726101', '0123456789', '0123456789ABCDEF'));
    
    function convBase($numberInput, $fromBaseInput, $toBaseInput)
    {
        if ($fromBaseInput==$toBaseInput) return $numberInput;
        $fromBase = str_split($fromBaseInput,1);
        $toBase = str_split($toBaseInput,1);
        $number = str_split($numberInput,1);
        $fromLen=strlen($fromBaseInput);
        $toLen=strlen($toBaseInput);
        $numberLen=strlen($numberInput);
        $retval='';
        if ($toBaseInput == '0123456789')
        {
            $retval=0;
            for ($i = 1;$i <= $numberLen; $i++)
                $retval = bcadd($retval, bcmul(array_search($number[$i-1], $fromBase),bcpow($fromLen,$numberLen-$i)));
            return $retval;
        }
        if ($fromBaseInput != '0123456789')
            $base10=convBase($numberInput, $fromBaseInput, '0123456789');
        else
            $base10 = $numberInput;
        if ($base10<strlen($toBaseInput))
            return $toBase[$base10];
        while($base10 != '0')
        {
            $retval = $toBase[bcmod($base10,$toLen)].$retval;
            $base10 = bcdiv($base10,$toLen,0);
        }
        return $retval;
    }
    ?>