iLinux

自由、梦想、飞翔 --- Free Dream Soar

forlinuxID:forlinux
86294次访问,排名1068好友2人,关注者4
forlinux的文章
原创 79 篇
翻译 0 篇
转载 67 篇
评论 74 篇
只爱LINUX的公告
机遇+努力=成功
努力才会有希望...
点击这里给我发消息
最近评论
forlinux:另: 使用 Ndiswrapper时,若linux是64位的,得使用64位的windows驱动程序
bingbingw:谢谢啊,多谢了
vvukqr:WoW Gold
vvukqr:WoW Gold
vvukqr:WoW Gold
文章分类
收藏
相册
只爱这一秒
.NET资源
.net Free soft
dotnet开源
Filehelper-Exp/Imp Data2DB
MSDN-library
Ajax Framework
jquery——The writte less,do more
prototype.js
prototype.js开发者文档
JAVA资源
java开源大全
中国IT实验室ECLIPSE专题
linux资源
202.96.64.144
ChinaUnix网友空间
Cooperative Linux(colinux)
OpenSSH For Windows
Oracle On Linux
Reactos(Wine Base)
Wine模拟器
健兔linux
成都理工大学FTP
班图LINUX
红帽Linux
长江大学FTP
鳥哥的Linux私房菜
lnux社区
linuxsir.org
linux伊甸园
linux公社
PHP资源
Apache with Open SSL
Apache软件历史版本
phpv.net
中日韩翻译
数据库相关
Oracle NetWorking FAQ
友情链接
baidu博客分站
SourceForge主页
漂在生活
闲云
存档
软件项目交易
订阅我的博客
XML聚合  FeedSky
订阅到鲜果
订阅到Google
订阅到抓虾
订阅到BlogLines
订阅到Yahoo
订阅到GouGou
订阅到飞鸽
订阅到Rojo
订阅到newsgator
订阅到netvibes

原创 How to use the rsa key generted by .net with php?收藏

新一篇: 让Totem使用Xine-lib库  | 旧一篇: 使用HttpHandler功能,把aspx文件编译进dll

the Solution .infact it's so easy to use rsakey file generated by .net .

------------rsa.class.php-------------------

