日期:2012-08-07  浏览次数:20494 次

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