php下的RSA算法实现

王朝php·作者佚名  2006-11-24
窄屏简体版  字體: |||超大  

/*

* 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,

[1] [2] [3] [4] [5] [6] 下一页

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
 
© 2005- 王朝網路 版權所有 導航