<?php
/*
*fileName rsa.class.php
*author: laiyunqing<laiyunqing#gmail.com>
 * Some constants
 
*/
define("BCCOMP_LARGER", 1);
class RSA
{
 
/*
  * 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.
  
*/

 
/**
  * rsa encrypt data
  *
  * @param binary string $message
  * @param unknown_type $public_key
  * @param numbers $modulus
  * @param numbers $keylength
  * @return binary data
  
*/
 
function rsa_encrypt($message, $public_key, $modulus, $keylength)
 {
  
$padded = RSA::add_PKCS1_padding($message, true, $keylength / 8);
  
$number = RSA::binary_to_number($padded);
  
$encrypted = RSA::pow_mod($number, $public_key, $modulus);
  
$result = RSA::number_to_binary($encrypted, $keylength / 8);

  
return $result;
 }

 
function rsa_decrypt($message, $private_key, $modulus, $keylength)
 {
  
$number = RSA::binary_to_number($message);
  
$decrypted = RSA::pow_mod($number, $private_key, $modulus);
  
$result = RSA::number_to_binary($decrypted, $keylength / 8);

  
return RSA::remove_PKCS1_padding($result, $keylength / 8);
 }

 
function rsa_sign($message, $private_key, $modulus, $keylength)
 {
  
$padded = RSA::add_PKCS1_padding($message, false, $keylength / 8);
  
$number = RSA::binary_to_number($padded);
  
$signed = RSA::pow_mod($number, $private_key, $modulus);
  
$result = RSA::number_to_binary($signed, $keylength / 8);

  
return $result;
 }

 
function rsa_verify($message, $public_key, $modulus, $keylength)
 {
  
return RSA::rsa_decrypt($message, $public_key, $modulus, $keylength);
 }

 
function rsa_kyp_verify($message, $public_key, $modulus, $keylength)
 {
  
$number = RSA::binary_to_number($message);
  
$decrypted = RSA::pow_mod($number, $public_key, $modulus);
  
$result = RSA::number_to_binary($decrypted, $keylength / 8);

  
return RSA::remove_KYP_padding($result, $keylength / 8);
 }


 
/*
  * 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($remarray_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_push($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 = "";

   
$padding = "";
   
for($i = 0$i < $pad_length$i++)
   {
    
$rnd = mt_rand(1, 255);
    
$padding .= chr($rnd);
   }
  }
  
else
  {
   
$block_type = "";
   
$padding = str_repeat("ÿ", $pad_length);
  }

  
return "" . $block_type . $padding . "" . $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== '')
  
die("Block type 0 not implemented.");

  
// Then the block type must be 1 or 2
  assert(($data{0== ""|| ($data{0== ""));
  
// Remove the padding
  $offset = strpos($data, "", 1);
  
return substr($data, $offset + 1);
 }

 
//--
 // Remove "kyp" padding
 // (Non standard)
 //--

 function remove_KYP_padding($data, $blocksize)
 {
  
assert(strlen($data== $blocksize);

  
$offset = strpos($data, "");
  
return substr($data, 0, $offset);
 }

 
//--
 // 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, "", STR_PAD_LEFT);
 }
}
?>

-------------RSAProcessor.class.php------------------------


<?php
/**
*fileName RSAProcessor.class.php
*author: laiyunqing<laiyunqing#gmail.com>
*/
require_once("rsa.class.php");

class RSAProcessor
{
 
 
private $public_key = null;
 
 
private $private_key = null;
 
 
private $modulus = null;
 
 
private $key_length = "1024";
 
 
 
public function __construct($xmlRsakey=null,$type=null)
 {
         
$xmlObj = null;
 
   
if($xmlRsakey==null)
          {
           
$xmlObj = simplexml_load_file("xmlfile/RSAKey.xml");
          }
          
elseif($type==RSAKeyType::XMLFile)
          {
           
$xmlObj = simplexml_load_file($xmlRsakey);
          }
          
else
          {
           
$xmlObj = simplexml_load_string($xmlRsakey);
          }
         
$this->modulus = RSA::binary_to_number(base64_decode($xmlObj->Modulus));
   
$this->public_key = RSA::binary_to_number(base64_decode($xmlObj->Exponent));
   
$this->key_length = strlen(base64_decode($xmlObj->Modulus))*8;
 }
 
/**
  * get public key
  *
  * @return string public key
  
*/
 
public function getPublicKey()
 {
  
//return base64_encode(RSA::number_to_binary($this->public_key,($this->key_length)/8));
  return $this->public_key;
 }
 
public function getPrivateKey()
 {
  
//return base64_encode(RSA::number_to_binary($this->private_key,($this->key_length)/8));
  return $this->private_key;
 }
 
public function getKeyLength()
 {
  
return $this->key_length;
 }
 
public function getModulus()
 {
  
return $this->modulus;
 }
 
/**
  * encrypt data
  *
  * @param string $data
  * @return base64 encoded  binary string
  
*/
 
public function encrypt($data)
 {
  
return base64_encode(RSA::rsa_encrypt($data,$this->public_key,$this->modulus,$this->key_length));
 }
 
 
public function dencrypt($data)
 {
  
return RSA::rsa_decrypt($data,$this->private_key,$this->modulus,$this->key_length);
 }
 
 
public function sign($data)
 {
  
return RSA::rsa_sign($data,$this->private_key,$this->modulus,$this->key_length);
 }
 
 
public function verify($data)
 {
  
return RSA::rsa_verify($data,$this->public_key,$this->modulus,$this->key_length);
 }
}

class RSAKeyType
{
 
const XMLFile = 0;
 
const XMLString = 1;
}
?>

-------------- encrypt data with public key-----------------

<?php
/**
*fileName testrsa.php
*author: laiyunqing<laiyunqing#gmail.com>
*/
require_once("RSAProcessor.class.php");
$processor = new RSAProcessor

(
"<RSAKeyValue><Modulus>m6ljoeWhmnd0oRnsVEH5iNw3B8+vKVu7v7CVfMyf6bnKEzHa62TRmT/baJiSevoI/vgm2ph/s1JrQQTaGiErHicigwSC

Aw7+i05WFbnz7tOyiiJJVMfsdd+v7Xan9Hiud05FzxoMbM8vpiMHPEIDbGJ1MiXyupTVkz2WcMHyBoJ4S189opktZ43pviUhy0PeuWkyoU7zR54akPmK

Yg+z5Zr1r7K8lUZ1a3TThfJGxTQR/uZMtZz/q8QF0AANVQ/eyahTv9icBzBoDuncS0Y5l3vqogW1C/ltJvhJpvSn/OgjbRjuixCAptOUmRd13sDWU95/

x0bMq+Lg68lj2OjJ1Q==</Modulus><Exponent>AQAB</Exponent><P>zfvdBsMLlmo+4PAUYLgSV2xyyVa7ZqFjkJaAE4EbYuH24EoZjrzeiJR++D

FUT/GUhjfZ5eZ/5e29dXwk0sKUw6nHzBdBtOPp5fr4t5SKLEcWY+J+zLUSOlhG9NUkohFf6+Miy2Y7BLpXVrcl6UwXV0ak8KkTPB2l/aIMwYj5dgc=</

P><Q>wXV0sA3nDzoSDQA/4QSu/WIlBhkA3jZ7K7G9Z9rpP1A0vH+bZeyCIyo52u8ahGuYbubaizF1XMp+Xv3Mh2KmRbt7+UptwEwbFAUiiad2a312mqm

j7IJd7gRjGkyzKEm+6fpNeY3NFLNVNhccBqzhNkRoM22xnvQcImD10XVAakM=</Q><DP>wd1HdCLEWCfc0DYE59a2pINUMXyo2foRTDbpifHcRZ+ojAY

Rsc6+nsssCQnccXVMNVqBgSgEvfGYe+eAfMBX5SN5APPuioJrVGF2DsoFlZC+WPoGH0JYSoNlHO8yEDrMDaXzzH2GFHgQ1XOAged0nFbHzB1FFjJNVL5

cxRXWu6c=</DP><DQ>QDKuCk5SwubOXqoaiJ15RHRxPNjHRPZnYVSWOgSXKn9/QJ5H/0bA2NKGaHS4JAFgkEzjcRV0kNpRnUwztymxa6qPtWZRjWK0Ca

y6jVuZHIqB9UkeMLoCWZ3zFSMmwNPYGuUJGLFJwPjR6iU5E64C/nMs8QQR0WHIhFAQwvVZ7uk=</DQ><InverseQ>JckMSlJR10VZdnp83VPjrZ/Z+63

CGu3tWHm7f4DJ8IwjJWr8FlCpbSwiP6a4e9Upv6bUn/tOj2gY6MMq5G5yTKm2SCRvpUKRu4NCmWAt7vlFv0Z6pkXlTOpzvVjv3v16+dIZOA5Zn+v7+r1

xbdYdH20KRAbiBO3MfQP7s+VJJvM=</InverseQ><D>W1xrBr2hQOj1wgxWAgoK7IHbprEFrK+TnWmGA46SGPsbmHJ9fAVbY6fwHg7Wgmk4WHXLUCeLY

/Nu0eWIISfwh60Oe3ls2WC2k4qxyeSvQDBuLNb81U7WAUT9m9E1uK4QMCP3oxs1ybM80zTh7UMNgVK0WG+fbFUomVffcWTTqW+Fu12PEIO+UR/85oq+x

qVlTzYAEzt1OE9IhkYiRzi99ePXeH2gFltzJ/fb/7jLsDTkhM2eiYTGyOTZmBnen6c6a8b9LFTY4Bc0bGpk5ezHkub6F8p2ZgL/JgIOJMyRZICjDjs+9

k9PTmMTFsCF6xzHY15Fg25xIDYzIyx1rrRUjQ==</D></RSAKeyValue>
",RSAKeyType::XMLString);
$rs =  $processor->encrypt("Hello,It's Works.");
echo $rs;
?>

 

发表于 @ 2008年05月25日 02:31:00|评论(loading...)|编辑

新一篇: 让Totem使用Xine-lib库  | 旧一篇: 使用HttpHandler功能,把aspx文件编译进dll

评论:没有评论。

发表评论  


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