/**
* Pure-PHP PKCS#1 (v2.1) compliant implementation of RSA.
*
- * PHP versions 4 and 5
+ * PHP version 5
*
* Here's an example of how to encrypt and decrypt text with this library:
* <code>
* <?php
- * include 'Crypt/RSA.php';
+ * include 'vendor/autoload.php';
*
- * $rsa = new Crypt_RSA();
+ * $rsa = new \phpseclib\Crypt\RSA();
* extract($rsa->createKey());
*
* $plaintext = 'terrafrost';
* Here's an example of how to create signatures and verify signatures with this library:
* <code>
* <?php
- * include 'Crypt/RSA.php';
+ * include 'vendor/autoload.php';
*
- * $rsa = new Crypt_RSA();
+ * $rsa = new \phpseclib\Crypt\RSA();
* extract($rsa->createKey());
*
* $plaintext = 'terrafrost';
* ?>
* </code>
*
- * LICENSE: Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to deal
- * in the Software without restriction, including without limitation the rights
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- * copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- * THE SOFTWARE.
- *
* @category Crypt
- * @package Crypt_RSA
+ * @package RSA
* @author Jim Wigginton <terrafrost@php.net>
* @copyright 2009 Jim Wigginton
* @license http://www.opensource.org/licenses/mit-license.html MIT License
* @link http://phpseclib.sourceforge.net
*/
-/**
- * Include Crypt_Random
- */
-// the class_exists() will only be called if the crypt_random_string function hasn't been defined and
-// will trigger a call to __autoload() if you're wanting to auto-load classes
-// call function_exists() a second time to stop the include_once from being called outside
-// of the auto loader
-if (!function_exists('crypt_random_string')) {
- include_once 'Random.php';
-}
+namespace phpseclib\Crypt;
-/**
- * Include Crypt_Hash
- */
-if (!class_exists('Crypt_Hash')) {
- include_once 'Hash.php';
-}
+use phpseclib\Math\BigInteger;
-/**#@+
- * @access public
- * @see Crypt_RSA::encrypt()
- * @see Crypt_RSA::decrypt()
- */
-/**
- * Use {@link http://en.wikipedia.org/wiki/Optimal_Asymmetric_Encryption_Padding Optimal Asymmetric Encryption Padding}
- * (OAEP) for encryption / decryption.
- *
- * Uses sha1 by default.
- *
- * @see Crypt_RSA::setHash()
- * @see Crypt_RSA::setMGFHash()
- */
-define('CRYPT_RSA_ENCRYPTION_OAEP', 1);
/**
- * Use PKCS#1 padding.
- *
- * Although CRYPT_RSA_ENCRYPTION_OAEP offers more security, including PKCS#1 padding is necessary for purposes of backwards
- * compatibility with protocols (like SSH-1) written before OAEP's introduction.
- */
-define('CRYPT_RSA_ENCRYPTION_PKCS1', 2);
-/**#@-*/
-
-/**#@+
- * @access public
- * @see Crypt_RSA::sign()
- * @see Crypt_RSA::verify()
- * @see Crypt_RSA::setHash()
- */
-/**
- * Use the Probabilistic Signature Scheme for signing
- *
- * Uses sha1 by default.
- *
- * @see Crypt_RSA::setSaltLength()
- * @see Crypt_RSA::setMGFHash()
- */
-define('CRYPT_RSA_SIGNATURE_PSS', 1);
-/**
- * Use the PKCS#1 scheme by default.
+ * Pure-PHP PKCS#1 compliant implementation of RSA.
*
- * Although CRYPT_RSA_SIGNATURE_PSS offers more security, including PKCS#1 signing is necessary for purposes of backwards
- * compatibility with protocols (like SSH-2) written before PSS's introduction.
+ * @package RSA
+ * @author Jim Wigginton <terrafrost@php.net>
+ * @access public
*/
-define('CRYPT_RSA_SIGNATURE_PKCS1', 2);
-/**#@-*/
+class RSA
+{
+ /**#@+
+ * @access public
+ * @see self::encrypt()
+ * @see self::decrypt()
+ */
+ /**
+ * Use {@link http://en.wikipedia.org/wiki/Optimal_Asymmetric_Encryption_Padding Optimal Asymmetric Encryption Padding}
+ * (OAEP) for encryption / decryption.
+ *
+ * Uses sha1 by default.
+ *
+ * @see self::setHash()
+ * @see self::setMGFHash()
+ */
+ const ENCRYPTION_OAEP = 1;
+ /**
+ * Use PKCS#1 padding.
+ *
+ * Although self::ENCRYPTION_OAEP offers more security, including PKCS#1 padding is necessary for purposes of backwards
+ * compatibility with protocols (like SSH-1) written before OAEP's introduction.
+ */
+ const ENCRYPTION_PKCS1 = 2;
+ /**
+ * Do not use any padding
+ *
+ * Although this method is not recommended it can none-the-less sometimes be useful if you're trying to decrypt some legacy
+ * stuff, if you're trying to diagnose why an encrypted message isn't decrypting, etc.
+ */
+ const ENCRYPTION_NONE = 3;
+ /**#@-*/
-/**#@+
- * @access private
- * @see Crypt_RSA::createKey()
- */
-/**
- * ASN1 Integer
- */
-define('CRYPT_RSA_ASN1_INTEGER', 2);
-/**
- * ASN1 Bit String
- */
-define('CRYPT_RSA_ASN1_BITSTRING', 3);
-/**
- * ASN1 Octet String
- */
-define('CRYPT_RSA_ASN1_OCTETSTRING', 4);
-/**
- * ASN1 Object Identifier
- */
-define('CRYPT_RSA_ASN1_OBJECT', 6);
-/**
- * ASN1 Sequence (with the constucted bit set)
- */
-define('CRYPT_RSA_ASN1_SEQUENCE', 48);
-/**#@-*/
+ /**#@+
+ * @access public
+ * @see self::sign()
+ * @see self::verify()
+ * @see self::setHash()
+ */
+ /**
+ * Use the Probabilistic Signature Scheme for signing
+ *
+ * Uses sha1 by default.
+ *
+ * @see self::setSaltLength()
+ * @see self::setMGFHash()
+ */
+ const SIGNATURE_PSS = 1;
+ /**
+ * Use the PKCS#1 scheme by default.
+ *
+ * Although self::SIGNATURE_PSS offers more security, including PKCS#1 signing is necessary for purposes of backwards
+ * compatibility with protocols (like SSH-2) written before PSS's introduction.
+ */
+ const SIGNATURE_PKCS1 = 2;
+ /**#@-*/
-/**#@+
- * @access private
- * @see Crypt_RSA::Crypt_RSA()
- */
-/**
- * To use the pure-PHP implementation
- */
-define('CRYPT_RSA_MODE_INTERNAL', 1);
-/**
- * To use the OpenSSL library
- *
- * (if enabled; otherwise, the internal implementation will be used)
- */
-define('CRYPT_RSA_MODE_OPENSSL', 2);
-/**#@-*/
+ /**#@+
+ * @access private
+ * @see \phpseclib\Crypt\RSA::createKey()
+ */
+ /**
+ * ASN1 Integer
+ */
+ const ASN1_INTEGER = 2;
+ /**
+ * ASN1 Bit String
+ */
+ const ASN1_BITSTRING = 3;
+ /**
+ * ASN1 Octet String
+ */
+ const ASN1_OCTETSTRING = 4;
+ /**
+ * ASN1 Object Identifier
+ */
+ const ASN1_OBJECT = 6;
+ /**
+ * ASN1 Sequence (with the constucted bit set)
+ */
+ const ASN1_SEQUENCE = 48;
+ /**#@-*/
-/**
- * Default openSSL configuration file.
- */
-define('CRYPT_RSA_OPENSSL_CONFIG', dirname(__FILE__) . '/../openssl.cnf');
+ /**#@+
+ * @access private
+ * @see \phpseclib\Crypt\RSA::__construct()
+ */
+ /**
+ * To use the pure-PHP implementation
+ */
+ const MODE_INTERNAL = 1;
+ /**
+ * To use the OpenSSL library
+ *
+ * (if enabled; otherwise, the internal implementation will be used)
+ */
+ const MODE_OPENSSL = 2;
+ /**#@-*/
-/**#@+
- * @access public
- * @see Crypt_RSA::createKey()
- * @see Crypt_RSA::setPrivateKeyFormat()
- */
-/**
- * PKCS#1 formatted private key
- *
- * Used by OpenSSH
- */
-define('CRYPT_RSA_PRIVATE_FORMAT_PKCS1', 0);
-/**
- * PuTTY formatted private key
- */
-define('CRYPT_RSA_PRIVATE_FORMAT_PUTTY', 1);
-/**
- * XML formatted private key
- */
-define('CRYPT_RSA_PRIVATE_FORMAT_XML', 2);
-/**
- * PKCS#8 formatted private key
- */
-define('CRYPT_RSA_PRIVATE_FORMAT_PKCS8', 3);
-/**#@-*/
+ /**#@+
+ * @access public
+ * @see \phpseclib\Crypt\RSA::createKey()
+ * @see \phpseclib\Crypt\RSA::setPrivateKeyFormat()
+ */
+ /**
+ * PKCS#1 formatted private key
+ *
+ * Used by OpenSSH
+ */
+ const PRIVATE_FORMAT_PKCS1 = 0;
+ /**
+ * PuTTY formatted private key
+ */
+ const PRIVATE_FORMAT_PUTTY = 1;
+ /**
+ * XML formatted private key
+ */
+ const PRIVATE_FORMAT_XML = 2;
+ /**
+ * PKCS#8 formatted private key
+ */
+ const PRIVATE_FORMAT_PKCS8 = 8;
+ /**#@-*/
-/**#@+
- * @access public
- * @see Crypt_RSA::createKey()
- * @see Crypt_RSA::setPublicKeyFormat()
- */
-/**
- * Raw public key
- *
- * An array containing two Math_BigInteger objects.
- *
- * The exponent can be indexed with any of the following:
- *
- * 0, e, exponent, publicExponent
- *
- * The modulus can be indexed with any of the following:
- *
- * 1, n, modulo, modulus
- */
-define('CRYPT_RSA_PUBLIC_FORMAT_RAW', 3);
-/**
- * PKCS#1 formatted public key (raw)
- *
- * Used by File/X509.php
- *
- * Has the following header:
- *
- * -----BEGIN RSA PUBLIC KEY-----
- *
- * Analogous to ssh-keygen's pem format (as specified by -m)
- */
-define('CRYPT_RSA_PUBLIC_FORMAT_PKCS1', 4);
-define('CRYPT_RSA_PUBLIC_FORMAT_PKCS1_RAW', 4);
-/**
- * XML formatted public key
- */
-define('CRYPT_RSA_PUBLIC_FORMAT_XML', 5);
-/**
- * OpenSSH formatted public key
- *
- * Place in $HOME/.ssh/authorized_keys
- */
-define('CRYPT_RSA_PUBLIC_FORMAT_OPENSSH', 6);
-/**
- * PKCS#1 formatted public key (encapsulated)
- *
- * Used by PHP's openssl_public_encrypt() and openssl's rsautl (when -pubin is set)
- *
- * Has the following header:
- *
- * -----BEGIN PUBLIC KEY-----
- *
- * Analogous to ssh-keygen's pkcs8 format (as specified by -m). Although PKCS8
- * is specific to private keys it's basically creating a DER-encoded wrapper
- * for keys. This just extends that same concept to public keys (much like ssh-keygen)
- */
-define('CRYPT_RSA_PUBLIC_FORMAT_PKCS8', 7);
-/**#@-*/
+ /**#@+
+ * @access public
+ * @see \phpseclib\Crypt\RSA::createKey()
+ * @see \phpseclib\Crypt\RSA::setPublicKeyFormat()
+ */
+ /**
+ * Raw public key
+ *
+ * An array containing two \phpseclib\Math\BigInteger objects.
+ *
+ * The exponent can be indexed with any of the following:
+ *
+ * 0, e, exponent, publicExponent
+ *
+ * The modulus can be indexed with any of the following:
+ *
+ * 1, n, modulo, modulus
+ */
+ const PUBLIC_FORMAT_RAW = 3;
+ /**
+ * PKCS#1 formatted public key (raw)
+ *
+ * Used by File/X509.php
+ *
+ * Has the following header:
+ *
+ * -----BEGIN RSA PUBLIC KEY-----
+ *
+ * Analogous to ssh-keygen's pem format (as specified by -m)
+ */
+ const PUBLIC_FORMAT_PKCS1 = 4;
+ const PUBLIC_FORMAT_PKCS1_RAW = 4;
+ /**
+ * XML formatted public key
+ */
+ const PUBLIC_FORMAT_XML = 5;
+ /**
+ * OpenSSH formatted public key
+ *
+ * Place in $HOME/.ssh/authorized_keys
+ */
+ const PUBLIC_FORMAT_OPENSSH = 6;
+ /**
+ * PKCS#1 formatted public key (encapsulated)
+ *
+ * Used by PHP's openssl_public_encrypt() and openssl's rsautl (when -pubin is set)
+ *
+ * Has the following header:
+ *
+ * -----BEGIN PUBLIC KEY-----
+ *
+ * Analogous to ssh-keygen's pkcs8 format (as specified by -m). Although PKCS8
+ * is specific to private keys it's basically creating a DER-encoded wrapper
+ * for keys. This just extends that same concept to public keys (much like ssh-keygen)
+ */
+ const PUBLIC_FORMAT_PKCS8 = 7;
+ /**#@-*/
-/**
- * Pure-PHP PKCS#1 compliant implementation of RSA.
- *
- * @package Crypt_RSA
- * @author Jim Wigginton <terrafrost@php.net>
- * @access public
- */
-class Crypt_RSA
-{
/**
* Precomputed Zero
*
- * @var Array
+ * @var \phpseclib\Math\BigInteger
* @access private
*/
var $zero;
/**
* Precomputed One
*
- * @var Array
+ * @var \phpseclib\Math\BigInteger
* @access private
*/
var $one;
/**
* Private Key Format
*
- * @var Integer
+ * @var int
* @access private
*/
- var $privateKeyFormat = CRYPT_RSA_PRIVATE_FORMAT_PKCS1;
+ var $privateKeyFormat = self::PRIVATE_FORMAT_PKCS1;
/**
* Public Key Format
*
- * @var Integer
+ * @var int
* @access public
*/
- var $publicKeyFormat = CRYPT_RSA_PUBLIC_FORMAT_PKCS8;
+ var $publicKeyFormat = self::PUBLIC_FORMAT_PKCS8;
/**
* Modulus (ie. n)
*
- * @var Math_BigInteger
+ * @var \phpseclib\Math\BigInteger
* @access private
*/
var $modulus;
/**
* Modulus length
*
- * @var Math_BigInteger
+ * @var \phpseclib\Math\BigInteger
* @access private
*/
var $k;
/**
* Exponent (ie. e or d)
*
- * @var Math_BigInteger
+ * @var \phpseclib\Math\BigInteger
* @access private
*/
var $exponent;
/**
* Primes for Chinese Remainder Theorem (ie. p and q)
*
- * @var Array
+ * @var array
* @access private
*/
var $primes;
/**
* Exponents for Chinese Remainder Theorem (ie. dP and dQ)
*
- * @var Array
+ * @var array
* @access private
*/
var $exponents;
/**
* Coefficients for Chinese Remainder Theorem (ie. qInv)
*
- * @var Array
+ * @var array
* @access private
*/
var $coefficients;
/**
* Hash name
*
- * @var String
+ * @var string
* @access private
*/
var $hashName;
/**
* Hash function
*
- * @var Crypt_Hash
+ * @var \phpseclib\Crypt\Hash
* @access private
*/
var $hash;
/**
* Length of hash function output
*
- * @var Integer
+ * @var int
* @access private
*/
var $hLen;
/**
* Length of salt
*
- * @var Integer
+ * @var int
* @access private
*/
var $sLen;
/**
* Hash function for the Mask Generation Function
*
- * @var Crypt_Hash
+ * @var \phpseclib\Crypt\Hash
* @access private
*/
var $mgfHash;
/**
* Length of MGF hash function output
*
- * @var Integer
+ * @var int
* @access private
*/
var $mgfHLen;
/**
* Encryption mode
*
- * @var Integer
+ * @var int
* @access private
*/
- var $encryptionMode = CRYPT_RSA_ENCRYPTION_OAEP;
+ var $encryptionMode = self::ENCRYPTION_OAEP;
/**
* Signature mode
*
- * @var Integer
+ * @var int
* @access private
*/
- var $signatureMode = CRYPT_RSA_SIGNATURE_PSS;
+ var $signatureMode = self::SIGNATURE_PSS;
/**
* Public Exponent
*
- * @var Mixed
+ * @var mixed
* @access private
*/
var $publicExponent = false;
/**
* Password
*
- * @var String
+ * @var string
* @access private
*/
var $password = false;
* For use with parsing XML formatted keys. PHP's XML Parser functions use utilized - instead of PHP's DOM functions -
* because PHP's XML Parser functions work on PHP4 whereas PHP's DOM functions - although surperior - don't.
*
- * @see Crypt_RSA::_start_element_handler()
- * @var Array
+ * @see self::_start_element_handler()
+ * @var array
* @access private
*/
var $components = array();
*
* For use with parsing XML formatted keys.
*
- * @see Crypt_RSA::_character_handler()
- * @see Crypt_RSA::_stop_element_handler()
- * @var Mixed
+ * @see self::_character_handler()
+ * @see self::_stop_element_handler()
+ * @var mixed
* @access private
*/
var $current;
* OpenSSL configuration file name.
*
* Set to null to use system configuration file.
- * @see Crypt_RSA::createKey()
- * @var Mixed
+ * @see self::createKey()
+ * @var mixed
* @Access public
*/
var $configFile;
/**
* Public key comment field.
*
- * @var String
+ * @var string
* @access private
*/
var $comment = 'phpseclib-generated-key';
* The constructor
*
* If you want to make use of the openssl extension, you'll need to set the mode manually, yourself. The reason
- * Crypt_RSA doesn't do it is because OpenSSL doesn't fail gracefully. openssl_pkey_new(), in particular, requires
+ * \phpseclib\Crypt\RSA doesn't do it is because OpenSSL doesn't fail gracefully. openssl_pkey_new(), in particular, requires
* openssl.cnf be present somewhere and, unfortunately, the only real way to find out is too late.
*
- * @return Crypt_RSA
+ * @return \phpseclib\Crypt\RSA
* @access public
*/
- function Crypt_RSA()
+ function __construct()
{
- if (!class_exists('Math_BigInteger')) {
- include_once 'Math/BigInteger.php';
- }
-
- $this->configFile = CRYPT_RSA_OPENSSL_CONFIG;
+ $this->configFile = dirname(__FILE__) . '/../openssl.cnf';
- if ( !defined('CRYPT_RSA_MODE') ) {
+ if (!defined('CRYPT_RSA_MODE')) {
switch (true) {
// Math/BigInteger's openssl requirements are a little less stringent than Crypt/RSA's. in particular,
// Math/BigInteger doesn't require an openssl.cfg file whereas Crypt/RSA does. so if Math/BigInteger
// can't use OpenSSL it can be pretty trivially assumed, then, that Crypt/RSA can't either.
case defined('MATH_BIGINTEGER_OPENSSL_DISABLE'):
- define('CRYPT_RSA_MODE', CRYPT_RSA_MODE_INTERNAL);
+ define('CRYPT_RSA_MODE', self::MODE_INTERNAL);
break;
- // openssl_pkey_get_details - which is used in the only place Crypt/RSA.php uses OpenSSL - was introduced in PHP 5.2.0
- case !function_exists('openssl_pkey_get_details'):
- define('CRYPT_RSA_MODE', CRYPT_RSA_MODE_INTERNAL);
- break;
- case extension_loaded('openssl') && version_compare(PHP_VERSION, '4.2.0', '>=') && file_exists($this->configFile):
+ case extension_loaded('openssl') && file_exists($this->configFile):
// some versions of XAMPP have mismatched versions of OpenSSL which causes it not to work
ob_start();
@phpinfo();
case !isset($versions['Header']):
case !isset($versions['Library']):
case $versions['Header'] == $versions['Library']:
- define('CRYPT_RSA_MODE', CRYPT_RSA_MODE_OPENSSL);
+ case version_compare($versions['Header'], '1.0.0') >= 0 && version_compare($versions['Library'], '1.0.0') >= 0:
+ define('CRYPT_RSA_MODE', self::MODE_OPENSSL);
break;
default:
- define('CRYPT_RSA_MODE', CRYPT_RSA_MODE_INTERNAL);
+ define('CRYPT_RSA_MODE', self::MODE_INTERNAL);
define('MATH_BIGINTEGER_OPENSSL_DISABLE', true);
}
break;
default:
- define('CRYPT_RSA_MODE', CRYPT_RSA_MODE_INTERNAL);
+ define('CRYPT_RSA_MODE', self::MODE_INTERNAL);
}
}
- $this->zero = new Math_BigInteger();
- $this->one = new Math_BigInteger(1);
+ $this->zero = new BigInteger();
+ $this->one = new BigInteger(1);
- $this->hash = new Crypt_Hash('sha1');
+ $this->hash = new Hash('sha1');
$this->hLen = $this->hash->getLength();
$this->hashName = 'sha1';
- $this->mgfHash = new Crypt_Hash('sha1');
+ $this->mgfHash = new Hash('sha1');
$this->mgfHLen = $this->mgfHash->getLength();
}
* - 'privatekey': The private key.
* - 'publickey': The public key.
* - 'partialkey': A partially computed key (if the execution time exceeded $timeout).
- * Will need to be passed back to Crypt_RSA::createKey() as the third parameter for further processing.
+ * Will need to be passed back to \phpseclib\Crypt\RSA::createKey() as the third parameter for further processing.
*
* @access public
- * @param optional Integer $bits
- * @param optional Integer $timeout
- * @param optional Math_BigInteger $p
+ * @param int $bits
+ * @param int $timeout
+ * @param array $p
*/
function createKey($bits = 1024, $timeout = false, $partial = array())
{
// per <http://cseweb.ucsd.edu/~hovav/dist/survey.pdf#page=5>, this number ought not result in primes smaller
// than 256 bits. as a consequence if the key you're trying to create is 1024 bits and you've set CRYPT_RSA_SMALLEST_PRIME
// to 384 bits then you're going to get a 384 bit prime and a 640 bit prime (384 + 1024 % 384). at least if
- // CRYPT_RSA_MODE is set to CRYPT_RSA_MODE_INTERNAL. if CRYPT_RSA_MODE is set to CRYPT_RSA_MODE_OPENSSL then
+ // CRYPT_RSA_MODE is set to self::MODE_INTERNAL. if CRYPT_RSA_MODE is set to self::MODE_OPENSSL then
// CRYPT_RSA_SMALLEST_PRIME is ignored (ie. multi-prime RSA support is more intended as a way to speed up RSA key
// generation when there's a chance neither gmp nor OpenSSL are installed)
if (!defined('CRYPT_RSA_SMALLEST_PRIME')) {
}
// OpenSSL uses 65537 as the exponent and requires RSA keys be 384 bits minimum
- if ( CRYPT_RSA_MODE == CRYPT_RSA_MODE_OPENSSL && $bits >= 384 && CRYPT_RSA_EXPONENT == 65537) {
+ if (CRYPT_RSA_MODE == self::MODE_OPENSSL && $bits >= 384 && CRYPT_RSA_EXPONENT == 65537) {
$config = array();
if (isset($this->configFile)) {
$config['config'] = $this->configFile;
$publickey = openssl_pkey_get_details($rsa);
$publickey = $publickey['key'];
- $privatekey = call_user_func_array(array($this, '_convertPrivateKey'), array_values($this->_parseKey($privatekey, CRYPT_RSA_PRIVATE_FORMAT_PKCS1)));
- $publickey = call_user_func_array(array($this, '_convertPublicKey'), array_values($this->_parseKey($publickey, CRYPT_RSA_PUBLIC_FORMAT_PKCS1)));
+ $privatekey = call_user_func_array(array($this, '_convertPrivateKey'), array_values($this->_parseKey($privatekey, self::PRIVATE_FORMAT_PKCS1)));
+ $publickey = call_user_func_array(array($this, '_convertPublicKey'), array_values($this->_parseKey($publickey, self::PUBLIC_FORMAT_PKCS1)));
// clear the buffer of error strings stemming from a minimalistic openssl.cnf
- while (openssl_error_string() !== false);
+ while (openssl_error_string() !== false) {
+ }
return array(
'privatekey' => $privatekey,
static $e;
if (!isset($e)) {
- $e = new Math_BigInteger(CRYPT_RSA_EXPONENT);
+ $e = new BigInteger(CRYPT_RSA_EXPONENT);
}
extract($this->_generateMinMax($bits));
$finalMax = $max;
extract($this->_generateMinMax($temp));
- $generator = new Math_BigInteger();
+ $generator = new BigInteger();
$n = $this->one->copy();
if (!empty($partial)) {
* Convert a private key to the appropriate format.
*
* @access private
- * @see setPrivateKeyFormat()
- * @param String $RSAPrivateKey
- * @return String
+ * @see self::setPrivateKeyFormat()
+ * @param string $RSAPrivateKey
+ * @return string
*/
function _convertPrivateKey($n, $e, $d, $primes, $exponents, $coefficients)
{
- $signed = $this->privateKeyFormat != CRYPT_RSA_PRIVATE_FORMAT_XML;
+ $signed = $this->privateKeyFormat != self::PRIVATE_FORMAT_XML;
$num_primes = count($primes);
$raw = array(
'version' => $num_primes == 2 ? chr(0) : chr(1), // two-prime vs. multi
// if the format in question does not support multi-prime rsa and multi-prime rsa was used,
// call _convertPublicKey() instead.
switch ($this->privateKeyFormat) {
- case CRYPT_RSA_PRIVATE_FORMAT_XML:
+ case self::PRIVATE_FORMAT_XML:
if ($num_primes != 2) {
return false;
}
' <D>' . base64_encode($raw['privateExponent']) . "</D>\r\n" .
'</RSAKeyValue>';
break;
- case CRYPT_RSA_PRIVATE_FORMAT_PUTTY:
+ case self::PRIVATE_FORMAT_PUTTY:
if ($num_primes != 2) {
return false;
}
$encryption = (!empty($this->password) || is_string($this->password)) ? 'aes256-cbc' : 'none';
$key.= $encryption;
$key.= "\r\nComment: " . $this->comment . "\r\n";
- $public = pack('Na*Na*Na*',
- strlen('ssh-rsa'), 'ssh-rsa', strlen($raw['publicExponent']), $raw['publicExponent'], strlen($raw['modulus']), $raw['modulus']
+ $public = pack(
+ 'Na*Na*Na*',
+ strlen('ssh-rsa'),
+ 'ssh-rsa',
+ strlen($raw['publicExponent']),
+ $raw['publicExponent'],
+ strlen($raw['modulus']),
+ $raw['modulus']
);
- $source = pack('Na*Na*Na*Na*',
- strlen('ssh-rsa'), 'ssh-rsa', strlen($encryption), $encryption,
- strlen($this->comment), $this->comment, strlen($public), $public
+ $source = pack(
+ 'Na*Na*Na*Na*',
+ strlen('ssh-rsa'),
+ 'ssh-rsa',
+ strlen($encryption),
+ $encryption,
+ strlen($this->comment),
+ $this->comment,
+ strlen($public),
+ $public
);
$public = base64_encode($public);
$key.= "Public-Lines: " . ((strlen($public) + 63) >> 6) . "\r\n";
$key.= chunk_split($public, 64);
- $private = pack('Na*Na*Na*Na*',
- strlen($raw['privateExponent']), $raw['privateExponent'], strlen($raw['prime1']), $raw['prime1'],
- strlen($raw['prime2']), $raw['prime2'], strlen($raw['coefficient']), $raw['coefficient']
+ $private = pack(
+ 'Na*Na*Na*Na*',
+ strlen($raw['privateExponent']),
+ $raw['privateExponent'],
+ strlen($raw['prime1']),
+ $raw['prime1'],
+ strlen($raw['prime2']),
+ $raw['prime2'],
+ strlen($raw['coefficient']),
+ $raw['coefficient']
);
if (empty($this->password) && !is_string($this->password)) {
$source.= pack('Na*', strlen($private), $private);
$hashkey = 'putty-private-key-file-mac-key';
} else {
- $private.= crypt_random_string(16 - (strlen($private) & 15));
+ $private.= Random::string(16 - (strlen($private) & 15));
$source.= pack('Na*', strlen($private), $private);
- if (!class_exists('Crypt_AES')) {
- include_once 'Crypt/AES.php';
- }
$sequence = 0;
$symkey = '';
while (strlen($symkey) < 32) {
$symkey.= pack('H*', sha1($temp));
}
$symkey = substr($symkey, 0, 32);
- $crypto = new Crypt_AES();
+ $crypto = new AES();
$crypto->setKey($symkey);
$crypto->disablePadding();
$private = base64_encode($private);
$key.= 'Private-Lines: ' . ((strlen($private) + 63) >> 6) . "\r\n";
$key.= chunk_split($private, 64);
- if (!class_exists('Crypt_Hash')) {
- include_once 'Crypt/Hash.php';
- }
- $hash = new Crypt_Hash('sha1');
+ $hash = new Hash('sha1');
$hash->setKey(pack('H*', sha1($hashkey)));
$key.= 'Private-MAC: ' . bin2hex($hash->hash($source)) . "\r\n";
return $key;
- default: // eg. CRYPT_RSA_PRIVATE_FORMAT_PKCS1
+ default: // eg. self::PRIVATE_FORMAT_PKCS1
$components = array();
foreach ($raw as $name => $value) {
- $components[$name] = pack('Ca*a*', CRYPT_RSA_ASN1_INTEGER, $this->_encodeLength(strlen($value)), $value);
+ $components[$name] = pack('Ca*a*', self::ASN1_INTEGER, $this->_encodeLength(strlen($value)), $value);
}
$RSAPrivateKey = implode('', $components);
// exponent INTEGER, -- di
// coefficient INTEGER -- ti
// }
- $OtherPrimeInfo = pack('Ca*a*', CRYPT_RSA_ASN1_INTEGER, $this->_encodeLength(strlen($primes[$i]->toBytes(true))), $primes[$i]->toBytes(true));
- $OtherPrimeInfo.= pack('Ca*a*', CRYPT_RSA_ASN1_INTEGER, $this->_encodeLength(strlen($exponents[$i]->toBytes(true))), $exponents[$i]->toBytes(true));
- $OtherPrimeInfo.= pack('Ca*a*', CRYPT_RSA_ASN1_INTEGER, $this->_encodeLength(strlen($coefficients[$i]->toBytes(true))), $coefficients[$i]->toBytes(true));
- $OtherPrimeInfos.= pack('Ca*a*', CRYPT_RSA_ASN1_SEQUENCE, $this->_encodeLength(strlen($OtherPrimeInfo)), $OtherPrimeInfo);
+ $OtherPrimeInfo = pack('Ca*a*', self::ASN1_INTEGER, $this->_encodeLength(strlen($primes[$i]->toBytes(true))), $primes[$i]->toBytes(true));
+ $OtherPrimeInfo.= pack('Ca*a*', self::ASN1_INTEGER, $this->_encodeLength(strlen($exponents[$i]->toBytes(true))), $exponents[$i]->toBytes(true));
+ $OtherPrimeInfo.= pack('Ca*a*', self::ASN1_INTEGER, $this->_encodeLength(strlen($coefficients[$i]->toBytes(true))), $coefficients[$i]->toBytes(true));
+ $OtherPrimeInfos.= pack('Ca*a*', self::ASN1_SEQUENCE, $this->_encodeLength(strlen($OtherPrimeInfo)), $OtherPrimeInfo);
}
- $RSAPrivateKey.= pack('Ca*a*', CRYPT_RSA_ASN1_SEQUENCE, $this->_encodeLength(strlen($OtherPrimeInfos)), $OtherPrimeInfos);
+ $RSAPrivateKey.= pack('Ca*a*', self::ASN1_SEQUENCE, $this->_encodeLength(strlen($OtherPrimeInfos)), $OtherPrimeInfos);
}
- $RSAPrivateKey = pack('Ca*a*', CRYPT_RSA_ASN1_SEQUENCE, $this->_encodeLength(strlen($RSAPrivateKey)), $RSAPrivateKey);
+ $RSAPrivateKey = pack('Ca*a*', self::ASN1_SEQUENCE, $this->_encodeLength(strlen($RSAPrivateKey)), $RSAPrivateKey);
- if ($this->privateKeyFormat == CRYPT_RSA_PRIVATE_FORMAT_PKCS8) {
+ if ($this->privateKeyFormat == self::PRIVATE_FORMAT_PKCS8) {
$rsaOID = pack('H*', '300d06092a864886f70d0101010500'); // hex version of MA0GCSqGSIb3DQEBAQUA
- $RSAPrivateKey = pack('Ca*a*Ca*a*',
- CRYPT_RSA_ASN1_INTEGER, "\01\00", $rsaOID, 4, $this->_encodeLength(strlen($RSAPrivateKey)), $RSAPrivateKey
+ $RSAPrivateKey = pack(
+ 'Ca*a*Ca*a*',
+ self::ASN1_INTEGER,
+ "\01\00",
+ $rsaOID,
+ 4,
+ $this->_encodeLength(strlen($RSAPrivateKey)),
+ $RSAPrivateKey
);
- $RSAPrivateKey = pack('Ca*a*', CRYPT_RSA_ASN1_SEQUENCE, $this->_encodeLength(strlen($RSAPrivateKey)), $RSAPrivateKey);
+ $RSAPrivateKey = pack('Ca*a*', self::ASN1_SEQUENCE, $this->_encodeLength(strlen($RSAPrivateKey)), $RSAPrivateKey);
if (!empty($this->password) || is_string($this->password)) {
- $salt = crypt_random_string(8);
+ $salt = Random::string(8);
$iterationCount = 2048;
- if (!class_exists('Crypt_DES')) {
- include_once 'Crypt/DES.php';
- }
- $crypto = new Crypt_DES();
+ $crypto = new DES();
$crypto->setPassword($this->password, 'pbkdf1', 'md5', $salt, $iterationCount);
$RSAPrivateKey = $crypto->encrypt($RSAPrivateKey);
- $parameters = pack('Ca*a*Ca*N',
- CRYPT_RSA_ASN1_OCTETSTRING, $this->_encodeLength(strlen($salt)), $salt,
- CRYPT_RSA_ASN1_INTEGER, $this->_encodeLength(4), $iterationCount
+ $parameters = pack(
+ 'Ca*a*Ca*N',
+ self::ASN1_OCTETSTRING,
+ $this->_encodeLength(strlen($salt)),
+ $salt,
+ self::ASN1_INTEGER,
+ $this->_encodeLength(4),
+ $iterationCount
);
$pbeWithMD5AndDES_CBC = "\x2a\x86\x48\x86\xf7\x0d\x01\x05\x03";
- $encryptionAlgorithm = pack('Ca*a*Ca*a*',
- CRYPT_RSA_ASN1_OBJECT, $this->_encodeLength(strlen($pbeWithMD5AndDES_CBC)), $pbeWithMD5AndDES_CBC,
- CRYPT_RSA_ASN1_SEQUENCE, $this->_encodeLength(strlen($parameters)), $parameters
+ $encryptionAlgorithm = pack(
+ 'Ca*a*Ca*a*',
+ self::ASN1_OBJECT,
+ $this->_encodeLength(strlen($pbeWithMD5AndDES_CBC)),
+ $pbeWithMD5AndDES_CBC,
+ self::ASN1_SEQUENCE,
+ $this->_encodeLength(strlen($parameters)),
+ $parameters
);
- $RSAPrivateKey = pack('Ca*a*Ca*a*',
- CRYPT_RSA_ASN1_SEQUENCE, $this->_encodeLength(strlen($encryptionAlgorithm)), $encryptionAlgorithm,
- CRYPT_RSA_ASN1_OCTETSTRING, $this->_encodeLength(strlen($RSAPrivateKey)), $RSAPrivateKey
+ $RSAPrivateKey = pack(
+ 'Ca*a*Ca*a*',
+ self::ASN1_SEQUENCE,
+ $this->_encodeLength(strlen($encryptionAlgorithm)),
+ $encryptionAlgorithm,
+ self::ASN1_OCTETSTRING,
+ $this->_encodeLength(strlen($RSAPrivateKey)),
+ $RSAPrivateKey
);
- $RSAPrivateKey = pack('Ca*a*', CRYPT_RSA_ASN1_SEQUENCE, $this->_encodeLength(strlen($RSAPrivateKey)), $RSAPrivateKey);
+ $RSAPrivateKey = pack('Ca*a*', self::ASN1_SEQUENCE, $this->_encodeLength(strlen($RSAPrivateKey)), $RSAPrivateKey);
$RSAPrivateKey = "-----BEGIN ENCRYPTED PRIVATE KEY-----\r\n" .
chunk_split(base64_encode($RSAPrivateKey), 64) .
}
if (!empty($this->password) || is_string($this->password)) {
- $iv = crypt_random_string(8);
+ $iv = Random::string(8);
$symkey = pack('H*', md5($this->password . $iv)); // symkey is short for symmetric key
$symkey.= substr(pack('H*', md5($symkey . $this->password . $iv)), 0, 8);
- if (!class_exists('Crypt_TripleDES')) {
- include_once 'Crypt/TripleDES.php';
- }
- $des = new Crypt_TripleDES();
+ $des = new TripleDES();
$des->setKey($symkey);
$des->setIV($iv);
$iv = strtoupper(bin2hex($iv));
* Convert a public key to the appropriate format
*
* @access private
- * @see setPublicKeyFormat()
- * @param String $RSAPrivateKey
- * @return String
+ * @see self::setPublicKeyFormat()
+ * @param string $RSAPrivateKey
+ * @return string
*/
function _convertPublicKey($n, $e)
{
- $signed = $this->publicKeyFormat != CRYPT_RSA_PUBLIC_FORMAT_XML;
+ $signed = $this->publicKeyFormat != self::PUBLIC_FORMAT_XML;
$modulus = $n->toBytes($signed);
$publicExponent = $e->toBytes($signed);
switch ($this->publicKeyFormat) {
- case CRYPT_RSA_PUBLIC_FORMAT_RAW:
+ case self::PUBLIC_FORMAT_RAW:
return array('e' => $e->copy(), 'n' => $n->copy());
- case CRYPT_RSA_PUBLIC_FORMAT_XML:
+ case self::PUBLIC_FORMAT_XML:
return "<RSAKeyValue>\r\n" .
' <Modulus>' . base64_encode($modulus) . "</Modulus>\r\n" .
' <Exponent>' . base64_encode($publicExponent) . "</Exponent>\r\n" .
'</RSAKeyValue>';
break;
- case CRYPT_RSA_PUBLIC_FORMAT_OPENSSH:
+ case self::PUBLIC_FORMAT_OPENSSH:
// from <http://tools.ietf.org/html/rfc4253#page-15>:
// string "ssh-rsa"
// mpint e
$RSAPublicKey = 'ssh-rsa ' . base64_encode($RSAPublicKey) . ' ' . $this->comment;
return $RSAPublicKey;
- default: // eg. CRYPT_RSA_PUBLIC_FORMAT_PKCS1_RAW or CRYPT_RSA_PUBLIC_FORMAT_PKCS1
+ default: // eg. self::PUBLIC_FORMAT_PKCS1_RAW or self::PUBLIC_FORMAT_PKCS1
// from <http://tools.ietf.org/html/rfc3447#appendix-A.1.1>:
// RSAPublicKey ::= SEQUENCE {
// modulus INTEGER, -- n
// publicExponent INTEGER -- e
// }
$components = array(
- 'modulus' => pack('Ca*a*', CRYPT_RSA_ASN1_INTEGER, $this->_encodeLength(strlen($modulus)), $modulus),
- 'publicExponent' => pack('Ca*a*', CRYPT_RSA_ASN1_INTEGER, $this->_encodeLength(strlen($publicExponent)), $publicExponent)
+ 'modulus' => pack('Ca*a*', self::ASN1_INTEGER, $this->_encodeLength(strlen($modulus)), $modulus),
+ 'publicExponent' => pack('Ca*a*', self::ASN1_INTEGER, $this->_encodeLength(strlen($publicExponent)), $publicExponent)
);
- $RSAPublicKey = pack('Ca*a*a*',
- CRYPT_RSA_ASN1_SEQUENCE, $this->_encodeLength(strlen($components['modulus']) + strlen($components['publicExponent'])),
- $components['modulus'], $components['publicExponent']
+ $RSAPublicKey = pack(
+ 'Ca*a*a*',
+ self::ASN1_SEQUENCE,
+ $this->_encodeLength(strlen($components['modulus']) + strlen($components['publicExponent'])),
+ $components['modulus'],
+ $components['publicExponent']
);
- if ($this->publicKeyFormat == CRYPT_RSA_PUBLIC_FORMAT_PKCS1_RAW) {
+ if ($this->publicKeyFormat == self::PUBLIC_FORMAT_PKCS1_RAW) {
$RSAPublicKey = "-----BEGIN RSA PUBLIC KEY-----\r\n" .
chunk_split(base64_encode($RSAPublicKey), 64) .
'-----END RSA PUBLIC KEY-----';
$RSAPublicKey = chr(0) . $RSAPublicKey;
$RSAPublicKey = chr(3) . $this->_encodeLength(strlen($RSAPublicKey)) . $RSAPublicKey;
- $RSAPublicKey = pack('Ca*a*',
- CRYPT_RSA_ASN1_SEQUENCE, $this->_encodeLength(strlen($rsaOID . $RSAPublicKey)), $rsaOID . $RSAPublicKey
+ $RSAPublicKey = pack(
+ 'Ca*a*',
+ self::ASN1_SEQUENCE,
+ $this->_encodeLength(strlen($rsaOID . $RSAPublicKey)),
+ $rsaOID . $RSAPublicKey
);
$RSAPublicKey = "-----BEGIN PUBLIC KEY-----\r\n" .
* Break a public or private key down into its constituant components
*
* @access private
- * @see _convertPublicKey()
- * @see _convertPrivateKey()
- * @param String $key
- * @param Integer $type
- * @return Array
+ * @see self::_convertPublicKey()
+ * @see self::_convertPrivateKey()
+ * @param string $key
+ * @param int $type
+ * @return array
*/
function _parseKey($key, $type)
{
- if ($type != CRYPT_RSA_PUBLIC_FORMAT_RAW && !is_string($key)) {
+ if ($type != self::PUBLIC_FORMAT_RAW && !is_string($key)) {
return false;
}
switch ($type) {
- case CRYPT_RSA_PUBLIC_FORMAT_RAW:
+ case self::PUBLIC_FORMAT_RAW:
if (!is_array($key)) {
return false;
}
$components['modulus'] = $key[1]->copy();
}
return isset($components['modulus']) && isset($components['publicExponent']) ? $components : false;
- case CRYPT_RSA_PRIVATE_FORMAT_PKCS1:
- case CRYPT_RSA_PRIVATE_FORMAT_PKCS8:
- case CRYPT_RSA_PUBLIC_FORMAT_PKCS1:
+ case self::PRIVATE_FORMAT_PKCS1:
+ case self::PRIVATE_FORMAT_PKCS8:
+ case self::PUBLIC_FORMAT_PKCS1:
/* Although PKCS#1 proposes a format that public and private keys can use, encrypting them is
"outside the scope" of PKCS#1. PKCS#1 then refers you to PKCS#12 and PKCS#15 if you're wanting to
protect private keys, however, that's not what OpenSSL* does. OpenSSL protects private keys by adding
}
switch ($matches[1]) {
case 'AES-256-CBC':
- if (!class_exists('Crypt_AES')) {
- include_once 'Crypt/AES.php';
- }
- $crypto = new Crypt_AES();
+ $crypto = new AES();
break;
case 'AES-128-CBC':
- if (!class_exists('Crypt_AES')) {
- include_once 'Crypt/AES.php';
- }
$symkey = substr($symkey, 0, 16);
- $crypto = new Crypt_AES();
+ $crypto = new AES();
break;
case 'DES-EDE3-CFB':
- if (!class_exists('Crypt_TripleDES')) {
- include_once 'Crypt/TripleDES.php';
- }
- $crypto = new Crypt_TripleDES(CRYPT_DES_MODE_CFB);
+ $crypto = new TripleDES(Base::MODE_CFB);
break;
case 'DES-EDE3-CBC':
- if (!class_exists('Crypt_TripleDES')) {
- include_once 'Crypt/TripleDES.php';
- }
$symkey = substr($symkey, 0, 24);
- $crypto = new Crypt_TripleDES();
+ $crypto = new TripleDES();
break;
case 'DES-CBC':
- if (!class_exists('Crypt_DES')) {
- include_once 'Crypt/DES.php';
- }
- $crypto = new Crypt_DES();
+ $crypto = new DES();
break;
default:
return false;
$components = array();
- if (ord($this->_string_shift($key)) != CRYPT_RSA_ASN1_SEQUENCE) {
+ if (ord($this->_string_shift($key)) != self::ASN1_SEQUENCE) {
return false;
}
if ($this->_decodeLength($key) != strlen($key)) {
ie. PKCS8 keys*/
- if ($tag == CRYPT_RSA_ASN1_INTEGER && substr($key, 0, 3) == "\x01\x00\x30") {
+ if ($tag == self::ASN1_INTEGER && substr($key, 0, 3) == "\x01\x00\x30") {
$this->_string_shift($key, 3);
- $tag = CRYPT_RSA_ASN1_SEQUENCE;
+ $tag = self::ASN1_SEQUENCE;
}
- if ($tag == CRYPT_RSA_ASN1_SEQUENCE) {
+ if ($tag == self::ASN1_SEQUENCE) {
$temp = $this->_string_shift($key, $this->_decodeLength($key));
- if (ord($this->_string_shift($temp)) != CRYPT_RSA_ASN1_OBJECT) {
+ if (ord($this->_string_shift($temp)) != self::ASN1_OBJECT) {
return false;
}
$length = $this->_decodeLength($temp);
salt OCTET STRING (SIZE(8)),
iterationCount INTEGER }
*/
- if (ord($this->_string_shift($temp)) != CRYPT_RSA_ASN1_SEQUENCE) {
+ if (ord($this->_string_shift($temp)) != self::ASN1_SEQUENCE) {
return false;
}
if ($this->_decodeLength($temp) != strlen($temp)) {
}
$this->_string_shift($temp); // assume it's an octet string
$salt = $this->_string_shift($temp, $this->_decodeLength($temp));
- if (ord($this->_string_shift($temp)) != CRYPT_RSA_ASN1_INTEGER) {
+ if (ord($this->_string_shift($temp)) != self::ASN1_INTEGER) {
return false;
}
$this->_decodeLength($temp);
return false;
}
- if (!class_exists('Crypt_DES')) {
- include_once 'Crypt/DES.php';
- }
- $crypto = new Crypt_DES();
+ $crypto = new DES();
$crypto->setPassword($this->password, 'pbkdf1', 'md5', $salt, $iterationCount);
$key = $crypto->decrypt($key);
if ($key === false) {
return false;
}
- return $this->_parseKey($key, CRYPT_RSA_PRIVATE_FORMAT_PKCS1);
+ return $this->_parseKey($key, self::PRIVATE_FORMAT_PKCS1);
default:
return false;
}
// "The initial octet shall encode, as an unsigned binary integer wtih bit 1 as the least significant bit, the number of
// unused bits in the final subsequent octet. The number shall be in the range zero to seven."
// -- http://www.itu.int/ITU-T/studygroups/com17/languages/X.690-0207.pdf (section 8.6.2.2)
- if ($tag == CRYPT_RSA_ASN1_BITSTRING) {
+ if ($tag == self::ASN1_BITSTRING) {
$this->_string_shift($key);
}
- if (ord($this->_string_shift($key)) != CRYPT_RSA_ASN1_SEQUENCE) {
+ if (ord($this->_string_shift($key)) != self::ASN1_SEQUENCE) {
return false;
}
if ($this->_decodeLength($key) != strlen($key)) {
}
$tag = ord($this->_string_shift($key));
}
- if ($tag != CRYPT_RSA_ASN1_INTEGER) {
+ if ($tag != self::ASN1_INTEGER) {
return false;
}
$length = $this->_decodeLength($key);
$temp = $this->_string_shift($key, $length);
if (strlen($temp) != 1 || ord($temp) > 2) {
- $components['modulus'] = new Math_BigInteger($temp, 256);
- $this->_string_shift($key); // skip over CRYPT_RSA_ASN1_INTEGER
+ $components['modulus'] = new BigInteger($temp, 256);
+ $this->_string_shift($key); // skip over self::ASN1_INTEGER
$length = $this->_decodeLength($key);
- $components[$type == CRYPT_RSA_PUBLIC_FORMAT_PKCS1 ? 'publicExponent' : 'privateExponent'] = new Math_BigInteger($this->_string_shift($key, $length), 256);
+ $components[$type == self::PUBLIC_FORMAT_PKCS1 ? 'publicExponent' : 'privateExponent'] = new BigInteger($this->_string_shift($key, $length), 256);
return $components;
}
- if (ord($this->_string_shift($key)) != CRYPT_RSA_ASN1_INTEGER) {
+ if (ord($this->_string_shift($key)) != self::ASN1_INTEGER) {
return false;
}
$length = $this->_decodeLength($key);
- $components['modulus'] = new Math_BigInteger($this->_string_shift($key, $length), 256);
+ $components['modulus'] = new BigInteger($this->_string_shift($key, $length), 256);
$this->_string_shift($key);
$length = $this->_decodeLength($key);
- $components['publicExponent'] = new Math_BigInteger($this->_string_shift($key, $length), 256);
+ $components['publicExponent'] = new BigInteger($this->_string_shift($key, $length), 256);
$this->_string_shift($key);
$length = $this->_decodeLength($key);
- $components['privateExponent'] = new Math_BigInteger($this->_string_shift($key, $length), 256);
+ $components['privateExponent'] = new BigInteger($this->_string_shift($key, $length), 256);
$this->_string_shift($key);
$length = $this->_decodeLength($key);
- $components['primes'] = array(1 => new Math_BigInteger($this->_string_shift($key, $length), 256));
+ $components['primes'] = array(1 => new BigInteger($this->_string_shift($key, $length), 256));
$this->_string_shift($key);
$length = $this->_decodeLength($key);
- $components['primes'][] = new Math_BigInteger($this->_string_shift($key, $length), 256);
+ $components['primes'][] = new BigInteger($this->_string_shift($key, $length), 256);
$this->_string_shift($key);
$length = $this->_decodeLength($key);
- $components['exponents'] = array(1 => new Math_BigInteger($this->_string_shift($key, $length), 256));
+ $components['exponents'] = array(1 => new BigInteger($this->_string_shift($key, $length), 256));
$this->_string_shift($key);
$length = $this->_decodeLength($key);
- $components['exponents'][] = new Math_BigInteger($this->_string_shift($key, $length), 256);
+ $components['exponents'][] = new BigInteger($this->_string_shift($key, $length), 256);
$this->_string_shift($key);
$length = $this->_decodeLength($key);
- $components['coefficients'] = array(2 => new Math_BigInteger($this->_string_shift($key, $length), 256));
+ $components['coefficients'] = array(2 => new BigInteger($this->_string_shift($key, $length), 256));
if (!empty($key)) {
- if (ord($this->_string_shift($key)) != CRYPT_RSA_ASN1_SEQUENCE) {
+ if (ord($this->_string_shift($key)) != self::ASN1_SEQUENCE) {
return false;
}
$this->_decodeLength($key);
while (!empty($key)) {
- if (ord($this->_string_shift($key)) != CRYPT_RSA_ASN1_SEQUENCE) {
+ if (ord($this->_string_shift($key)) != self::ASN1_SEQUENCE) {
return false;
}
$this->_decodeLength($key);
$key = substr($key, 1);
$length = $this->_decodeLength($key);
- $components['primes'][] = new Math_BigInteger($this->_string_shift($key, $length), 256);
+ $components['primes'][] = new BigInteger($this->_string_shift($key, $length), 256);
$this->_string_shift($key);
$length = $this->_decodeLength($key);
- $components['exponents'][] = new Math_BigInteger($this->_string_shift($key, $length), 256);
+ $components['exponents'][] = new BigInteger($this->_string_shift($key, $length), 256);
$this->_string_shift($key);
$length = $this->_decodeLength($key);
- $components['coefficients'][] = new Math_BigInteger($this->_string_shift($key, $length), 256);
+ $components['coefficients'][] = new BigInteger($this->_string_shift($key, $length), 256);
}
}
return $components;
- case CRYPT_RSA_PUBLIC_FORMAT_OPENSSH:
+ case self::PUBLIC_FORMAT_OPENSSH:
$parts = explode(' ', $key, 3);
$key = isset($parts[1]) ? base64_decode($parts[1]) : false;
return false;
}
extract(unpack('Nlength', $this->_string_shift($key, 4)));
- $publicExponent = new Math_BigInteger($this->_string_shift($key, $length), -256);
+ $publicExponent = new BigInteger($this->_string_shift($key, $length), -256);
if (strlen($key) <= 4) {
return false;
}
extract(unpack('Nlength', $this->_string_shift($key, 4)));
- $modulus = new Math_BigInteger($this->_string_shift($key, $length), -256);
+ $modulus = new BigInteger($this->_string_shift($key, $length), -256);
if ($cleanup && strlen($key)) {
if (strlen($key) <= 4) {
return false;
}
extract(unpack('Nlength', $this->_string_shift($key, 4)));
- $realModulus = new Math_BigInteger($this->_string_shift($key, $length), -256);
+ $realModulus = new BigInteger($this->_string_shift($key, $length), -256);
return strlen($key) ? false : array(
'modulus' => $realModulus,
'publicExponent' => $modulus,
}
// http://www.w3.org/TR/xmldsig-core/#sec-RSAKeyValue
// http://en.wikipedia.org/wiki/XML_Signature
- case CRYPT_RSA_PRIVATE_FORMAT_XML:
- case CRYPT_RSA_PUBLIC_FORMAT_XML:
+ case self::PRIVATE_FORMAT_XML:
+ case self::PUBLIC_FORMAT_XML:
$this->components = array();
$xml = xml_parser_create('UTF-8');
return isset($this->components['modulus']) && isset($this->components['publicExponent']) ? $this->components : false;
// from PuTTY's SSHPUBK.C
- case CRYPT_RSA_PRIVATE_FORMAT_PUTTY:
+ case self::PRIVATE_FORMAT_PUTTY:
$components = array();
$key = preg_split('#\r\n|\r|\n#', $key);
$type = trim(preg_replace('#PuTTY-User-Key-File-2: (.+)#', '$1', $key[0]));
$public = base64_decode(implode('', array_map('trim', array_slice($key, 4, $publicLength))));
$public = substr($public, 11);
extract(unpack('Nlength', $this->_string_shift($public, 4)));
- $components['publicExponent'] = new Math_BigInteger($this->_string_shift($public, $length), -256);
+ $components['publicExponent'] = new BigInteger($this->_string_shift($public, $length), -256);
extract(unpack('Nlength', $this->_string_shift($public, 4)));
- $components['modulus'] = new Math_BigInteger($this->_string_shift($public, $length), -256);
+ $components['modulus'] = new BigInteger($this->_string_shift($public, $length), -256);
$privateLength = trim(preg_replace('#Private-Lines: (\d+)#', '$1', $key[$publicLength + 4]));
$private = base64_decode(implode('', array_map('trim', array_slice($key, $publicLength + 5, $privateLength))));
switch ($encryption) {
case 'aes256-cbc':
- if (!class_exists('Crypt_AES')) {
- include_once 'Crypt/AES.php';
- }
$symkey = '';
$sequence = 0;
while (strlen($symkey) < 32) {
$symkey.= pack('H*', sha1($temp));
}
$symkey = substr($symkey, 0, 32);
- $crypto = new Crypt_AES();
+ $crypto = new AES();
}
if ($encryption != 'none') {
if (strlen($private) < $length) {
return false;
}
- $components['privateExponent'] = new Math_BigInteger($this->_string_shift($private, $length), -256);
+ $components['privateExponent'] = new BigInteger($this->_string_shift($private, $length), -256);
extract(unpack('Nlength', $this->_string_shift($private, 4)));
if (strlen($private) < $length) {
return false;
}
- $components['primes'] = array(1 => new Math_BigInteger($this->_string_shift($private, $length), -256));
+ $components['primes'] = array(1 => new BigInteger($this->_string_shift($private, $length), -256));
extract(unpack('Nlength', $this->_string_shift($private, 4)));
if (strlen($private) < $length) {
return false;
}
- $components['primes'][] = new Math_BigInteger($this->_string_shift($private, $length), -256);
+ $components['primes'][] = new BigInteger($this->_string_shift($private, $length), -256);
$temp = $components['primes'][1]->subtract($this->one);
$components['exponents'] = array(1 => $components['publicExponent']->modInverse($temp));
if (strlen($private) < $length) {
return false;
}
- $components['coefficients'] = array(2 => new Math_BigInteger($this->_string_shift($private, $length), -256));
+ $components['coefficients'] = array(2 => new BigInteger($this->_string_shift($private, $length), -256));
return $components;
}
* More specifically, this returns the size of the modulo in bits.
*
* @access public
- * @return Integer
+ * @return int
*/
function getSize()
{
* Called by xml_set_element_handler()
*
* @access private
- * @param Resource $parser
- * @param String $name
- * @param Array $attribs
+ * @param resource $parser
+ * @param string $name
+ * @param array $attribs
*/
function _start_element_handler($parser, $name, $attribs)
{
* Called by xml_set_element_handler()
*
* @access private
- * @param Resource $parser
- * @param String $name
+ * @param resource $parser
+ * @param string $name
*/
function _stop_element_handler($parser, $name)
{
if (isset($this->current)) {
- $this->current = new Math_BigInteger(base64_decode($this->current), 256);
+ $this->current = new BigInteger(base64_decode($this->current), 256);
unset($this->current);
}
}
* Called by xml_set_character_data_handler()
*
* @access private
- * @param Resource $parser
- * @param String $data
+ * @param resource $parser
+ * @param string $data
*/
function _data_handler($parser, $data)
{
* Returns true on success and false on failure (ie. an incorrect password was provided or the key was malformed)
*
* @access public
- * @param String $key
- * @param Integer $type optional
+ * @param string $key
+ * @param int $type optional
*/
function loadKey($key, $type = false)
{
- if (is_object($key) && strtolower(get_class($key)) == 'crypt_rsa') {
+ if ($key instanceof RSA) {
$this->privateKeyFormat = $key->privateKeyFormat;
$this->publicKeyFormat = $key->publicKeyFormat;
$this->k = $key->k;
$this->comment = $key->comment;
if (is_object($key->hash)) {
- $this->hash = new Crypt_Hash($key->hash->getHash());
+ $this->hash = new Hash($key->hash->getHash());
}
if (is_object($key->mgfHash)) {
- $this->mgfHash = new Crypt_Hash($key->mgfHash->getHash());
+ $this->mgfHash = new Hash($key->mgfHash->getHash());
}
if (is_object($key->modulus)) {
if ($type === false) {
$types = array(
- CRYPT_RSA_PUBLIC_FORMAT_RAW,
- CRYPT_RSA_PRIVATE_FORMAT_PKCS1,
- CRYPT_RSA_PRIVATE_FORMAT_XML,
- CRYPT_RSA_PRIVATE_FORMAT_PUTTY,
- CRYPT_RSA_PUBLIC_FORMAT_OPENSSH
+ self::PUBLIC_FORMAT_RAW,
+ self::PRIVATE_FORMAT_PKCS1,
+ self::PRIVATE_FORMAT_XML,
+ self::PRIVATE_FORMAT_PUTTY,
+ self::PUBLIC_FORMAT_OPENSSH
);
foreach ($types as $type) {
$components = $this->_parseKey($key, $type);
break;
}
}
-
} else {
$components = $this->_parseKey($key, $type);
}
}
switch ($type) {
- case CRYPT_RSA_PUBLIC_FORMAT_OPENSSH:
- case CRYPT_RSA_PUBLIC_FORMAT_RAW:
+ case self::PUBLIC_FORMAT_OPENSSH:
+ case self::PUBLIC_FORMAT_RAW:
$this->setPublicKey();
break;
- case CRYPT_RSA_PRIVATE_FORMAT_PKCS1:
+ case self::PRIVATE_FORMAT_PKCS1:
switch (true) {
case strpos($key, '-BEGIN PUBLIC KEY-') !== false:
case strpos($key, '-BEGIN RSA PUBLIC KEY-') !== false:
* Private keys can be encrypted with a password. To unset the password, pass in the empty string or false.
* Or rather, pass in $password such that empty($password) && !is_string($password) is true.
*
- * @see createKey()
- * @see loadKey()
+ * @see self::createKey()
+ * @see self::loadKey()
* @access public
- * @param String $password
+ * @param string $password
*/
function setPassword($password = false)
{
*
* Returns true on success, false on failure
*
- * @see getPublicKey()
+ * @see self::getPublicKey()
* @access public
- * @param String $key optional
- * @param Integer $type optional
- * @return Boolean
+ * @param string $key optional
+ * @param int $type optional
+ * @return bool
*/
function setPublicKey($key = false, $type = false)
{
if ($type === false) {
$types = array(
- CRYPT_RSA_PUBLIC_FORMAT_RAW,
- CRYPT_RSA_PUBLIC_FORMAT_PKCS1,
- CRYPT_RSA_PUBLIC_FORMAT_XML,
- CRYPT_RSA_PUBLIC_FORMAT_OPENSSH
+ self::PUBLIC_FORMAT_RAW,
+ self::PUBLIC_FORMAT_PKCS1,
+ self::PUBLIC_FORMAT_XML,
+ self::PUBLIC_FORMAT_OPENSSH
);
foreach ($types as $type) {
$components = $this->_parseKey($key, $type);
*
* Returns true on success, false on failure
*
- * @see getPublicKey()
+ * @see self::getPublicKey()
* @access public
- * @param String $key optional
- * @param Integer $type optional
- * @return Boolean
+ * @param string $key optional
+ * @param int $type optional
+ * @return bool
*/
function setPrivateKey($key = false, $type = false)
{
if ($key === false && !empty($this->publicExponent)) {
- unset($this->publicExponent);
+ $this->publicExponent = false;
return true;
}
- $rsa = new Crypt_RSA();
+ $rsa = new RSA();
if (!$rsa->loadKey($key, $type)) {
return false;
}
- unset($rsa->publicExponent);
+ $rsa->publicExponent = false;
// don't overwrite the old key if the new key is invalid
$this->loadKey($rsa);
* or if the public key was set via setPublicKey(). If the currently loaded key is supposed to be the public key this
* function won't return it since this library, for the most part, doesn't distinguish between public and private keys.
*
- * @see getPublicKey()
+ * @see self::getPublicKey()
* @access public
- * @param String $key
- * @param Integer $type optional
+ * @param string $key
+ * @param int $type optional
*/
- function getPublicKey($type = CRYPT_RSA_PUBLIC_FORMAT_PKCS8)
+ function getPublicKey($type = self::PUBLIC_FORMAT_PKCS8)
{
if (empty($this->modulus) || empty($this->publicExponent)) {
return false;
return $temp;
}
+ /**
+ * Returns the public key's fingerprint
+ *
+ * The public key's fingerprint is returned, which is equivalent to running `ssh-keygen -lf rsa.pub`. If there is
+ * no public key currently loaded, false is returned.
+ * Example output (md5): "c1:b1:30:29:d7:b8:de:6c:97:77:10:d7:46:41:63:87" (as specified by RFC 4716)
+ *
+ * @access public
+ * @param string $algorithm The hashing algorithm to be used. Valid options are 'md5' and 'sha256'. False is returned
+ * for invalid values.
+ * @return mixed
+ */
+ function getPublicKeyFingerprint($algorithm = 'md5')
+ {
+ if (empty($this->modulus) || empty($this->publicExponent)) {
+ return false;
+ }
+
+ $modulus = $this->modulus->toBytes(true);
+ $publicExponent = $this->publicExponent->toBytes(true);
+
+ $RSAPublicKey = pack('Na*Na*Na*', strlen('ssh-rsa'), 'ssh-rsa', strlen($publicExponent), $publicExponent, strlen($modulus), $modulus);
+
+ switch ($algorithm) {
+ case 'sha256':
+ $hash = new Hash('sha256');
+ $base = base64_encode($hash->hash($RSAPublicKey));
+ return substr($base, 0, strlen($base) - 1);
+ case 'md5':
+ return substr(chunk_split(md5($RSAPublicKey), 2, ':'), 0, -1);
+ default:
+ return false;
+ }
+ }
+
/**
* Returns the private key
*
* The private key is only returned if the currently loaded key contains the constituent prime numbers.
*
- * @see getPublicKey()
+ * @see self::getPublicKey()
* @access public
- * @param String $key
- * @param Integer $type optional
+ * @param string $key
+ * @param int $type optional
+ * @return mixed
*/
- function getPrivateKey($type = CRYPT_RSA_PUBLIC_FORMAT_PKCS1)
+ function getPrivateKey($type = self::PUBLIC_FORMAT_PKCS1)
{
if (empty($this->primes)) {
return false;
* Returns the private key without the prime number constituants. Structurally identical to a public key that
* hasn't been set as the public key
*
- * @see getPrivateKey()
+ * @see self::getPrivateKey()
* @access private
- * @param String $key
- * @param Integer $type optional
+ * @param string $key
+ * @param int $type optional
*/
- function _getPrivatePublicKey($mode = CRYPT_RSA_PUBLIC_FORMAT_PKCS8)
+ function _getPrivatePublicKey($mode = self::PUBLIC_FORMAT_PKCS8)
{
if (empty($this->modulus) || empty($this->exponent)) {
return false;
* __toString() magic method
*
* @access public
+ * @return string
*/
function __toString()
{
* __clone() magic method
*
* @access public
+ * @return Crypt_RSA
*/
function __clone()
{
- $key = new Crypt_RSA();
+ $key = new RSA();
$key->loadKey($this);
return $key;
}
* Generates the smallest and largest numbers requiring $bits bits
*
* @access private
- * @param Integer $bits
- * @return Array
+ * @param int $bits
+ * @return array
*/
function _generateMinMax($bits)
{
}
return array(
- 'min' => new Math_BigInteger($min, 256),
- 'max' => new Math_BigInteger($max, 256)
+ 'min' => new BigInteger($min, 256),
+ 'max' => new BigInteger($max, 256)
);
}
* {@link http://itu.int/ITU-T/studygroups/com17/languages/X.690-0207.pdf#p=13 X.690 paragraph 8.1.3} for more information.
*
* @access private
- * @param String $string
- * @return Integer
+ * @param string $string
+ * @return int
*/
function _decodeLength(&$string)
{
$length = ord($this->_string_shift($string));
- if ( $length & 0x80 ) { // definite length, long form
+ if ($length & 0x80) { // definite length, long form
$length&= 0x7F;
$temp = $this->_string_shift($string, $length);
list(, $length) = unpack('N', substr(str_pad($temp, 4, chr(0), STR_PAD_LEFT), -4));
* {@link http://itu.int/ITU-T/studygroups/com17/languages/X.690-0207.pdf#p=13 X.690 paragraph 8.1.3} for more information.
*
* @access private
- * @param Integer $length
- * @return String
+ * @param int $length
+ * @return string
*/
function _encodeLength($length)
{
*
* Inspired by array_shift
*
- * @param String $string
- * @param optional Integer $index
- * @return String
+ * @param string $string
+ * @param int $index
+ * @return string
* @access private
*/
function _string_shift(&$string, $index = 1)
/**
* Determines the private key format
*
- * @see createKey()
+ * @see self::createKey()
* @access public
- * @param Integer $format
+ * @param int $format
*/
function setPrivateKeyFormat($format)
{
/**
* Determines the public key format
*
- * @see createKey()
+ * @see self::createKey()
* @access public
- * @param Integer $format
+ * @param int $format
*/
function setPublicKeyFormat($format)
{
/**
* Determines which hashing function should be used
*
- * Used with signature production / verification and (if the encryption mode is CRYPT_RSA_ENCRYPTION_OAEP) encryption and
+ * Used with signature production / verification and (if the encryption mode is self::ENCRYPTION_OAEP) encryption and
* decryption. If $hash isn't supported, sha1 is used.
*
* @access public
- * @param String $hash
+ * @param string $hash
*/
function setHash($hash)
{
- // Crypt_Hash supports algorithms that PKCS#1 doesn't support. md5-96 and sha1-96, for example.
+ // \phpseclib\Crypt\Hash supports algorithms that PKCS#1 doesn't support. md5-96 and sha1-96, for example.
switch ($hash) {
case 'md2':
case 'md5':
case 'sha256':
case 'sha384':
case 'sha512':
- $this->hash = new Crypt_Hash($hash);
+ $this->hash = new Hash($hash);
$this->hashName = $hash;
break;
default:
- $this->hash = new Crypt_Hash('sha1');
+ $this->hash = new Hash('sha1');
$this->hashName = 'sha1';
}
$this->hLen = $this->hash->getLength();
/**
* Determines which hashing function should be used for the mask generation function
*
- * The mask generation function is used by CRYPT_RSA_ENCRYPTION_OAEP and CRYPT_RSA_SIGNATURE_PSS and although it's
+ * The mask generation function is used by self::ENCRYPTION_OAEP and self::SIGNATURE_PSS and although it's
* best if Hash and MGFHash are set to the same thing this is not a requirement.
*
* @access public
- * @param String $hash
+ * @param string $hash
*/
function setMGFHash($hash)
{
- // Crypt_Hash supports algorithms that PKCS#1 doesn't support. md5-96 and sha1-96, for example.
+ // \phpseclib\Crypt\Hash supports algorithms that PKCS#1 doesn't support. md5-96 and sha1-96, for example.
switch ($hash) {
case 'md2':
case 'md5':
case 'sha256':
case 'sha384':
case 'sha512':
- $this->mgfHash = new Crypt_Hash($hash);
+ $this->mgfHash = new Hash($hash);
break;
default:
- $this->mgfHash = new Crypt_Hash('sha1');
+ $this->mgfHash = new Hash('sha1');
}
$this->mgfHLen = $this->mgfHash->getLength();
}
* of the hash function Hash) and 0.
*
* @access public
- * @param Integer $format
+ * @param int $format
*/
function setSaltLength($sLen)
{
* See {@link http://tools.ietf.org/html/rfc3447#section-4.1 RFC3447#section-4.1}.
*
* @access private
- * @param Math_BigInteger $x
- * @param Integer $xLen
- * @return String
+ * @param \phpseclib\Math\BigInteger $x
+ * @param int $xLen
+ * @return string
*/
function _i2osp($x, $xLen)
{
* See {@link http://tools.ietf.org/html/rfc3447#section-4.2 RFC3447#section-4.2}.
*
* @access private
- * @param String $x
- * @return Math_BigInteger
+ * @param string $x
+ * @return \phpseclib\Math\BigInteger
*/
function _os2ip($x)
{
- return new Math_BigInteger($x, 256);
+ return new BigInteger($x, 256);
}
/**
* See {@link http://tools.ietf.org/html/rfc3447#section-5.1.1 RFC3447#section-5.1.2}.
*
* @access private
- * @param Math_BigInteger $x
- * @return Math_BigInteger
+ * @param \phpseclib\Math\BigInteger $x
+ * @return \phpseclib\Math\BigInteger
*/
function _exponentiate($x)
{
- if (empty($this->primes) || empty($this->coefficients) || empty($this->exponents)) {
- return $x->modPow($this->exponent, $this->modulus);
+ switch (true) {
+ case empty($this->primes):
+ case $this->primes[1]->equals($this->zero):
+ case empty($this->coefficients):
+ case $this->coefficients[2]->equals($this->zero):
+ case empty($this->exponents):
+ case $this->exponents[1]->equals($this->zero):
+ return $x->modPow($this->exponent, $this->modulus);
}
$num_primes = count($this->primes);
}
}
- $one = new Math_BigInteger(1);
+ $one = new BigInteger(1);
$r = $one->random($one, $smallest->subtract($one));
* Returns $x->modPow($this->exponents[$i], $this->primes[$i])
*
* @access private
- * @param Math_BigInteger $x
- * @param Math_BigInteger $r
- * @param Integer $i
- * @return Math_BigInteger
+ * @param \phpseclib\Math\BigInteger $x
+ * @param \phpseclib\Math\BigInteger $r
+ * @param int $i
+ * @return \phpseclib\Math\BigInteger
*/
function _blind($x, $r, $i)
{
* Thanks for the heads up singpolyma!
*
* @access private
- * @param String $x
- * @param String $y
- * @return Boolean
+ * @param string $x
+ * @param string $y
+ * @return bool
*/
function _equals($x, $y)
{
* See {@link http://tools.ietf.org/html/rfc3447#section-5.1.1 RFC3447#section-5.1.1}.
*
* @access private
- * @param Math_BigInteger $m
- * @return Math_BigInteger
+ * @param \phpseclib\Math\BigInteger $m
+ * @return \phpseclib\Math\BigInteger
*/
function _rsaep($m)
{
* See {@link http://tools.ietf.org/html/rfc3447#section-5.1.2 RFC3447#section-5.1.2}.
*
* @access private
- * @param Math_BigInteger $c
- * @return Math_BigInteger
+ * @param \phpseclib\Math\BigInteger $c
+ * @return \phpseclib\Math\BigInteger
*/
function _rsadp($c)
{
* See {@link http://tools.ietf.org/html/rfc3447#section-5.2.1 RFC3447#section-5.2.1}.
*
* @access private
- * @param Math_BigInteger $m
- * @return Math_BigInteger
+ * @param \phpseclib\Math\BigInteger $m
+ * @return \phpseclib\Math\BigInteger
*/
function _rsasp1($m)
{
* See {@link http://tools.ietf.org/html/rfc3447#section-5.2.2 RFC3447#section-5.2.2}.
*
* @access private
- * @param Math_BigInteger $s
- * @return Math_BigInteger
+ * @param \phpseclib\Math\BigInteger $s
+ * @return \phpseclib\Math\BigInteger
*/
function _rsavp1($s)
{
* See {@link http://tools.ietf.org/html/rfc3447#appendix-B.2.1 RFC3447#appendix-B.2.1}.
*
* @access private
- * @param String $mgfSeed
- * @param Integer $mgfLen
- * @return String
+ * @param string $mgfSeed
+ * @param int $mgfLen
+ * @return string
*/
function _mgf1($mgfSeed, $maskLen)
{
* {http://en.wikipedia.org/wiki/Optimal_Asymmetric_Encryption_Padding OAES}.
*
* @access private
- * @param String $m
- * @param String $l
- * @return String
+ * @param string $m
+ * @param string $l
+ * @return string
*/
function _rsaes_oaep_encrypt($m, $l = '')
{
$lHash = $this->hash->hash($l);
$ps = str_repeat(chr(0), $this->k - $mLen - 2 * $this->hLen - 2);
$db = $lHash . $ps . chr(1) . $m;
- $seed = crypt_random_string($this->hLen);
+ $seed = Random::string($this->hLen);
$dbMask = $this->_mgf1($seed, $this->k - $this->hLen - 1);
$maskedDB = $db ^ $dbMask;
$seedMask = $this->_mgf1($maskedDB, $this->hLen);
* this document.
*
* @access private
- * @param String $c
- * @param String $l
- * @return String
+ * @param string $c
+ * @param string $l
+ * @return string
*/
function _rsaes_oaep_decrypt($c, $l = '')
{
return substr($m, 1);
}
+ /**
+ * Raw Encryption / Decryption
+ *
+ * Doesn't use padding and is not recommended.
+ *
+ * @access private
+ * @param string $m
+ * @return string
+ */
+ function _raw_encrypt($m)
+ {
+ $temp = $this->_os2ip($m);
+ $temp = $this->_rsaep($temp);
+ return $this->_i2osp($temp, $this->k);
+ }
+
/**
* RSAES-PKCS1-V1_5-ENCRYPT
*
* See {@link http://tools.ietf.org/html/rfc3447#section-7.2.1 RFC3447#section-7.2.1}.
*
* @access private
- * @param String $m
- * @return String
+ * @param string $m
+ * @return string
*/
function _rsaes_pkcs1_v1_5_encrypt($m)
{
$psLen = $this->k - $mLen - 3;
$ps = '';
while (strlen($ps) != $psLen) {
- $temp = crypt_random_string($psLen - strlen($ps));
+ $temp = Random::string($psLen - strlen($ps));
$temp = str_replace("\x00", '', $temp);
$ps.= $temp;
}
* to be 2 regardless of which key is used. For compatibility purposes, we'll just check to make sure the
* second byte is 2 or less. If it is, we'll accept the decrypted string as valid.
*
- * As a consequence of this, a private key encrypted ciphertext produced with Crypt_RSA may not decrypt
+ * As a consequence of this, a private key encrypted ciphertext produced with \phpseclib\Crypt\RSA may not decrypt
* with a strictly PKCS#1 v1.5 compliant RSA implementation. Public key encrypted ciphertext's should but
* not private key encrypted ciphertext's.
*
* @access private
- * @param String $c
- * @return String
+ * @param string $c
+ * @return string
*/
function _rsaes_pkcs1_v1_5_decrypt($c)
{
* See {@link http://tools.ietf.org/html/rfc3447#section-9.1.1 RFC3447#section-9.1.1}.
*
* @access private
- * @param String $m
- * @param Integer $emBits
+ * @param string $m
+ * @param int $emBits
*/
function _emsa_pss_encode($m, $emBits)
{
// be output.
$emLen = ($emBits + 1) >> 3; // ie. ceil($emBits / 8)
- $sLen = $this->sLen == false ? $this->hLen : $this->sLen;
+ $sLen = $this->sLen !== null ? $this->sLen : $this->hLen;
$mHash = $this->hash->hash($m);
if ($emLen < $this->hLen + $sLen + 2) {
return false;
}
- $salt = crypt_random_string($sLen);
+ $salt = Random::string($sLen);
$m2 = "\0\0\0\0\0\0\0\0" . $mHash . $salt;
$h = $this->hash->hash($m2);
$ps = str_repeat(chr(0), $emLen - $sLen - $this->hLen - 2);
* See {@link http://tools.ietf.org/html/rfc3447#section-9.1.2 RFC3447#section-9.1.2}.
*
* @access private
- * @param String $m
- * @param String $em
- * @param Integer $emBits
- * @return String
+ * @param string $m
+ * @param string $em
+ * @param int $emBits
+ * @return string
*/
function _emsa_pss_verify($m, $em, $emBits)
{
// be output.
$emLen = ($emBits + 1) >> 3; // ie. ceil($emBits / 8);
- $sLen = $this->sLen == false ? $this->hLen : $this->sLen;
+ $sLen = $this->sLen !== null ? $this->sLen : $this->hLen;
$mHash = $this->hash->hash($m);
if ($emLen < $this->hLen + $sLen + 2) {
* See {@link http://tools.ietf.org/html/rfc3447#section-8.1.1 RFC3447#section-8.1.1}.
*
* @access private
- * @param String $m
- * @return String
+ * @param string $m
+ * @return string
*/
function _rsassa_pss_sign($m)
{
* See {@link http://tools.ietf.org/html/rfc3447#section-8.1.2 RFC3447#section-8.1.2}.
*
* @access private
- * @param String $m
- * @param String $s
- * @return String
+ * @param string $m
+ * @param string $s
+ * @return string
*/
function _rsassa_pss_verify($m, $s)
{
* See {@link http://tools.ietf.org/html/rfc3447#section-9.2 RFC3447#section-9.2}.
*
* @access private
- * @param String $m
- * @param Integer $emLen
- * @return String
+ * @param string $m
+ * @param int $emLen
+ * @return string
*/
function _emsa_pkcs1_v1_5_encode($m, $emLen)
{
* See {@link http://tools.ietf.org/html/rfc3447#section-8.2.1 RFC3447#section-8.2.1}.
*
* @access private
- * @param String $m
- * @return String
+ * @param string $m
+ * @return string
*/
function _rsassa_pkcs1_v1_5_sign($m)
{
* See {@link http://tools.ietf.org/html/rfc3447#section-8.2.2 RFC3447#section-8.2.2}.
*
* @access private
- * @param String $m
- * @return String
+ * @param string $m
+ * @return string
*/
function _rsassa_pkcs1_v1_5_verify($m, $s)
{
/**
* Set Encryption Mode
*
- * Valid values include CRYPT_RSA_ENCRYPTION_OAEP and CRYPT_RSA_ENCRYPTION_PKCS1.
+ * Valid values include self::ENCRYPTION_OAEP and self::ENCRYPTION_PKCS1.
*
* @access public
- * @param Integer $mode
+ * @param int $mode
*/
function setEncryptionMode($mode)
{
/**
* Set Signature Mode
*
- * Valid values include CRYPT_RSA_SIGNATURE_PSS and CRYPT_RSA_SIGNATURE_PKCS1
+ * Valid values include self::SIGNATURE_PSS and self::SIGNATURE_PKCS1
*
* @access public
- * @param Integer $mode
+ * @param int $mode
*/
function setSignatureMode($mode)
{
* Set public key comment.
*
* @access public
- * @param String $comment
+ * @param string $comment
*/
function setComment($comment)
{
* Get public key comment.
*
* @access public
- * @return String
+ * @return string
*/
function getComment()
{
/**
* Encryption
*
- * Both CRYPT_RSA_ENCRYPTION_OAEP and CRYPT_RSA_ENCRYPTION_PKCS1 both place limits on how long $plaintext can be.
+ * Both self::ENCRYPTION_OAEP and self::ENCRYPTION_PKCS1 both place limits on how long $plaintext can be.
* If $plaintext exceeds those limits it will be broken up so that it does and the resultant ciphertext's will
* be concatenated together.
*
- * @see decrypt()
+ * @see self::decrypt()
* @access public
- * @param String $plaintext
- * @return String
+ * @param string $plaintext
+ * @return string
*/
function encrypt($plaintext)
{
switch ($this->encryptionMode) {
- case CRYPT_RSA_ENCRYPTION_PKCS1:
+ case self::ENCRYPTION_NONE:
+ $plaintext = str_split($plaintext, $this->k);
+ $ciphertext = '';
+ foreach ($plaintext as $m) {
+ $ciphertext.= $this->_raw_encrypt($m);
+ }
+ return $ciphertext;
+ case self::ENCRYPTION_PKCS1:
$length = $this->k - 11;
if ($length <= 0) {
return false;
$ciphertext.= $this->_rsaes_pkcs1_v1_5_encrypt($m);
}
return $ciphertext;
- //case CRYPT_RSA_ENCRYPTION_OAEP:
+ //case self::ENCRYPTION_OAEP:
default:
$length = $this->k - 2 * $this->hLen - 2;
if ($length <= 0) {
/**
* Decryption
*
- * @see encrypt()
+ * @see self::encrypt()
* @access public
- * @param String $plaintext
- * @return String
+ * @param string $plaintext
+ * @return string
*/
function decrypt($ciphertext)
{
$plaintext = '';
switch ($this->encryptionMode) {
- case CRYPT_RSA_ENCRYPTION_PKCS1:
+ case self::ENCRYPTION_NONE:
+ $decrypt = '_raw_encrypt';
+ break;
+ case self::ENCRYPTION_PKCS1:
$decrypt = '_rsaes_pkcs1_v1_5_decrypt';
break;
- //case CRYPT_RSA_ENCRYPTION_OAEP:
+ //case self::ENCRYPTION_OAEP:
default:
$decrypt = '_rsaes_oaep_decrypt';
}
/**
* Create a signature
*
- * @see verify()
+ * @see self::verify()
* @access public
- * @param String $message
- * @return String
+ * @param string $message
+ * @return string
*/
function sign($message)
{
}
switch ($this->signatureMode) {
- case CRYPT_RSA_SIGNATURE_PKCS1:
+ case self::SIGNATURE_PKCS1:
return $this->_rsassa_pkcs1_v1_5_sign($message);
- //case CRYPT_RSA_SIGNATURE_PSS:
+ //case self::SIGNATURE_PSS:
default:
return $this->_rsassa_pss_sign($message);
}
/**
* Verifies a signature
*
- * @see sign()
+ * @see self::sign()
* @access public
- * @param String $message
- * @param String $signature
- * @return Boolean
+ * @param string $message
+ * @param string $signature
+ * @return bool
*/
function verify($message, $signature)
{
}
switch ($this->signatureMode) {
- case CRYPT_RSA_SIGNATURE_PKCS1:
+ case self::SIGNATURE_PKCS1:
return $this->_rsassa_pkcs1_v1_5_verify($message, $signature);
- //case CRYPT_RSA_SIGNATURE_PSS:
+ //case self::SIGNATURE_PSS:
default:
return $this->_rsassa_pss_verify($message, $signature);
}
* Extract raw BER from Base64 encoding
*
* @access private
- * @param String $str
- * @return String
+ * @param string $str
+ * @return string
*/
function _extractBER($str)
{
* subject=/O=organization/OU=org unit/CN=common name
* issuer=/O=organization/CN=common name
*/
- $temp = preg_replace('#.*?^-+[^-]+-+#ms', '', $str, 1);
+ $temp = preg_replace('#.*?^-+[^-]+-+[\r\n ]*$#ms', '', $str, 1);
// remove the -----BEGIN CERTIFICATE----- and -----END CERTIFICATE----- stuff
$temp = preg_replace('#-+[^-]+-+#', '', $temp);
// remove new lines