欢迎光临TRip的专栏

--焦急的等待燃烧的刹那

曹宇ID:trip
86839次访问,排名1010好友0人,关注者2
trip的文章
原创 75 篇
翻译 0 篇
转载 1 篇
评论 9 篇
待燃的烟头的公告
声明:本Blog的部分文章是费尽千辛万苦从全国各地搜刮而来的,版权归原作者所有.
点击发送消息给我 QQ : 10245499
最近评论
agjyfm:wow gold
xiaohang99:我在网上找了好久,好不容易找到了您blog里收藏的php rsa代码,以下是我写的一段程序,可是rsa加密出来的使用是乱码,我郁闷了,请老大您不吝指点
<?
include("rsa.php");
//p:4133935801205863
//q:391939488017981
//n:16202526814238280264……
TOM:我想要一个直接可以运行的代码,可以给我吗!非常感谢!
E-mail:pulanhui@hotmail.com 狂等!
kus:但也许是我的问题,有的地方老是调试不通
6yhgyknyji:kjyujhklihmjolkomkmjliojhjkjkjkl
文章分类
收藏
    相册
    DOwnlOAd
    Java资料收集
    Eclipse 3 + Lomboz 3 + Tomcat 5 开发网站
    Eclipse, Lomboz and Tomcat 的 JSP 调试
    Eclipse, Lomboz and Tomcat 的 Web Project 设置
    IBM JAVA技术专区
    SUN 社区论坛
    吴蔚文集
    Linux相关
    Linux AS 3 中文手册
    linux资源站(EN)
    中国网关联盟论坛
    开源软件国际化·简体中文组
    Lotus资源
    OA软件联盟
    PHP相关Blog
    "阿信"的javascript强站!
    Haohappy的专栏--PHP5研究中心--
    paulgao-高春辉
    PHP&More 杂志 Wiki
    PHP5研究中心
    PHP5研究室
    PHP中文站(RSS)
    存档
    软件项目交易
    订阅我的博客
    XML聚合  FeedSky
    订阅到鲜果
    订阅到Google
    订阅到抓虾
    订阅到BlogLines
    订阅到Yahoo
    订阅到GouGou
    订阅到飞鸽
    订阅到Rojo
    订阅到newsgator
    订阅到netvibes

    原创 php下的RSA算法实现收藏

    新一篇: PHP下得到客户端ip的方法 | 旧一篇: PHP下如何对文件进行加锁

    /*
    * 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);
    }

    ?>

    发表于 @ 2005年07月12日 08:47:00|评论(loading...)|编辑

    新一篇: PHP下得到客户端ip的方法 | 旧一篇: PHP下如何对文件进行加锁

    评论

    #xiaohang99 发表于2006-01-14 12:39:00  IP: 60.176.95.*
    我在网上找了好久,好不容易找到了您blog里收藏的php rsa代码,以下是我写的一段程序,可是rsa加密出来的使用是乱码,我郁闷了,请老大您不吝指点
    <?
    include("rsa.php");
    //p:4133935801205863
    //q:391939488017981
    //n:1620252681423828026459626622603
    //d:1112516264707268870964168074921
    //e:10001
    //keysize:128


    $M= rsa_encrypt("1234567","10001",
    "46082400091804843600160060165903",128);
    echo $M;
    echo rsa_decrypt($M,"14532935695385704694469548719553"
    ,"46082400091804843600160060165903",128)
    ?>

    发表评论  


    当前用户设置只有注册用户才能发表评论。如果你没有登录,请点击登录
    Csdn Blog version 3.1a
    Copyright © 待燃的烟头