/    Sign up×
Community /Pin to ProfileBookmark

[RESOLVED] RSA implementation in pure PHP

I spent a lot of time researching this and couldn’t find an existing implementation of the RSA algorithm in pure PHP (besides with PEAR, which requires you to have access to PEAR, making the ending application much less portable). So I ended up creating one myself. Here are the capabilities and limitations of this implementation:

[B]Capabilities:[/B]

[LIST]

  • [*]

    Generates its own prime numbers with (theoretically) no limit on size


  • [*]

    Can create keypairs with (theoretically) no limits on size


  • [*]

    Can encrypt and decrypt text of any length (though since it’s kinda slow, it shouldn’t be used on really long text blocks)


  • [*]

    On my server, with a 1024 bit key and 100 character block size, it takes .5 seconds per block to encrypt and 1.5 seconds per block to decrypt


  • [/LIST]

    [B]Limitations:[/B]

    [LIST]

  • [*]

    This implementation does not include a function to encrypt the private keys for repeated usage using a pass phrase. You must create your own function using symmetric (AES, DES3, Blowfish…) encryption.


  • [*]

    On my system, this takes between 3 and 30 seconds to generate one 155-digit prime number (two 155 digit primes are required for a 1024 bit key)


  • [*]

    The math to create a keypair after the primes have been calculated taked about 2 second on my system


  • [*]

    You may need to make use of the set_time_limit function to make sure that the key generation has enough time to complete.


  • [*]

    It is not set up to recognize bit length for key generation. See the first comment for more info.


  • [/LIST]

    This code is released under the GPL license… google it for more information. There is no warranty, express or implied, and all that mumbo jumbo. Just use it however you want and nobody’s gonna get all up in your business about it.

    [code=php]<?php
    class RSA_Handler {
    function encrypt($text, $key) {
    //The complete encryption function.
    //Accepts plain text and outputs a numeric code (divided into blocks by spaces)
    list($p, $r) = unserialize(base64_decode($key));
    $in = $this->blockify($text, 100); //Cut it into blocks of 100 characters (seems to fit well without getting too big)
    $out = ”;
    foreach($in as $block) {
    if($block)
    $out .= $this->crypt_num($this->txt2num($block), $p, $r) . ” “;
    }
    return $out;
    }
    function decrypt($code, $key) {
    //The complete decryption function
    //Accepts data in the format which was created by the encrypt function
    //(numbers divided into blocks in, text out)
    list($q, $r) = unserialize(base64_decode($key));
    $in = explode(” “, $code);
    $out = ”;
    foreach($in as $block) {
    if($block)
    $out .= $this->num2txt($this->crypt_num($block, $q, $r));
    }
    return $out;
    }
    function generate_keypair($digits = 310) {
    set_time_limit(60);
    $km = new RSA_keymaker();
    $keys = $km->make_keys($digits);
    //The keys are separated into arrays and then serialized and encoded in base64
    //This makes it easier to store and transmit them
    //
    //The private key should probably be encrypted with a user-supplied key (in AES or DES3)…
    //This way it can be stored on the server, yet still be secure. The user-supplied key should not be stored.
    $pub = base64_encode(serialize(array($keys[0], $keys[2])));
    $priv = base64_encode(serialize(array($keys[1], $keys[2])));
    return array($pub, $priv);
    }
    function crypt_num($num, $key, $mod) {
    //This is the same function whether you are encrypting or decrypting.
    $out = $this->powmod($num, $key, $mod);
    return $out;
    }
    function blockify($in, $b_length) {
    //Add spaces to the end of text so it fits evenly into the block size
    $x = bcmod(strlen($in), $b_length);
    while($x > 0) {
    $in = str_pad($in, 1, ” “);
    $x–;
    }
    return str_split($in, $b_length);
    }
    function txt2num($str) {
    //Turns regular text into a number that can be manipulated by the RSA algorithm
    $result = ‘0’;
    $n = strlen($str);
    do {
    $result = bcadd(bcmul($result, ‘256’), ord($str{–$n}));
    } while ($n > 0);
    return $result;
    }
    function num2txt($num) {
    //Turns the numeric representation of text (as output by txt2num) back into text
    $result = ”;
    do {
    $result .= chr(bcmod($num, ‘256’));
    $num = bcdiv($num, ‘256’);
    } while (bccomp($num, ‘0’));
    return $result;
    }
    function powmod($num, $pow, $mod) {
    if (function_exists(‘bcpowmod’)) {
    // bcpowmod is only available under PHP5
    return bcpowmod($num, $pow, $mod);
    }
    // emulate bcpowmod
    $result = ‘1’;
    do {
    if (!bccomp(bcmod($pow, ‘2’), ‘1’)) {
    $result = bcmod(bcmul($result, $num), $mod);
    }
    $num = bcmod(bcpow($num, ‘2’), $mod);
    $pow = bcdiv($pow, ‘2’);
    } while (bccomp($pow, ‘0’));
    return $result;
    }
    }
    class RSA_keymaker {
    static $primes = null;
    static $primes_cnt = 0;
    static $prefix;
    function __construct() {
    if(is_null($this->primes)) {
    //Make $this->primes an array of all primes under 10,000
    //We will use this list to rule out the “easy” composite (non-prime) numbers
    for ($i = 0; $i < 10000; $i++) {
    $numbers[] = $i;
    }
    $numbers[0] = $numbers[1] = 0;
    foreach ($numbers as $i => $num) {
    if(!$num) {
    continue;
    }
    $j = $i;
    for ($j += $i; $j < 10000; $j += $i) {
    $numbers[$j] = 0;
    }
    }
    $j = 0;
    foreach($numbers as $num) {
    if ($num) {
    $this->primes[$j++] = $num;
    }
    }
    $this->primes_cnt = $j;
    }
    $this->prefix = rand(10000, 99999);
    }
    function make_keys($digits = 310, $u = false, $v = false) {
    //Select 2 random prime numbers each at half the digits of our total
    //We use a prefix so the first 5 numbers are the same, so that the primes are similar in value
    if(!$u)
    $u = $this->make_prime(intval($digits/2), $this->prefix);
    if(!$v)
    $v = $this->make_prime(intval($digits/2), $this->prefix);
    //Make sure they are at least 1 quadrillion numbers apart
    while(substr($prime1, -16, 2) < (substr($prime2, -16, 2) + 2) &amp;&amp; substr($prime1, -16, 2) > (substr($prime2, -16, 2) – 2) ) {
    $prime2 = $pm->make_prime(intval($digits/2));
    }
    $r = bcmul($u, $v);
    $phir = bcmul(bcsub($u, 1), bcsub($v, 1));
    //Pick a value for p (The Public key). We will make it smaller than half so the private key will be longer
    $p = $this->make_prime(intval($digits/3), false);
    //Find the inverse of p using the Extended Euclidian Algorithm
    $q = $this->euclid($p, $phir);
    return array($p, $q, $r);
    }
    function make_prime($digits, $prefix = false) {
    $ent = $this->entropyarray();
    $e_cnt = count($ent);
    //If a prefix is defined, use it as the first (prefix length) numbers
    //This is to keep the two numbers closer together in value
    $pre_len = $prefix ? strlen($prefix) : 0;
    $num = $prefix;
    for($i = 0; $i < ($digits – $pre_len); $i++) {
    //Create a long integer where the first number is 1-9 and the last is 1,3,7 or 9
    if($i == ($digits – $pre_len – 1)) {
    while($spec != 1 &amp;&amp; $spec != 3 &amp;&amp; $spec != 7 &amp; $spec != 9) {
    $spec = rand(1,9);
    }
    $num .= $spec;
    $spec = 0;
    } elseif($i == 0)
    $num .= rand(1,9);
    else

    $num .= bcmod(rand(0,9) + $ent[bcmod($i, $e_cnt)], 10);
    }
    while(!$this->is_prime($num)) {
    //If the number is not prime, add 2 or 4 (since it is currently an odd number)
    //This will keep the number odd and skip 5 to speed up the primality testing
    if(substr($num, -1, 1) == 3)
    $num = bcadd($num, 4);
    else

    $num = bcadd($num, 2);
    $tries++;
    }
    return $num;
    }
    function entropyarray() {
    //create a long number based on as much entropy as possible
    $a = base_convert(substr(md5(microtime()), 0, 10), 16, 10);
    $b = mt_rand();
    $c = base_convert(substr(sha1(@exec(‘uptime’)), 0, 10), 16, 10);
    //make sure it is only numbers
    $all = str_split(preg_replace(“[^0-9]”, “”, bcadd(bcmul($a, $b), $c)));
    shuffle($all);
    return $all;
    }
    function is_prime($num) {
    if(bccomp($num, 1) < 1)
    return >false;
    //Clear the easy stuff (divide by all primes under 10,000)
    for($i=0; $i < $this->primes_cnt; $i++) {
    if(bccomp($num, $this->primes[$i]) == 0)
    return >true;
    if(!bcmod($num, $this->primes[$i]))
    return >false;
    }
    //Try the more complex method with the first 7 primes as bases
    for($i = 0; $i < 7; $i++) {
    if(!$this->_millerTest($num, $this->primes[$i]))
    return >false; //Number is composite
    }
    //Strong probability that the number is prime
    return >true;
    }
    function _millerTest($num, $base) {
    if(!bccomp($num, ‘1’)) {
    // 1 is not prime πŸ˜‰
    return >false;
    }
    $tmp = bcsub($num, ‘1’);
    $zero_bits = 0;
    while (!bccomp(bcmod($tmp, ‘2’), ‘0’)) {
    $zero_bits++;
    $tmp = bcdiv($tmp, ‘2’);
    }
    $tmp = $this->powmod($base, $tmp, $num);
    if (!bccomp($tmp, ‘1’)) {
    // $num is probably prime
    return >true;
    }
    while ($zero_bits–) {
    if (!bccomp(bcadd($tmp, ‘1’), $num)) {
    // $num is probably prime
    return >true;
    }
    $tmp = $this->powmod($tmp, ‘2’, $num);
    }
    // $num is composite
    return >false;
    }
    function euclid($num, $mod) {
    //The Extended Euclidian Algorithm
    $x = ‘1’;
    $y = ‘0’;
    $num1 = $mod;
    do {
    $tmp = bcmod($num, $num1);
    $q = bcdiv($num, $num1);
    $num = $num1;
    $num1 = $tmp;
    $tmp = bcsub($x, bcmul($y, $q));
    $x = $y;
    $y = $tmp;
    } while (bccomp($num1, ‘0’));
    if (bccomp($x, ‘0’) < 0) {
    $x = bcadd($x, $mod);
    }
    return $x;
    }
    function powmod($num, $pow, $mod) {
    if (function_exists(‘bcpowmod’)) {
    // bcpowmod is only available under PHP5
    return bcpowmod($num, $pow, $mod);
    }
    // emulate bcpowmod
    $result = ‘1’;
    do {
    if (!bccomp(bcmod($pow, ‘2’), ‘1’)) {
    $result = bcmod(bcmul($result, $num), $mod);
    }
    $num = bcmod(bcpow($num, ‘2’), $mod);
    $pow = bcdiv($pow, ‘2’);
    } while (bccomp($pow, ‘0’));
    return $result;
    }
    }
    ?>[/code]

    to post a comment
    PHP

    6 Comments(s) ↴

    Copy linkTweet thisAlerts:
    @StevishauthorMar 24.2009 β€”Β About key bit lengths. Since this class defines length of the keys by digits, it is difficult to specify an exact key length. Using a 310 digit modulo (which is the default, and will consist of two 155-digit primes) will pretty much get you a 1024 bit key. For 2048, use 620 digits, etc...

    Much less than 1024 bits (or 310 digits), is not particularly secure, so you should avoid it.

    Also, if you use this function with smaller keys, you may want to change the RSA_Handler::generate_keys function to use a smaller block length, as a 512 bit key may not be able to handle 100 character blocks.
    Copy linkTweet thisAlerts:
    @NogDogMar 25.2009 β€”Β Just FYI, you don't really have to "have access to PEAR" to use it. There's nothing stopping you from downloading the classes you need and installing them wherever you want them. That being said, if your class provides all the needed functionality and does not have any worries about dependencies (as a PEAR class might), more power to it.
    Copy linkTweet thisAlerts:
    @StevishauthorMar 25.2009 β€”Β Yeah, in the case of the RSA classes in PEAR, there was a require() that called some other pear files as well as calls to classes that were not defined in the RSA files.
    Copy linkTweet thisAlerts:
    @StevishauthorMar 30.2009 β€”Β I have updated the code to get rid of some of it's limitations.

    It now calculates its own block sizes in case a smaller key is used, and it generates keys (and primes) based on bit size instead of how many digits. It is also better documented.

    [B]Due to post size limits, I've split it into two posts. These two posts should be combined into one file:[/B]

    [code=php]
    <?php
    // Stevish RSA version 2.0

    // Copyright 2009, Stevish.com (with mad props to te developers of the PEAR RSA extension)
    // This script is distributed under the terms of the GNU General Public License (GPL)
    // See http://www.gnu.org/licenses/gpl.txt for license details

    // Please use, distribute, modify, rip-off, sell or destroy this script however you see fit
    // I only ask that you remove my copyright if you modify and re-release this.
    // To make sure you have the genuine, up-to-date version, visit http://stevish.com/rsa-encryption-in-pure-php

    // To use:
    //
    // $text = "Peter Piper picked a peck of pickled peppers";
    // $RSA = new RSA_Handler();
    // $keys = $RSA->generate_keypair(1024);
    // $encrypted = $RSA->encrypt($text, $keys[0]);
    // $decrypted = $RSA->decrypt($encrypted, $keys[1]);
    // echo $decrypted; //Will print Peter Piper picked a peck of pickled peppers

    class RSA_Handler {
    function encrypt($text, $key) {
    list($p, $r, $keysize) = unserialize(base64_decode($key));
    $in = $this->blockify($text, $keysize);
    $out = '';
    foreach($in as $block) {
    if($block) {
    $cryptblock = $this->crypt_num($this->txt2num($block), $p, $r);
    $out .= $this->long_base_convert($cryptblock, 10, 145) . " ";
    }
    }
    return $out;
    }

    function decrypt($code, $key) {
    list($q, $r) = unserialize(base64_decode($key));
    $in = explode(" ", $code);
    $out = '';
    foreach($in as $block) {
    if($block) {
    $block = $this->long_base_convert($block, 145, 10);
    $out .= $this->num2txt($this->crypt_num($block, $q, $r));
    }
    }
    return $out;
    }

    function generate_keypair($bits = 1024, $debug = false) {
    $km = new RSA_keymaker();
    $keys = $km->make_keys($bits, $debug);
    if ($debug) print_r($keys);
    //The keys are separated into arrays and then serialized and encoded in base64
    //This makes it easier to store and transmit them
    //
    //The private key should probably be encrypted with a user-supplied key (in AES or DES3)...
    //This way it can be stored on the server, yet still be secure. The user-supplied key should not be stored.
    $pub = base64_encode(serialize(array($keys[0], $keys[2], $bits)));
    $priv = base64_encode(serialize(array($keys[1], $keys[2], $bits)));
    return array($pub, $priv);
    }

    function crypt_num($num, $key, $mod) {
    //The powerhorse function. This is where the encryption/decryption actually happens.
    //This function is used whether you are encrypting or decrypting.
    return $this->powmod($num, $key, $mod);
    }

    function long_base_convert ($numstring, $frombase, $tobase) {
    //Converts a long integer (passed as a string) to/from any base from 2 to 145
    $chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-+=!@#$&#37;^*(){[}]|:,.?/`~&#8226;&#164;&#182;&#167;&#199;&#252;&#233;&#226;&#228;&#224;&#229;&#231;&#234;&#235;&#232;&#239;&#238;&#236;&#196;&#197;&#201;&#230;&#198;&#244;&#246;&#242;&#251;&#249;&#255;&#214;&#220;&#162;&#163;&#165;&#402;&#225;&#237;&#243;&#250;&#241;&#209;&#170;&#186;&#191;&#172;&#189;&#188;&#161;&#171;&#187;&#175;&#223;&#181;&#177;&#247;;<>";
    $fromstring = substr($chars, 0, $frombase);
    $tostring = substr($chars, 0, $tobase);

    $length = strlen($numstring);
    $result = '';
    for ($i = 0; $i < $length; $i++) {
    $number[$i] = strpos($fromstring, $numstring{$i});
    }
    do {
    $divide = 0;
    $newlen = 0;
    for ($i = 0; $i < $length; $i++) {
    $divide = $divide * $frombase + $number[$i];
    if ($divide >= $tobase) {
    $number[$newlen++] = (int)($divide / $tobase);
    $divide = $divide % $tobase;
    } elseif ($newlen > 0) {
    $number[$newlen++] = 0;
    }
    }
    $length = $newlen;
    $result = $tostring{$divide} . $result;
    } while ($newlen != 0);
    return $result;
    }

    function blockify($in, $keysize) {
    //Calculate blocksize by keysize
    $b_len = floor($keysize/8);
    return str_split($in, $b_len);
    }

    function txt2num($str) {
    //Turns regular text into a number that can be manipulated by the RSA algorithm
    $result = '0';
    $n = strlen($str);
    do {
    $result = bcadd(bcmul($result, '256'), ord($str{--$n}));
    } while ($n > 0);
    return $result;
    }

    function num2txt($num) {
    //Turns the numeric representation of text (as output by txt2num) back into text
    $result = '';
    do {
    $result .= chr(bcmod($num, '256'));
    $num = bcdiv($num, '256');
    } while (bccomp($num, '0'));
    return $result;
    }

    function powmod($num, $pow, $mod) {
    if (function_exists('bcpowmod')) {
    // bcpowmod is only available under PHP5
    return bcpowmod($num, $pow, $mod);
    }

    // emulate bcpowmod
    $result = '1';
    do {
    if (!bccomp(bcmod($pow, '2'), '1')) {
    $result = bcmod(bcmul($result, $num), $mod);
    }
    $num = bcmod(bcpow($num, '2'), $mod);

    $pow = bcdiv($pow, '2');
    } while (bccomp($pow, '0'));
    return $result;
    }
    }
    //...Continued in next post
    [/code]
    Copy linkTweet thisAlerts:
    @StevishauthorMar 30.2009 β€”Β [B]Part 2[/B]
    [code=php]
    class RSA_keymaker {

    static $primes = null;

    function __construct() {
    if(is_null($this->primes)) {
    //Make $this->primes an array of all primes under 20,000
    //We will use this list to rule out the "easy" composite (non-prime) numbers

    for ($i = 0; $i < 20000; $i++) {
    $numbers[] = $i;
    }
    $numbers[0] = $numbers[1] = 0; //Zero and one are not primes :)
    foreach ($numbers as $i => $num) {
    if(!$num) {
    continue;
    }
    $j = $i;

    for ($j += $i; $j < 20000; $j += $i) {
    //Jump to each multiple of the current number and set it to 0 (not prime)
    $numbers[$j] = 0;
    }
    }
    foreach($numbers as $num) {
    //Take all the prime numbers and fill the primes array
    if ($num) {
    $this->primes[] = $num;
    }
    }
    }
    }

    function make_keys($bits = 1024, $debug = false, $u = false, $v = false) {
    //Select 2 random prime numbers each at about half the bit size of our key
    //We keep a possible variant of 2 bits so that there are a wider range of primes that can be used
    $variant = rand(0,2);
    if(!$u)
    $u = $this->make_prime(ceil($bits/2) + $variant, $debug);
    if(!$v)
    $v = $this->make_prime(floor($bits/2) - $variant, $debug);
    while(substr($u, -16, 2) < (substr($v, -16, 2) + 2) && substr($u, -16, 2) > (substr($v, -16, 2) - 2) ) {
    //Make sure the 2 primes are at least 1 quadrillion numbers apart
    $v = $pm->make_prime(intval($digits/2));
    }

    //Find our modulo r and phi(r)
    $r = bcmul($u, $v);
    $phir = bcmul(bcsub($u, 1), bcsub($v, 1));

    //Pick a value for p (The Public key). We will make it 17 bits or smaller.
    $psize = ($bits > 51) ? 17 : intval($bits/3);
    $p = $this->make_prime($psize, false);

    //Find the inverse of p mod phi(r) using the Extended Euclidian Algorithm
    $q = $this->euclid($p, $phir);

    return array($p, $q, $r);
    }

    function make_prime($bits, $debug = false) {
    //This function should not be used to generate primes less than 18 bits
    if($debug) {
    $b = microtime(true);
    echo "Debug true:<br/><br/>";
    }

    $min = bcpow(2, $bits - 1);
    $max = bcsub(bcmul($min, 2), 1);
    $digits = strlen($max);
    while(strlen($min) < $digits)
    $min = "0" . $min;
    $ent = $this->entropyarray($digits);
    if($debug) echo "<br/>min: $min<br/>max: $max<br/>digits: $digits<br/>bits: $bits<br/>entropy: $ent";
    $maxed = true;
    $mined = true;
    $num = '';
    for($i = 0; $i < $digits; $i++) {
    //Create a long integer between $min and $max starting with the entropy number
    $thismax = 9;
    $thismin = 0;
    if($maxed)
    $thismax = substr($max, $i, 1);
    if($mined)
    $thismin = substr($min, $i, 1);

    //Add random numbers (mod 10) until the number meets the constraints
    $thisdigit = ($ent[$i] + rand(0,9)) % 10;
    if($i == $digits - 1) //The last digit should be a 1, 3, 7 or 9
    while($thisdigit != 1 && $thisdigit != 3 && $thisdigit != 7 && $thisdigit != 9 && $thisdigit <= $thismax && $thisdigit >= $thismin)
    $thisdigit = ($thisdigit + rand(0,9)) % 10;
    else
    while($thisdigit <= $thismax && $thisdigit >= $thismin)
    $thisdigit = ($thisdigit + rand(0,9)) % 10;
    $num .= $thisdigit;
    if($maxed && $thisdigit < $thismax)
    $maxed = false;
    if($mined && $thisdigit > $thismin)
    $mined = false;
    }

    //Check if the number is prime
    while(!$this->is_prime($num)) {
    //If the number is not prime, add 2 or 4 (since it is currently an odd number)
    //This will keep the number odd and skip 5 to speed up the primality testing
    if(substr($num, -1, 1) == 3)
    $num = bcadd($num, 4);
    else
    $num = bcadd($num, 2);
    $tries++;
    }
    return $num;
    }

    function entropyarray($digits) {
    //create a long number based on as much entropy as possible
    $a = base_convert(md5(microtime()), 16, 10);
    $b = base_convert(sha1(@exec('uptime')), 16, 10);
    $c = mt_rand();
    $d = disk_total_space("/");
    $e = rand();
    $f = memory_get_usage();

    //Make sure it is only numbers, scramble it and make it the right length
    $num = str_shuffle(preg_replace("[^0-9]", '', $a . $b . $c . $d . $e));
    if(strlen($num) > $digits)
    $num = substr($num, 0, $digits);
    else
    while(strlen($num) < $digits)
    $num = str_shuffle(substr(base_convert(md5($num), 16, 10), 3, 1) . $num);

    //Turn the number into an array and return it
    $ent_array = str_split($num);
    return $ent_array;
    }

    function is_prime($num) {
    if(bccomp($num, 1) < 1)
    return false;
    //Clear the easy stuff (divide by all primes under 20,000)
    foreach($this->primes as $prime) {
    if(bccomp($num, $prime) == 0)
    return true;
    if(!bcmod($num, $prime))
    return false;
    }

    //Try the more complex method with the first 7 primes as bases
    for($i = 0; $i < 7; $i++) {
    if(!$this->_millerTest($num, $this->primes[$i]))
    return false; //Number is composite
    }

    //Strong probability that the number is prime
    return true;
    }

    function _millerTest($num, $base) {
    if(!bccomp($num, '1')) {
    // 1 is not prime ;)
    return false;
    }
    $tmp = bcsub($num, '1');

    $zero_bits = 0;
    while (!bccomp(bcmod($tmp, '2'), '0')) {
    $zero_bits++;
    $tmp = bcdiv($tmp, '2');
    }

    $tmp = $this->powmod($base, $tmp, $num);
    if (!bccomp($tmp, '1')) {
    // $num is probably prime
    return true;
    }

    while ($zero_bits--) {
    if (!bccomp(bcadd($tmp, '1'), $num)) {
    // $num is probably prime
    return true;
    }
    $tmp = $this->powmod($tmp, '2', $num);
    }
    // $num is composite
    return false;
    }

    function euclid($num, $mod) {
    //The Extended Euclidian Algorithm
    $x = '1';
    $y = '0';
    $num1 = $mod;
    do {
    $tmp = bcmod($num, $num1);
    $q = bcdiv($num, $num1);
    $num = $num1;
    $num1 = $tmp;

    $tmp = bcsub($x, bcmul($y, $q));
    $x = $y;
    $y = $tmp;
    } while (bccomp($num1, '0'));
    if (bccomp($x, '0') < 0) {
    $x = bcadd($x, $mod);
    }
    return $x;
    }

    function powmod($num, $pow, $mod) {
    if (function_exists('bcpowmod')) {
    // bcpowmod is only available under PHP5
    return bcpowmod($num, $pow, $mod);
    }

    // emulate bcpowmod
    $result = '1';
    do {
    if (!bccomp(bcmod($pow, '2'), '1')) {
    $result = bcmod(bcmul($result, $num), $mod);
    }
    $num = bcmod(bcpow($num, '2'), $mod);

    $pow = bcdiv($pow, '2');
    } while (bccomp($pow, '0'));
    return $result;
    }
    }
    ?>
    [/code]
    Copy linkTweet thisAlerts:
    @vishnuyrApr 02.2016 β€”Β Thanks a lot to post the code .

    I have tried the above code , but i need the help in applying the RSA algorithm for PDF files.

    Can you help me out ASAP?
    Γ—

    Success!

    Help @Stevish spread the word by sharing this article on Twitter...

    Tweet This
    Sign in
    Forgot password?
    Sign in with TwitchSign in with GithubCreate Account
    about: ({
    version: 0.1.9 β€” BETA 5.20,
    whats_new: community page,
    up_next: more Davinciβ€’003 tasks,
    coming_soon: events calendar,
    social: @webDeveloperHQ
    });

    legal: ({
    terms: of use,
    privacy: policy
    });
    changelog: (
    version: 0.1.9,
    notes: added community page

    version: 0.1.8,
    notes: added Davinciβ€’003

    version: 0.1.7,
    notes: upvote answers to bounties

    version: 0.1.6,
    notes: article editor refresh
    )...
    recent_tips: (
    tipper: @AriseFacilitySolutions09,
    tipped: article
    amount: 1000 SATS,

    tipper: @Yussuf4331,
    tipped: article
    amount: 1000 SATS,

    tipper: @darkwebsites540,
    tipped: article
    amount: 10 SATS,
    )...