首页 > 学院 > 逻辑算法 > 正文

php下的RSA算法实现

2020-02-06 17:12:37
字体:
来源:转载
供稿:网友

/*
* implementation of the rsa algorithm
* (c) copyright 2004 edsko de vries, ireland
*
* licensed under the gnu public license (gpl)
*
* this implementation has been verified against [3]
* (tested java/php interoperability).
*
* references:
* [1] "applied cryptography", bruce schneier, john wiley & sons, 1996
* [2] "prime number hide-and-seek", brian raiter, muppetlabs (online)
* [3] "the bouncy castle crypto package", legion of the bouncy castle,
* (open source cryptography library for java, online)
* [4] "pkcs #1: rsa encryption standard", rsa laboratories technical note,
* version 1.5, revised november 1, 1993

*/

/*
* functions that are meant to be used by the user of this php module.
*
* notes:
* - $key and $modulus should be numbers in (decimal) string format
* - $message is expected to be binary data
* - $keylength should be a multiple of 8, and should be in bits
* - for rsa_encrypt/rsa_sign, the length of $message should not exceed
* ($keylength / 8) - 11 (as mandated by [4]).
* - rsa_encrypt and rsa_sign will automatically add padding to the message.
* for rsa_encrypt, this padding will consist of random values; for rsa_sign,
* padding will consist of the appropriate number of 0xff values (see [4])
* - rsa_decrypt and rsa_verify will automatically remove message padding.
* - blocks for decoding (rsa_decrypt, rsa_verify) should be exactly
* ($keylength / 8) bytes long.
* - rsa_encrypt and rsa_verify expect a public key; rsa_decrypt and rsa_sign
* expect a private key.

*/

function rsa_encrypt($message, $public_key, $modulus, $keylength)
{

    $padded = add_pkcs1_padding($message, true, $keylength / 8);
    $number = binary_to_number($padded);
    $encrypted = pow_mod($number, $public_key, $modulus);
    $result = number_to_binary($encrypted, $keylength / 8);
    
    return $result;
}


function rsa_decrypt($message, $private_key, $modulus, $keylength)
{

    $number = binary_to_number($message);
    $decrypted = pow_mod($number, $private_key, $modulus);
    $result = number_to_binary($decrypted, $keylength / 8);

    return remove_pkcs1_padding($result, $keylength / 8);
}


function rsa_sign($message, $private_key, $modulus, $keylength)
{

    $padded = add_pkcs1_padding($message, false, $keylength / 8);
    $number = binary_to_number($padded);
    $signed = pow_mod($number, $private_key, $modulus);
    $result = number_to_binary($signed, $keylength / 8);

    return $result;
}


function rsa_verify($message, $public_key, $modulus, $keylength)
{

    return rsa_decrypt($message, $public_key, $modulus, $keylength);
}


/*
* some constants

*/

define("bccomp_larger", 1);

/*
* the actual implementation.
* requires bcmath support in php (compile with --enable-bcmath)

*/

//--
// calculate (p ^ q) mod r
//
// we need some trickery to [2]:
// (a) avoid calculating (p ^ q) before (p ^ q) mod r, because for typical rsa
// applications, (p ^ q) is going to be _way_ too large.
// (i mean, __way__ too large - won't fit in your computer'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_pus(
$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 [4]
//--

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 [4] for more details.
//--

function remove_pkcs1_padding($data, $blocksize)
{

    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"));

    // remove the padding
$offset = strpos($data, "/0", 1);
    return substr($data, $offset + 1);
}


//--
// 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 $result;
}


//--
// convert a number back into binary form
//--

function number_to_binary($number, $blocksize)
{

    $base = "256";
    $result = "";

    $div = $number;
    while($div > 0)
    {

        $mod = bcmod($div, $base);
        $div = bcdiv($div, $base);
        
        $result = chr($mod) . $result;
    }


    return str_pad($result, $blocksize, "/x00", str_pad_left);
}

?>
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选