php下的RSA算法实现

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

时间: 2024-08-02 21:50:51

php下的RSA算法实现的相关文章

RSA算法原理(一)

如果你问我,哪一种算法最重要? 我可能会回答"公钥加密算法". 因为它是计算机通信安全的基石,保证了加密数据不会被破解.你可以想象一下,信用卡交易被破解的后果. 进入正题之前,我先简单介绍一下,什么是"公钥加密算法". 一.一点历史 1976年以前,所有的加密方法都是同一种模式: (1)甲方选择某一种加密规则,对信息进行加密: (2)乙方使用同一种规则,对信息进行解密. 由于加密和解密使用同样规则(简称"密钥"),这被称为"对称加密算法

基于私钥加密公钥解密的RSA算法C#实现

RSA算法是第一个能同时用于加密和数字签名的算法,也易于理解和操作. RSA是被研究得最广泛的公钥算法,从提出到现在已近二十年,经历了各种攻击的 考验,逐渐为人们接受,普遍认为是目前最优秀的公钥方案之一.RSA的安全性依 赖于大数的因子分解,但并没有从理论上证明破译RSA的难度与大数分解难度等价 . RSA的安全性依赖于大数分解.公钥和私钥都是两个大素数( 大于 100 个十进制位)的函数.据猜测,从一个密钥和密文推断出明文的难度等同于分解 两个大素数的积. 密钥对的产生.选择两个大素数,p 和

RSA算法

先说下这个算法,RSA公钥加密算法是1977年由Ron Rivest.Adi Shamirh和LenAdleman在(美国麻省理工学院)开发的. 这个算法的名字也是他们三个人名字首字母,RSA算法基于一个十分简单的数论事实:将两个大素数相乘十分容易,但想要对其乘积进行因式分解却极其困难,因此可以将乘积公开作为加密密钥. package rsa; import java.math.BigInteger; public class RSA { private long p,q,e,d,n; publ

Swift 使用RSA算法进行数据加密,解密以及数字签名

RSA算法是一种非对称加密算法,要了解RSA算法,首先要知道什么是对称加密算法,什么是非对称加密算法. 1,对称加密算法 密钥只有一个,发收信双方都使用这个密钥对数据进行加密和解密. 特点:算法公开.计算量小.加密速度快.加密效率高特点.但交易双方都使用同样钥匙,安全性得不到保证. 具体算法有:DES算法,3DES算法,TDEA算法,Blowfish算法,RC5算法,IDEA算法. 2,非对称加密算法 非对称加密算法需要两个密钥:公开密钥(publickey)和私有密钥(privatekey).

加密解密-DES算法和RSA算法

昨天忽然对加密解密有了兴趣,今天上班查找了一些资料,现在就整理一下吧:) 一.DES算法 这种算法如图所示,这里将描述它的每一个步骤.这个算法进行了16次迭代(圈),把各块明文交织起来与 从密钥中获得的值混合.这个算法就像织线的织布机一样.明文被分成两根线,密钥就像染料一样在每一圈中 改变线的颜色.结果是一个五颜六色织好的图案. ********** ********** *原始消息 * * 密钥 * ********** ********** || || || || || || *******

RSA算法原理(二)

上一次,我介绍了一些数论知识. 有了这些知识,我们就可以看懂RSA算法.这是目前地球上最重要的加密算法. 六.密钥生成的步骤 我们通过一个例子,来理解RSA算法.假设爱丽丝要与鲍勃进行加密通信,她该怎么生成公钥和私钥呢? 第一步,随机选择两个不相等的质数p和q. 爱丽丝选择了61和53.(实际应用中,这两个质数越大,就越难破解.) 第二步,计算p和q的乘积n. 爱丽丝就把61和53相乘. n = 61×53 = 3233 n的长度就是密钥长度.3233写成二进制是110010100001,一共有

C#基于大整数类的RSA算法实现(公钥加密解密,私钥加密解密)

最近因为项目需要通过RSA加密来保证客户端与服务端的通信安全.但是C#自 带的RSA算法类RSACryptoServiceProvider只支持公钥加密私钥解密,即数字证 书的使用. 所以参考了一些网上的资料写了一个RSA的算法实现.算法实 现是基于网上提供的一个大整数类. 一.密钥管理 取得密钥主要 是通过2种方式 一种是通过RSACryptoServiceProvider取得: /// <summary> /// RSA算法对象,此处主要用于获取密钥对 /// </summary&g

RSA算法解析

RSA是第一个既能用于数据加密也能用于数字签名的算法.它易于理解和操作,也很流行.算法的名字以发明者的名字命名:Ron Rivest, Adi Shamir 和Leonard Adleman.但RSA的安全性一直未能得到理论上的证明.它经历了各种攻击,至今未被完全攻破. 它是第一个既能用于数据加密也能用于数字签名的算法.它易于理解和操作,也很流行.算法的名字以发明者的名字命名:Ron Rivest, Adi Shamir 和Leonard Adleman.但RSA的安全性一直未能得到理论上的证明

安全-rsa算法中私钥能不能是负数

问题描述 rsa算法中私钥能不能是负数 C语言写的函数计算17x+3120y=1的时候x的乘法逆元算出来是-367,请问能不能用负数作为私钥啊? 解决方案 可以.(必须得加上几个字) 解决方案二: http://www.cnblogs.com/Veegin/archive/2011/08/11/2135411.html while(D<=0) D+=(P-1)*(Q-1);//将负逆元转正 解决方案三: 不行.是质数.需要为正