2 /* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
5 * Pure-PHP PKCS#1 (v2.1) compliant implementation of RSA.
9 * Here's an example of how to encrypt and decrypt text with this library:
12 * include('Crypt/RSA.php');
14 * $rsa = new Crypt_RSA();
15 * extract($rsa->createKey());
17 * $plaintext = 'terrafrost';
19 * $rsa->loadKey($privatekey);
20 * $ciphertext = $rsa->encrypt($plaintext);
22 * $rsa->loadKey($publickey);
23 * echo $rsa->decrypt($ciphertext);
27 * Here's an example of how to create signatures and verify signatures with this library:
30 * include('Crypt/RSA.php');
32 * $rsa = new Crypt_RSA();
33 * extract($rsa->createKey());
35 * $plaintext = 'terrafrost';
37 * $rsa->loadKey($privatekey);
38 * $signature = $rsa->sign($plaintext);
40 * $rsa->loadKey($publickey);
41 * echo $rsa->verify($plaintext, $signature) ? 'verified' : 'unverified';
45 * LICENSE: This library is free software; you can redistribute it and/or
46 * modify it under the terms of the GNU Lesser General Public
47 * License as published by the Free Software Foundation; either
48 * version 2.1 of the License, or (at your option) any later version.
50 * This library is distributed in the hope that it will be useful,
51 * but WITHOUT ANY WARRANTY; without even the implied warranty of
52 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
53 * Lesser General Public License for more details.
55 * You should have received a copy of the GNU Lesser General Public
56 * License along with this library; if not, write to the Free Software
57 * Foundation, Inc., 59 Temple Place, Suite 330, Boston,
62 * @author Jim Wigginton <terrafrost@php.net>
63 * @copyright MMIX Jim Wigginton
64 * @license http://www.gnu.org/licenses/lgpl.txt
65 * @version $Id: RSA.php,v 1.14 2010/03/01 17:28:19 terrafrost Exp $
66 * @link http://phpseclib.sourceforge.net
70 * Include Math_BigInteger
72 require_once('Math/BigInteger.php');
75 * Include Crypt_Random
77 require_once('Crypt/Random.php');
82 require_once('Crypt/Hash.php');
86 * @see Crypt_RSA::encrypt()
87 * @see Crypt_RSA::decrypt()
90 * Use {@link http://en.wikipedia.org/wiki/Optimal_Asymmetric_Encryption_Padding Optimal Asymmetric Encryption Padding}
91 * (OAEP) for encryption / decryption.
93 * Uses sha1 by default.
95 * @see Crypt_RSA::setHash()
96 * @see Crypt_RSA::setMGFHash()
98 define('CRYPT_RSA_ENCRYPTION_OAEP', 1);
100 * Use PKCS#1 padding.
102 * Although CRYPT_RSA_ENCRYPTION_OAEP offers more security, including PKCS#1 padding is necessary for purposes of backwards
103 * compatability with protocols (like SSH-1) written before OAEP's introduction.
105 define('CRYPT_RSA_ENCRYPTION_PKCS1', 2);
110 * @see Crypt_RSA::sign()
111 * @see Crypt_RSA::verify()
112 * @see Crypt_RSA::setHash()
115 * Use the Probabilistic Signature Scheme for signing
117 * Uses sha1 by default.
119 * @see Crypt_RSA::setSaltLength()
120 * @see Crypt_RSA::setMGFHash()
122 define('CRYPT_RSA_SIGNATURE_PSS', 1);
124 * Use the PKCS#1 scheme by default.
126 * Although CRYPT_RSA_SIGNATURE_PSS offers more security, including PKCS#1 signing is necessary for purposes of backwards
127 * compatability with protocols (like SSH-2) written before PSS's introduction.
129 define('CRYPT_RSA_SIGNATURE_PKCS1', 2);
134 * @see Crypt_RSA::createKey()
139 define('CRYPT_RSA_ASN1_INTEGER', 2);
141 * ASN1 Sequence (with the constucted bit set)
143 define('CRYPT_RSA_ASN1_SEQUENCE', 48);
148 * @see Crypt_RSA::Crypt_RSA()
151 * To use the pure-PHP implementation
153 define('CRYPT_RSA_MODE_INTERNAL', 1);
155 * To use the OpenSSL library
157 * (if enabled; otherwise, the internal implementation will be used)
159 define('CRYPT_RSA_MODE_OPENSSL', 2);
164 * @see Crypt_RSA::createKey()
165 * @see Crypt_RSA::setPrivateKeyFormat()
168 * PKCS#1 formatted private key
172 define('CRYPT_RSA_PRIVATE_FORMAT_PKCS1', 0);
177 * @see Crypt_RSA::createKey()
178 * @see Crypt_RSA::setPublicKeyFormat()
183 * An array containing two Math_BigInteger objects.
185 * The exponent can be indexed with any of the following:
187 * 0, e, exponent, publicExponent
189 * The modulus can be indexed with any of the following:
191 * 1, n, modulo, modulus
193 define('CRYPT_RSA_PUBLIC_FORMAT_RAW', 1);
195 * PKCS#1 formatted public key
197 define('CRYPT_RSA_PUBLIC_FORMAT_PKCS1', 2);
199 * OpenSSH formatted public key
201 * Place in $HOME/.ssh/authorized_keys
203 define('CRYPT_RSA_PUBLIC_FORMAT_OPENSSH', 3);
207 * Pure-PHP PKCS#1 compliant implementation of RSA.
209 * @author Jim Wigginton <terrafrost@php.net>
237 var $privateKeyFormat = CRYPT_RSA_PRIVATE_FORMAT_PKCS1;
245 var $publicKeyFormat = CRYPT_RSA_PUBLIC_FORMAT_PKCS1;
250 * @var Math_BigInteger
258 * @var Math_BigInteger
264 * Exponent (ie. e or d)
266 * @var Math_BigInteger
272 * Primes for Chinese Remainder Theorem (ie. p and q)
280 * Exponents for Chinese Remainder Theorem (ie. dP and dQ)
288 * Coefficients for Chinese Remainder Theorem (ie. qInv)
312 * Length of hash function output
328 * Hash function for the Mask Generation Function
336 * Length of MGF hash function output
349 var $encryptionMode = CRYPT_RSA_ENCRYPTION_OAEP;
357 var $signatureMode = CRYPT_RSA_SIGNATURE_PSS;
365 var $publicExponent = false;
378 * If you want to make use of the openssl extension, you'll need to set the mode manually, yourself. The reason
379 * Crypt_RSA doesn't do it is because OpenSSL doesn't fail gracefully. openssl_pkey_new(), in particular, requires
380 * openssl.cnf be present somewhere and, unfortunately, the only real way to find out is too late.
387 if ( !defined('CRYPT_RSA_MODE') ) {
389 //case extension_loaded('openssl') && version_compare(PHP_VERSION, '4.2.0', '>='):
390 // define('CRYPT_RSA_MODE', CRYPT_RSA_MODE_OPENSSL);
393 define('CRYPT_RSA_MODE', CRYPT_RSA_MODE_INTERNAL);
397 $this->zero = new Math_BigInteger();
398 $this->one = new Math_BigInteger(1);
400 $this->hash = new Crypt_Hash('sha1');
401 $this->hLen = $this->hash->getLength();
402 $this->hashName = 'sha1';
403 $this->mgfHash = new Crypt_Hash('sha1');
404 $this->mgfHLen = $this->mgfHash->getLength();
408 * Create public / private key pair
410 * Returns an array with the following three elements:
411 * - 'privatekey': The private key.
412 * - 'publickey': The public key.
413 * - 'partialkey': A partially computed key (if the execution time exceeded $timeout).
414 * Will need to be passed back to Crypt_RSA::createKey() as the third parameter for further processing.
417 * @param optional Integer $bits
418 * @param optional Integer $timeout
419 * @param optional Math_BigInteger $p
421 function createKey($bits = 1024, $timeout = false, $partial = array())
423 if ( CRYPT_RSA_MODE == CRYPT_RSA_MODE_OPENSSL ) {
424 $rsa = openssl_pkey_new(array('private_key_bits' => $bits));
425 openssl_pkey_export($rsa, $privatekey);
426 $publickey = openssl_pkey_get_details($rsa);
427 $publickey = $publickey['key'];
429 if ($this->privateKeyFormat != CRYPT_RSA_PRIVATE_FORMAT_PKCS1) {
430 $privatekey = call_user_func_array(array($this, '_convertPrivateKey'), array_values($this->_parseKey($privatekey, CRYPT_RSA_PRIVATE_FORMAT_PKCS1)));
431 $publickey = call_user_func_array(array($this, '_convertPublicKey'), array_values($this->_parseKey($publickey, CRYPT_RSA_PUBLIC_FORMAT_PKCS1)));
435 'privatekey' => $privatekey,
436 'publickey' => $publickey,
437 'partialkey' => false
443 if (!defined('CRYPT_RSA_EXPONENT')) {
444 // http://en.wikipedia.org/wiki/65537_%28number%29
445 define('CRYPT_RSA_EXPONENT', '65537');
447 if (!defined('CRYPT_RSA_COMMENT')) {
448 define('CRYPT_RSA_COMMENT', 'phpseclib-generated-key');
450 // per <http://cseweb.ucsd.edu/~hovav/dist/survey.pdf#page=5>, this number ought not result in primes smaller
452 if (!defined('CRYPT_RSA_SMALLEST_PRIME')) {
453 define('CRYPT_RSA_SMALLEST_PRIME', 4096);
456 $e = new Math_BigInteger(CRYPT_RSA_EXPONENT);
459 extract($this->_generateMinMax($bits));
462 if ($temp > CRYPT_RSA_SMALLEST_PRIME) {
463 $num_primes = floor($bits / CRYPT_RSA_SMALLEST_PRIME);
464 $temp = CRYPT_RSA_SMALLEST_PRIME;
468 extract($this->_generateMinMax($temp + $bits % $temp));
470 extract($this->_generateMinMax($temp));
472 $generator = new Math_BigInteger();
473 $generator->setRandomGenerator('crypt_random');
475 $n = $this->one->copy();
476 if (!empty($partial)) {
477 extract(unserialize($partial));
479 $exponents = $coefficients = $primes = array();
481 'top' => $this->one->copy(),
487 $i0 = count($primes) + 1;
490 for ($i = $i0; $i <= $num_primes; $i++) {
491 if ($timeout !== false) {
492 $timeout-= time() - $start;
495 return serialize(array(
498 'partialkey' => array(
500 'coefficients' => $coefficients,
502 'exponents' => $exponents
508 if ($i == $num_primes) {
509 list($min, $temp) = $absoluteMin->divide($n);
510 if (!$temp->equals($this->zero)) {
511 $min = $min->add($this->one); // ie. ceil()
513 $primes[$i] = $generator->randomPrime($min, $finalMax, $timeout);
515 $primes[$i] = $generator->randomPrime($min, $max, $timeout);
518 if ($primes[$i] === false) { // if we've reached the timeout
522 'partialkey' => empty($primes) ? '' : serialize(array(
523 'primes' => array_slice($primes, 0, $i - 1),
524 'coefficients' => $coefficients,
526 'exponents' => $exponents
531 // the first coefficient is calculated differently from the rest
532 // ie. instead of being $primes[1]->modInverse($primes[2]), it's $primes[2]->modInverse($primes[1])
534 $coefficients[$i] = $n->modInverse($primes[$i]);
537 $n = $n->multiply($primes[$i]);
539 $temp = $primes[$i]->subtract($this->one);
541 // textbook RSA implementations use Euler's totient function instead of the least common multiple.
542 // see http://en.wikipedia.org/wiki/Euler%27s_totient_function
543 $lcm['top'] = $lcm['top']->multiply($temp);
544 $lcm['bottom'] = $lcm['bottom'] === false ? $temp : $lcm['bottom']->gcd($temp);
546 $exponents[$i] = $e->modInverse($temp);
549 list($lcm) = $lcm['top']->divide($lcm['bottom']);
550 $gcd = $lcm->gcd($e);
552 } while (!$gcd->equals($this->one));
554 $d = $e->modInverse($lcm);
556 $coefficients[2] = $primes[2]->modInverse($primes[1]);
558 // from <http://tools.ietf.org/html/rfc3447#appendix-A.1.2>:
559 // RSAPrivateKey ::= SEQUENCE {
561 // modulus INTEGER, -- n
562 // publicExponent INTEGER, -- e
563 // privateExponent INTEGER, -- d
564 // prime1 INTEGER, -- p
565 // prime2 INTEGER, -- q
566 // exponent1 INTEGER, -- d mod (p-1)
567 // exponent2 INTEGER, -- d mod (q-1)
568 // coefficient INTEGER, -- (inverse of q) mod p
569 // otherPrimeInfos OtherPrimeInfos OPTIONAL
573 'privatekey' => $this->_convertPrivateKey($n, $e, $d, $primes, $exponents, $coefficients),
574 'publickey' => $this->_convertPublicKey($n, $e),
575 'partialkey' => false
580 * Convert a private key to the appropriate format.
583 * @see setPrivateKeyFormat()
584 * @param String $RSAPrivateKey
587 function _convertPrivateKey($n, $e, $d, $primes, $exponents, $coefficients)
589 $num_primes = count($primes);
591 'version' => $num_primes == 2 ? chr(0) : chr(1), // two-prime vs. multi
592 'modulus' => $n->toBytes(true),
593 'publicExponent' => $e->toBytes(true),
594 'privateExponent' => $d->toBytes(true),
595 'prime1' => $primes[1]->toBytes(true),
596 'prime2' => $primes[2]->toBytes(true),
597 'exponent1' => $exponents[1]->toBytes(true),
598 'exponent2' => $exponents[2]->toBytes(true),
599 'coefficient' => $coefficients[2]->toBytes(true)
602 // if the format in question does not support multi-prime rsa and multi-prime rsa was used,
603 // call _convertPublicKey() instead.
604 switch ($this->privateKeyFormat) {
605 default: // eg. CRYPT_RSA_PRIVATE_FORMAT_PKCS1
606 $components = array();
607 foreach ($raw as $name => $value) {
608 $components[$name] = pack('Ca*a*', CRYPT_RSA_ASN1_INTEGER, $this->_encodeLength(strlen($value)), $value);
611 $RSAPrivateKey = implode('', $components);
613 if ($num_primes > 2) {
614 $OtherPrimeInfos = '';
615 for ($i = 3; $i <= $num_primes; $i++) {
616 // OtherPrimeInfos ::= SEQUENCE SIZE(1..MAX) OF OtherPrimeInfo
618 // OtherPrimeInfo ::= SEQUENCE {
619 // prime INTEGER, -- ri
620 // exponent INTEGER, -- di
621 // coefficient INTEGER -- ti
623 $OtherPrimeInfo = pack('Ca*a*', CRYPT_RSA_ASN1_INTEGER, $this->_encodeLength(strlen($primes[$i]->toBytes(true))), $primes[$i]->toBytes(true));
624 $OtherPrimeInfo.= pack('Ca*a*', CRYPT_RSA_ASN1_INTEGER, $this->_encodeLength(strlen($exponents[$i]->toBytes(true))), $exponents[$i]->toBytes(true));
625 $OtherPrimeInfo.= pack('Ca*a*', CRYPT_RSA_ASN1_INTEGER, $this->_encodeLength(strlen($coefficients[$i]->toBytes(true))), $coefficients[$i]->toBytes(true));
626 $OtherPrimeInfos.= pack('Ca*a*', CRYPT_RSA_ASN1_SEQUENCE, $this->_encodeLength(strlen($OtherPrimeInfo)), $OtherPrimeInfo);
628 $RSAPrivateKey.= pack('Ca*a*', CRYPT_RSA_ASN1_SEQUENCE, $this->_encodeLength(strlen($OtherPrimeInfos)), $OtherPrimeInfos);
631 $RSAPrivateKey = pack('Ca*a*', CRYPT_RSA_ASN1_SEQUENCE, $this->_encodeLength(strlen($RSAPrivateKey)), $RSAPrivateKey);
633 if (!empty($this->password)) {
634 $iv = $this->_random(8);
635 $symkey = pack('H*', md5($this->password . $iv)); // symkey is short for symmetric key
636 $symkey.= substr(pack('H*', md5($symkey . $this->password . $iv)), 0, 8);
637 if (!class_exists('Crypt_TripleDES')) {
638 require_once('Crypt/TripleDES.php');
640 $des = new Crypt_TripleDES();
641 $des->setKey($symkey);
643 $iv = strtoupper(bin2hex($iv));
644 $RSAPrivateKey = "-----BEGIN RSA PRIVATE KEY-----\r\n" .
645 "Proc-Type: 4,ENCRYPTED\r\n" .
646 "DEK-Info: DES-EDE3-CBC,$iv\r\n" .
648 chunk_split(base64_encode($des->encrypt($RSAPrivateKey))) .
649 '-----END RSA PRIVATE KEY-----';
651 $RSAPrivateKey = "-----BEGIN RSA PRIVATE KEY-----\r\n" .
652 chunk_split(base64_encode($RSAPrivateKey)) .
653 '-----END RSA PRIVATE KEY-----';
656 return $RSAPrivateKey;
661 * Convert a public key to the appropriate format
664 * @see setPublicKeyFormat()
665 * @param String $RSAPrivateKey
668 function _convertPublicKey($n, $e)
670 $modulus = $n->toBytes(true);
671 $publicExponent = $e->toBytes(true);
673 switch ($this->publicKeyFormat) {
674 case CRYPT_RSA_PUBLIC_FORMAT_RAW:
675 return array('e' => $e->copy(), 'n' => $n->copy());
676 case CRYPT_RSA_PUBLIC_FORMAT_OPENSSH:
677 // from <http://tools.ietf.org/html/rfc4253#page-15>:
681 $RSAPublicKey = pack('Na*Na*Na*', strlen('ssh-rsa'), 'ssh-rsa', strlen($publicExponent), $publicExponent, strlen($modulus), $modulus);
682 $RSAPublicKey = 'ssh-rsa ' . base64_encode($RSAPublicKey) . ' ' . CRYPT_RSA_COMMENT;
684 return $RSAPublicKey;
685 default: // eg. CRYPT_RSA_PUBLIC_FORMAT_PKCS1
686 // from <http://tools.ietf.org/html/rfc3447#appendix-A.1.1>:
687 // RSAPublicKey ::= SEQUENCE {
688 // modulus INTEGER, -- n
689 // publicExponent INTEGER -- e
692 'modulus' => pack('Ca*a*', CRYPT_RSA_ASN1_INTEGER, $this->_encodeLength(strlen($modulus)), $modulus),
693 'publicExponent' => pack('Ca*a*', CRYPT_RSA_ASN1_INTEGER, $this->_encodeLength(strlen($publicExponent)), $publicExponent)
696 $RSAPublicKey = pack('Ca*a*a*',
697 CRYPT_RSA_ASN1_SEQUENCE, $this->_encodeLength(strlen($components['modulus']) + strlen($components['publicExponent'])),
698 $components['modulus'], $components['publicExponent']
701 $RSAPublicKey = "-----BEGIN PUBLIC KEY-----\r\n" .
702 chunk_split(base64_encode($RSAPublicKey)) .
703 '-----END PUBLIC KEY-----';
705 return $RSAPublicKey;
710 * Break a public or private key down into its constituant components
713 * @see _convertPublicKey()
714 * @see _convertPrivateKey()
716 * @param Integer $type
719 function _parseKey($key, $type)
722 case CRYPT_RSA_PUBLIC_FORMAT_RAW:
723 if (!is_array($key)) {
726 $components = array();
728 case isset($key['e']):
729 $components['publicExponent'] = $key['e']->copy();
731 case isset($key['exponent']):
732 $components['publicExponent'] = $key['exponent']->copy();
734 case isset($key['publicExponent']):
735 $components['publicExponent'] = $key['publicExponent']->copy();
738 $components['publicExponent'] = $key[0]->copy();
741 case isset($key['n']):
742 $components['modulus'] = $key['n']->copy();
744 case isset($key['modulo']):
745 $components['modulus'] = $key['modulo']->copy();
747 case isset($key['modulus']):
748 $components['modulus'] = $key['modulus']->copy();
751 $components['modulus'] = $key[1]->copy();
754 case CRYPT_RSA_PRIVATE_FORMAT_PKCS1:
755 case CRYPT_RSA_PUBLIC_FORMAT_PKCS1:
756 /* Although PKCS#1 proposes a format that public and private keys can use, encrypting them is
757 "outside the scope" of PKCS#1. PKCS#1 then refers you to PKCS#12 and PKCS#15 if you're wanting to
758 protect private keys, however, that's not what OpenSSL* does. OpenSSL protects private keys by adding
759 two new "fields" to the key - DEK-Info and Proc-Type. These fields are discussed here:
761 http://tools.ietf.org/html/rfc1421#section-4.6.1.1
762 http://tools.ietf.org/html/rfc1421#section-4.6.1.3
764 DES-EDE3-CBC as an algorithm, however, is not discussed anywhere, near as I can tell.
765 DES-CBC and DES-EDE are discussed in RFC1423, however, DES-EDE3-CBC isn't, nor is its key derivation
766 function. As is, the definitive authority on this encoding scheme isn't the IETF but rather OpenSSL's
767 own implementation. ie. the implementation *is* the standard and any bugs that may exist in that
768 implementation are part of the standard, as well.
770 * OpenSSL is the de facto standard. It's utilized by OpenSSH and other projects */
771 if (preg_match('#DEK-Info: (.+),(.+)#', $key, $matches)) {
772 $iv = pack('H*', trim($matches[2]));
773 $symkey = pack('H*', md5($this->password . $iv)); // symkey is short for symmetric key
774 $symkey.= substr(pack('H*', md5($symkey . $this->password . $iv)), 0, 8);
775 $ciphertext = preg_replace('#.+(\r|\n|\r\n)\1|[\r\n]|-.+-#s', '', $key);
776 $ciphertext = preg_match('#^[a-zA-Z\d/+]*={0,2}$#', $ciphertext) ? base64_decode($ciphertext) : false;
777 if ($ciphertext === false) {
780 switch ($matches[1]) {
782 if (!class_exists('Crypt_TripleDES')) {
783 require_once('Crypt/TripleDES.php');
785 $crypto = new Crypt_TripleDES();
788 if (!class_exists('Crypt_DES')) {
789 require_once('Crypt/DES.php');
791 $crypto = new Crypt_DES();
796 $crypto->setKey($symkey);
798 $decoded = $crypto->decrypt($ciphertext);
800 $decoded = preg_replace('#-.+-|[\r\n]#', '', $key);
801 $decoded = preg_match('#^[a-zA-Z\d/+]*={0,2}$#', $decoded) ? base64_decode($decoded) : false;
804 if ($decoded !== false) {
808 $components = array();
810 if (ord($this->_string_shift($key)) != CRYPT_RSA_ASN1_SEQUENCE) {
813 if ($this->_decodeLength($key) != strlen($key)) {
817 $tag = ord($this->_string_shift($key));
818 if ($tag == CRYPT_RSA_ASN1_SEQUENCE) {
819 /* intended for keys for which OpenSSL's asn1parse returns the following:
821 0:d=0 hl=4 l= 290 cons: SEQUENCE
822 4:d=1 hl=2 l= 13 cons: SEQUENCE
823 6:d=2 hl=2 l= 9 prim: OBJECT :rsaEncryption
824 17:d=2 hl=2 l= 0 prim: NULL
825 19:d=1 hl=4 l= 271 prim: BIT STRING */
826 $this->_string_shift($key, $this->_decodeLength($key));
827 $this->_string_shift($key); // skip over the BIT STRING tag
828 $this->_decodeLength($key); // skip over the BIT STRING length
829 // "The initial octet shall encode, as an unsigned binary integer wtih bit 1 as the least significant bit, the number of
830 // unused bits in teh final subsequent octet. The number shall be in the range zero to seven."
831 // -- http://www.itu.int/ITU-T/studygroups/com17/languages/X.690-0207.pdf (section 8.6.2.2)
832 $this->_string_shift($key);
833 if (ord($this->_string_shift($key)) != CRYPT_RSA_ASN1_SEQUENCE) {
836 if ($this->_decodeLength($key) != strlen($key)) {
839 $tag = ord($this->_string_shift($key));
841 if ($tag != CRYPT_RSA_ASN1_INTEGER) {
845 $length = $this->_decodeLength($key);
846 $temp = $this->_string_shift($key, $length);
847 if (strlen($temp) != 1 || ord($temp) > 2) {
848 $components['modulus'] = new Math_BigInteger($temp, -256);
849 $this->_string_shift($key); // skip over CRYPT_RSA_ASN1_INTEGER
850 $length = $this->_decodeLength($key);
851 $components[$type == CRYPT_RSA_PUBLIC_FORMAT_PKCS1 ? 'publicExponent' : 'privateExponent'] = new Math_BigInteger($this->_string_shift($key, $length), -256);
855 if (ord($this->_string_shift($key)) != CRYPT_RSA_ASN1_INTEGER) {
858 $length = $this->_decodeLength($key);
859 $components['modulus'] = new Math_BigInteger($this->_string_shift($key, $length), -256);
860 $this->_string_shift($key);
861 $length = $this->_decodeLength($key);
862 $components['publicExponent'] = new Math_BigInteger($this->_string_shift($key, $length), -256);
863 $this->_string_shift($key);
864 $length = $this->_decodeLength($key);
865 $components['privateExponent'] = new Math_BigInteger($this->_string_shift($key, $length), -256);
866 $this->_string_shift($key);
867 $length = $this->_decodeLength($key);
868 $components['primes'] = array(1 => new Math_BigInteger($this->_string_shift($key, $length), -256));
869 $this->_string_shift($key);
870 $length = $this->_decodeLength($key);
871 $components['primes'][] = new Math_BigInteger($this->_string_shift($key, $length), -256);
872 $this->_string_shift($key);
873 $length = $this->_decodeLength($key);
874 $components['exponents'] = array(1 => new Math_BigInteger($this->_string_shift($key, $length), -256));
875 $this->_string_shift($key);
876 $length = $this->_decodeLength($key);
877 $components['exponents'][] = new Math_BigInteger($this->_string_shift($key, $length), -256);
878 $this->_string_shift($key);
879 $length = $this->_decodeLength($key);
880 $components['coefficients'] = array(2 => new Math_BigInteger($this->_string_shift($key, $length), -256));
883 if (ord($this->_string_shift($key)) != CRYPT_RSA_ASN1_SEQUENCE) {
886 $this->_decodeLength($key);
887 while (!empty($key)) {
888 if (ord($this->_string_shift($key)) != CRYPT_RSA_ASN1_SEQUENCE) {
891 $this->_decodeLength($key);
892 $key = substr($key, 1);
893 $length = $this->_decodeLength($key);
894 $components['primes'][] = new Math_BigInteger($this->_string_shift($key, $length), -256);
895 $this->_string_shift($key);
896 $length = $this->_decodeLength($key);
897 $components['exponents'][] = new Math_BigInteger($this->_string_shift($key, $length), -256);
898 $this->_string_shift($key);
899 $length = $this->_decodeLength($key);
900 $components['coefficients'][] = new Math_BigInteger($this->_string_shift($key, $length), -256);
905 case CRYPT_RSA_PUBLIC_FORMAT_OPENSSH:
906 $key = base64_decode(preg_replace('#^ssh-rsa | .+$#', '', $key));
907 if ($key === false) {
911 $cleanup = substr($key, 0, 11) == "\0\0\0\7ssh-rsa";
913 extract(unpack('Nlength', $this->_string_shift($key, 4)));
914 $publicExponent = new Math_BigInteger($this->_string_shift($key, $length), -256);
915 extract(unpack('Nlength', $this->_string_shift($key, 4)));
916 $modulus = new Math_BigInteger($this->_string_shift($key, $length), -256);
918 if ($cleanup && strlen($key)) {
919 extract(unpack('Nlength', $this->_string_shift($key, 4)));
921 'modulus' => new Math_BigInteger($this->_string_shift($key, $length), -256),
922 'publicExponent' => $modulus
926 'modulus' => $modulus,
927 'publicExponent' => $publicExponent
934 * Loads a public or private key
936 * Returns true on success and false on failure (ie. an incorrect password was provided or the key was malformed)
940 * @param Integer $type optional
942 function loadKey($key, $type = CRYPT_RSA_PRIVATE_FORMAT_PKCS1)
944 $components = $this->_parseKey($key, $type);
945 if ($components === false) {
949 $this->modulus = $components['modulus'];
950 $this->k = strlen($this->modulus->toBytes());
951 $this->exponent = isset($components['privateExponent']) ? $components['privateExponent'] : $components['publicExponent'];
952 if (isset($components['primes'])) {
953 $this->primes = $components['primes'];
954 $this->exponents = $components['exponents'];
955 $this->coefficients = $components['coefficients'];
956 $this->publicExponent = $components['publicExponent'];
958 $this->primes = array();
959 $this->exponents = array();
960 $this->coefficients = array();
961 $this->publicExponent = false;
970 * Private keys can be encrypted with a password. To unset the password, pass in the empty string or false.
971 * Or rather, pass in $password such that empty($password) is true.
976 * @param String $password
978 function setPassword($password)
980 $this->password = $password;
984 * Defines the public key
986 * Some private key formats define the public exponent and some don't. Those that don't define it are problematic when
987 * used in certain contexts. For example, in SSH-2, RSA authentication works by sending the public key along with a
988 * message signed by the private key to the server. The SSH-2 server looks the public key up in an index of public keys
989 * and if it's present then proceeds to verify the signature. Problem is, if your private key doesn't include the public
990 * exponent this won't work unless you manually add the public exponent.
992 * Do note that when a new key is loaded the index will be cleared.
994 * Returns true on success, false on failure
996 * @see getPublicKey()
999 * @param Integer $type optional
1002 function setPublicKey($key, $type = CRYPT_RSA_PUBLIC_FORMAT_PKCS1)
1004 $components = $this->_parseKey($key, $type);
1005 if (empty($this->modulus) || !$this->modulus->equals($components['modulus'])) {
1008 $this->publicExponent = $components['publicExponent'];
1012 * Returns the public key
1014 * The public key is only returned under two circumstances - if the private key had the public key embedded within it
1015 * or if the public key was set via setPublicKey(). If the currently loaded key is supposed to be the public key this
1016 * function won't return it since this library, for the most part, doesn't distinguish between public and private keys.
1018 * @see getPublicKey()
1020 * @param String $key
1021 * @param Integer $type optional
1023 function getPublicKey($type = CRYPT_RSA_PUBLIC_FORMAT_PKCS1)
1025 if (empty($this->modulus) || empty($this->publicExponent)) {
1029 $oldFormat = $this->publicKeyFormat;
1030 $this->publicKeyFormat = $type;
1031 $temp = $this->_convertPublicKey($this->modulus, $this->publicExponent);
1032 $this->publicKeyFormat = $oldFormat;
1037 * Generates the smallest and largest numbers requiring $bits bits
1040 * @param Integer $bits
1043 function _generateMinMax($bits)
1045 $bytes = $bits >> 3;
1046 $min = str_repeat(chr(0), $bytes);
1047 $max = str_repeat(chr(0xFF), $bytes);
1050 $min = chr(1 << ($msb - 1)) . $min;
1051 $max = chr((1 << $msb) - 1) . $max;
1053 $min[0] = chr(0x80);
1057 'min' => new Math_BigInteger($min, 256),
1058 'max' => new Math_BigInteger($max, 256)
1063 * DER-decode the length
1065 * DER supports lengths up to (2**8)**127, however, we'll only support lengths up to (2**8)**4. See
1066 * {@link http://itu.int/ITU-T/studygroups/com17/languages/X.690-0207.pdf#p=13 X.690 § 8.1.3} for more information.
1069 * @param String $string
1072 function _decodeLength(&$string)
1074 $length = ord($this->_string_shift($string));
1075 if ( $length & 0x80 ) { // definite length, long form
1077 $temp = $this->_string_shift($string, $length);
1078 list(, $length) = unpack('N', substr(str_pad($temp, 4, chr(0), STR_PAD_LEFT), -4));
1084 * DER-encode the length
1086 * DER supports lengths up to (2**8)**127, however, we'll only support lengths up to (2**8)**4. See
1087 * {@link http://itu.int/ITU-T/studygroups/com17/languages/X.690-0207.pdf#p=13 X.690 § 8.1.3} for more information.
1090 * @param Integer $length
1093 function _encodeLength($length)
1095 if ($length <= 0x7F) {
1096 return chr($length);
1099 $temp = ltrim(pack('N', $length), chr(0));
1100 return pack('Ca*', 0x80 | strlen($temp), $temp);
1106 * Inspired by array_shift
1108 * @param String $string
1109 * @param optional Integer $index
1113 function _string_shift(&$string, $index = 1)
1115 $substr = substr($string, 0, $index);
1116 $string = substr($string, $index);
1121 * Determines the private key format
1125 * @param Integer $format
1127 function setPrivateKeyFormat($format)
1129 $this->privateKeyFormat = $format;
1133 * Determines the public key format
1137 * @param Integer $format
1139 function setPublicKeyFormat($format)
1141 $this->publicKeyFormat = $format;
1145 * Determines which hashing function should be used
1147 * Used with signature production / verification and (if the encryption mode is CRYPT_RSA_ENCRYPTION_OAEP) encryption and
1148 * decryption. If $hash isn't supported, sha1 is used.
1151 * @param String $hash
1153 function setHash($hash)
1155 // Crypt_Hash supports algorithms that PKCS#1 doesn't support. md5-96 and sha1-96, for example.
1163 $this->hash = new Crypt_Hash($hash);
1164 $this->hashName = $hash;
1167 $this->hash = new Crypt_Hash('sha1');
1168 $this->hashName = 'sha1';
1170 $this->hLen = $this->hash->getLength();
1174 * Determines which hashing function should be used for the mask generation function
1176 * The mask generation function is used by CRYPT_RSA_ENCRYPTION_OAEP and CRYPT_RSA_SIGNATURE_PSS and although it's
1177 * best if Hash and MGFHash are set to the same thing this is not a requirement.
1180 * @param String $hash
1182 function setMGFHash($hash)
1184 // Crypt_Hash supports algorithms that PKCS#1 doesn't support. md5-96 and sha1-96, for example.
1192 $this->mgfHash = new Crypt_Hash($hash);
1195 $this->mgfHash = new Crypt_Hash('sha1');
1197 $this->mgfHLen = $this->mgfHash->getLength();
1201 * Determines the salt length
1203 * To quote from {@link http://tools.ietf.org/html/rfc3447#page-38 RFC3447#page-38}:
1205 * Typical salt lengths in octets are hLen (the length of the output
1206 * of the hash function Hash) and 0.
1209 * @param Integer $format
1211 function setSaltLength($sLen)
1213 $this->sLen = $sLen;
1217 * Generates a random string x bytes long
1220 * @param Integer $bytes
1221 * @param optional Integer $nonzero
1224 function _random($bytes, $nonzero = false)
1228 for ($i = 0; $i < $bytes; $i++) {
1229 $temp.= chr(crypt_random(1, 255));
1232 $ints = ($bytes + 1) >> 2;
1233 for ($i = 0; $i < $ints; $i++) {
1234 $temp.= pack('N', crypt_random());
1236 $temp = substr($temp, 0, $bytes);
1242 * Integer-to-Octet-String primitive
1244 * See {@link http://tools.ietf.org/html/rfc3447#section-4.1 RFC3447#section-4.1}.
1247 * @param Math_BigInteger $x
1248 * @param Integer $xLen
1251 function _i2osp($x, $xLen)
1254 if (strlen($x) > $xLen) {
1255 user_error('Integer too large', E_USER_NOTICE);
1258 return str_pad($x, $xLen, chr(0), STR_PAD_LEFT);
1262 * Octet-String-to-Integer primitive
1264 * See {@link http://tools.ietf.org/html/rfc3447#section-4.2 RFC3447#section-4.2}.
1268 * @return Math_BigInteger
1272 return new Math_BigInteger($x, 256);
1276 * Exponentiate with or without Chinese Remainder Theorem
1278 * See {@link http://tools.ietf.org/html/rfc3447#section-5.1.1 RFC3447#section-5.1.2}.
1281 * @param Math_BigInteger $x
1282 * @return Math_BigInteger
1284 function _exponentiate($x)
1286 if (empty($this->primes) || empty($this->coefficients) || empty($this->exponents)) {
1287 return $x->modPow($this->exponent, $this->modulus);
1290 $num_primes = count($this->primes);
1292 if (defined('CRYPT_RSA_DISABLE_BLINDING')) {
1294 1 => $x->modPow($this->exponents[1], $this->primes[1]),
1295 2 => $x->modPow($this->exponents[2], $this->primes[2])
1297 $h = $m_i[1]->subtract($m_i[2]);
1298 $h = $h->multiply($this->coefficients[2]);
1299 list(, $h) = $h->divide($this->primes[1]);
1300 $m = $m_i[2]->add($h->multiply($this->primes[2]));
1302 $r = $this->primes[1];
1303 for ($i = 3; $i <= $num_primes; $i++) {
1304 $m_i = $x->modPow($this->exponents[$i], $this->primes[$i]);
1306 $r = $r->multiply($this->primes[$i - 1]);
1308 $h = $m_i->subtract($m);
1309 $h = $h->multiply($this->coefficients[$i]);
1310 list(, $h) = $h->divide($this->primes[$i]);
1312 $m = $m->add($r->multiply($h));
1315 $smallest = $this->primes[1];
1316 for ($i = 2; $i <= $num_primes; $i++) {
1317 if ($smallest->compare($this->primes[$i]) > 0) {
1318 $smallest = $this->primes[$i];
1322 $one = new Math_BigInteger(1);
1323 $one->setRandomGenerator('crypt_random');
1325 $r = $one->random($one, $smallest->subtract($one));
1328 1 => $this->_blind($x, $r, 1),
1329 2 => $this->_blind($x, $r, 2)
1331 $h = $m_i[1]->subtract($m_i[2]);
1332 $h = $h->multiply($this->coefficients[2]);
1333 list(, $h) = $h->divide($this->primes[1]);
1334 $m = $m_i[2]->add($h->multiply($this->primes[2]));
1336 $r = $this->primes[1];
1337 for ($i = 3; $i <= $num_primes; $i++) {
1338 $m_i = $this->_blind($x, $r, $i);
1340 $r = $r->multiply($this->primes[$i - 1]);
1342 $h = $m_i->subtract($m);
1343 $h = $h->multiply($this->coefficients[$i]);
1344 list(, $h) = $h->divide($this->primes[$i]);
1346 $m = $m->add($r->multiply($h));
1354 * Performs RSA Blinding
1356 * Protects against timing attacks by employing RSA Blinding.
1357 * Returns $x->modPow($this->exponents[$i], $this->primes[$i])
1360 * @param Math_BigInteger $x
1361 * @param Math_BigInteger $r
1363 * @return Math_BigInteger
1365 function _blind($x, $r, $i)
1367 $x = $x->multiply($r->modPow($this->publicExponent, $this->primes[$i]));
1369 $x = $x->modPow($this->exponents[$i], $this->primes[$i]);
1371 $r = $r->modInverse($this->primes[$i]);
1372 $x = $x->multiply($r);
1373 list(, $x) = $x->divide($this->primes[$i]);
1381 * See {@link http://tools.ietf.org/html/rfc3447#section-5.1.1 RFC3447#section-5.1.1}.
1384 * @param Math_BigInteger $m
1385 * @return Math_BigInteger
1389 if ($m->compare($this->zero) < 0 || $m->compare($this->modulus) > 0) {
1390 user_error('Message representative out of range', E_USER_NOTICE);
1393 return $this->_exponentiate($m);
1399 * See {@link http://tools.ietf.org/html/rfc3447#section-5.1.2 RFC3447#section-5.1.2}.
1402 * @param Math_BigInteger $c
1403 * @return Math_BigInteger
1407 if ($c->compare($this->zero) < 0 || $c->compare($this->modulus) > 0) {
1408 user_error('Ciphertext representative out of range', E_USER_NOTICE);
1411 return $this->_exponentiate($c);
1417 * See {@link http://tools.ietf.org/html/rfc3447#section-5.2.1 RFC3447#section-5.2.1}.
1420 * @param Math_BigInteger $m
1421 * @return Math_BigInteger
1423 function _rsasp1($m)
1425 if ($m->compare($this->zero) < 0 || $m->compare($this->modulus) > 0) {
1426 user_error('Message representative out of range', E_USER_NOTICE);
1429 return $this->_exponentiate($m);
1435 * See {@link http://tools.ietf.org/html/rfc3447#section-5.2.2 RFC3447#section-5.2.2}.
1438 * @param Math_BigInteger $s
1439 * @return Math_BigInteger
1441 function _rsavp1($s)
1443 if ($s->compare($this->zero) < 0 || $s->compare($this->modulus) > 0) {
1444 user_error('Signature representative out of range', E_USER_NOTICE);
1447 return $this->_exponentiate($s);
1453 * See {@link http://tools.ietf.org/html/rfc3447#appendix-B.2.1 RFC3447#appendix-B.2.1}.
1456 * @param String $mgfSeed
1457 * @param Integer $mgfLen
1460 function _mgf1($mgfSeed, $maskLen)
1462 // if $maskLen would yield strings larger than 4GB, PKCS#1 suggests a "Mask too long" error be output.
1465 $count = ceil($maskLen / $this->mgfHLen);
1466 for ($i = 0; $i < $count; $i++) {
1468 $t.= $this->mgfHash->hash($mgfSeed . $c);
1471 return substr($t, 0, $maskLen);
1475 * RSAES-OAEP-ENCRYPT
1477 * See {@link http://tools.ietf.org/html/rfc3447#section-7.1.1 RFC3447#section-7.1.1} and
1478 * {http://en.wikipedia.org/wiki/Optimal_Asymmetric_Encryption_Padding OAES}.
1485 function _rsaes_oaep_encrypt($m, $l = '')
1491 // if $l is larger than two million terrabytes and you're using sha1, PKCS#1 suggests a "Label too long" error
1494 if ($mLen > $this->k - 2 * $this->hLen - 2) {
1495 user_error('Message too long', E_USER_NOTICE);
1499 // EME-OAEP encoding
1501 $lHash = $this->hash->hash($l);
1502 $ps = str_repeat(chr(0), $this->k - $mLen - 2 * $this->hLen - 2);
1503 $db = $lHash . $ps . chr(1) . $m;
1504 $seed = $this->_random($this->hLen);
1505 $dbMask = $this->_mgf1($seed, $this->k - $this->hLen - 1);
1506 $maskedDB = $db ^ $dbMask;
1507 $seedMask = $this->_mgf1($maskedDB, $this->hLen);
1508 $maskedSeed = $seed ^ $seedMask;
1509 $em = chr(0) . $maskedSeed . $maskedDB;
1513 $m = $this->_os2ip($em);
1514 $c = $this->_rsaep($m);
1515 $c = $this->_i2osp($c, $this->k);
1517 // Output the ciphertext C
1523 * RSAES-OAEP-DECRYPT
1525 * See {@link http://tools.ietf.org/html/rfc3447#section-7.1.2 RFC3447#section-7.1.2}. The fact that the error
1526 * messages aren't distinguishable from one another hinders debugging, but, to quote from RFC3447#section-7.1.2:
1528 * Note. Care must be taken to ensure that an opponent cannot
1529 * distinguish the different error conditions in Step 3.g, whether by
1530 * error message or timing, or, more generally, learn partial
1531 * information about the encoded message EM. Otherwise an opponent may
1532 * be able to obtain useful information about the decryption of the
1533 * ciphertext C, leading to a chosen-ciphertext attack such as the one
1534 * observed by Manger [36].
1536 * As for $l... to quote from {@link http://tools.ietf.org/html/rfc3447#page-17 RFC3447#page-17}:
1538 * Both the encryption and the decryption operations of RSAES-OAEP take
1539 * the value of a label L as input. In this version of PKCS #1, L is
1540 * the empty string; other uses of the label are outside the scope of
1548 function _rsaes_oaep_decrypt($c, $l = '')
1552 // if $l is larger than two million terrabytes and you're using sha1, PKCS#1 suggests a "Label too long" error
1555 if (strlen($c) != $this->k || $this->k < 2 * $this->hLen + 2) {
1556 user_error('Decryption error', E_USER_NOTICE);
1562 $c = $this->_os2ip($c);
1563 $m = $this->_rsadp($c);
1565 user_error('Decryption error', E_USER_NOTICE);
1568 $em = $this->_i2osp($m, $this->k);
1570 // EME-OAEP decoding
1572 $lHash = $this->hash->hash($l);
1574 $maskedSeed = substr($em, 1, $this->hLen);
1575 $maskedDB = substr($em, $this->hLen + 1);
1576 $seedMask = $this->_mgf1($maskedDB, $this->hLen);
1577 $seed = $maskedSeed ^ $seedMask;
1578 $dbMask = $this->_mgf1($seed, $this->k - $this->hLen - 1);
1579 $db = $maskedDB ^ $dbMask;
1580 $lHash2 = substr($db, 0, $this->hLen);
1581 $m = substr($db, $this->hLen);
1582 if ($lHash != $lHash2) {
1583 user_error('Decryption error', E_USER_NOTICE);
1586 $m = ltrim($m, chr(0));
1587 if (ord($m[0]) != 1) {
1588 user_error('Decryption error', E_USER_NOTICE);
1592 // Output the message M
1594 return substr($m, 1);
1598 * RSAES-PKCS1-V1_5-ENCRYPT
1600 * See {@link http://tools.ietf.org/html/rfc3447#section-7.2.1 RFC3447#section-7.2.1}.
1606 function _rsaes_pkcs1_v1_5_encrypt($m)
1612 if ($mLen > $this->k - 11) {
1613 user_error('Message too long', E_USER_NOTICE);
1617 // EME-PKCS1-v1_5 encoding
1619 $ps = $this->_random($this->k - $mLen - 3, true);
1620 $em = chr(0) . chr(2) . $ps . chr(0) . $m;
1623 $m = $this->_os2ip($em);
1624 $c = $this->_rsaep($m);
1625 $c = $this->_i2osp($c, $this->k);
1627 // Output the ciphertext C
1633 * RSAES-PKCS1-V1_5-DECRYPT
1635 * See {@link http://tools.ietf.org/html/rfc3447#section-7.2.2 RFC3447#section-7.2.2}.
1641 function _rsaes_pkcs1_v1_5_decrypt($c)
1645 if (strlen($c) != $this->k) { // or if k < 11
1646 user_error('Decryption error', E_USER_NOTICE);
1652 $c = $this->_os2ip($c);
1653 $m = $this->_rsadp($c);
1655 user_error('Decryption error', E_USER_NOTICE);
1658 $em = $this->_i2osp($m, $this->k);
1660 // EME-PKCS1-v1_5 decoding
1662 if (ord($em[0]) != 0 || ord($em[1]) != 2) {
1663 user_error('Decryption error', E_USER_NOTICE);
1667 $ps = substr($em, 2, strpos($em, chr(0), 2) - 2);
1668 $m = substr($em, strlen($ps) + 3);
1670 if (strlen($ps) < 8) {
1671 user_error('Decryption error', E_USER_NOTICE);
1683 * See {@link http://tools.ietf.org/html/rfc3447#section-9.1.1 RFC3447#section-9.1.1}.
1687 * @param Integer $emBits
1689 function _emsa_pss_encode($m, $emBits)
1691 // if $m is larger than two million terrabytes and you're using sha1, PKCS#1 suggests a "Label too long" error
1694 $emLen = ($emBits + 1) >> 3; // ie. ceil($emBits / 8)
1695 $sLen = $this->sLen == false ? $this->hLen : $this->sLen;
1697 $mHash = $this->hash->hash($m);
1698 if ($emLen < $this->hLen + $sLen + 2) {
1699 user_error('Encoding error', E_USER_NOTICE);
1703 $salt = $this->_random($sLen);
1704 $m2 = "\0\0\0\0\0\0\0\0" . $mHash . $salt;
1705 $h = $this->hash->hash($m2);
1706 $ps = str_repeat(chr(0), $emLen - $sLen - $this->hLen - 2);
1707 $db = $ps . chr(1) . $salt;
1708 $dbMask = $this->_mgf1($h, $emLen - $this->hLen - 1);
1709 $maskedDB = $db ^ $dbMask;
1710 $maskedDB[0] = ~chr(0xFF << ($emBits & 7)) & $maskedDB[0];
1711 $em = $maskedDB . $h . chr(0xBC);
1719 * See {@link http://tools.ietf.org/html/rfc3447#section-9.1.2 RFC3447#section-9.1.2}.
1724 * @param Integer $emBits
1727 function _emsa_pss_verify($m, $em, $emBits)
1729 // if $m is larger than two million terrabytes and you're using sha1, PKCS#1 suggests a "Label too long" error
1732 $emLen = ($emBits + 1) >> 3; // ie. ceil($emBits / 8);
1733 $sLen = $this->sLen == false ? $this->hLen : $this->sLen;
1735 $mHash = $this->hash->hash($m);
1736 if ($emLen < $this->hLen + $sLen + 2) {
1740 if ($em[strlen($em) - 1] != chr(0xBC)) {
1744 $maskedDB = substr($em, 0, $em - $this->hLen - 1);
1745 $h = substr($em, $em - $this->hLen - 1, $this->hLen);
1746 $temp = chr(0xFF << ($emBits & 7));
1747 if ((~$maskedDB[0] & $temp) != $temp) {
1750 $dbMask = $this->_mgf1($h, $emLen - $this->hLen - 1);
1751 $db = $maskedDB ^ $dbMask;
1752 $db[0] = ~chr(0xFF << ($emBits & 7)) & $db[0];
1753 $temp = $emLen - $this->hLen - $sLen - 2;
1754 if (substr($db, 0, $temp) != str_repeat(chr(0), $temp) || ord($db[$temp]) != 1) {
1757 $salt = substr($db, $temp + 1); // should be $sLen long
1758 $m2 = "\0\0\0\0\0\0\0\0" . $mHash . $salt;
1759 $h2 = $this->hash->hash($m2);
1766 * See {@link http://tools.ietf.org/html/rfc3447#section-8.1.1 RFC3447#section-8.1.1}.
1772 function _rsassa_pss_sign($m)
1774 // EMSA-PSS encoding
1776 $em = $this->_emsa_pss_encode($m, 8 * $this->k - 1);
1780 $m = $this->_os2ip($em);
1781 $s = $this->_rsasp1($m);
1782 $s = $this->_i2osp($s, $this->k);
1784 // Output the signature S
1792 * See {@link http://tools.ietf.org/html/rfc3447#section-8.1.2 RFC3447#section-8.1.2}.
1799 function _rsassa_pss_verify($m, $s)
1803 if (strlen($s) != $this->k) {
1804 user_error('Invalid signature', E_USER_NOTICE);
1810 $modBits = 8 * $this->k;
1812 $s2 = $this->_os2ip($s);
1813 $m2 = $this->_rsavp1($s2);
1814 if ($m2 === false) {
1815 user_error('Invalid signature', E_USER_NOTICE);
1818 $em = $this->_i2osp($m2, $modBits >> 3);
1819 if ($em === false) {
1820 user_error('Invalid signature', E_USER_NOTICE);
1824 // EMSA-PSS verification
1826 return $this->_emsa_pss_verify($m, $em, $modBits - 1);
1830 * EMSA-PKCS1-V1_5-ENCODE
1832 * See {@link http://tools.ietf.org/html/rfc3447#section-9.2 RFC3447#section-9.2}.
1836 * @param Integer $emLen
1839 function _emsa_pkcs1_v1_5_encode($m, $emLen)
1841 $h = $this->hash->hash($m);
1846 // see http://tools.ietf.org/html/rfc3447#page-43
1847 switch ($this->hashName) {
1849 $t = pack('H*', '3020300c06082a864886f70d020205000410');
1852 $t = pack('H*', '3020300c06082a864886f70d020505000410');
1855 $t = pack('H*', '3021300906052b0e03021a05000414');
1858 $t = pack('H*', '3031300d060960864801650304020105000420');
1861 $t = pack('H*', '3041300d060960864801650304020205000430');
1864 $t = pack('H*', '3051300d060960864801650304020305000440');
1869 if ($emLen < $tLen + 11) {
1870 user_error('Intended encoded message length too short', E_USER_NOTICE);
1874 $ps = str_repeat(chr(0xFF), $emLen - $tLen - 3);
1876 $em = "\0\1$ps\0$t";
1882 * RSASSA-PKCS1-V1_5-SIGN
1884 * See {@link http://tools.ietf.org/html/rfc3447#section-8.2.1 RFC3447#section-8.2.1}.
1890 function _rsassa_pkcs1_v1_5_sign($m)
1892 // EMSA-PKCS1-v1_5 encoding
1894 $em = $this->_emsa_pkcs1_v1_5_encode($m, $this->k);
1895 if ($em === false) {
1896 user_error('RSA modulus too short', E_USER_NOTICE);
1902 $m = $this->_os2ip($em);
1903 $s = $this->_rsasp1($m);
1904 $s = $this->_i2osp($s, $this->k);
1906 // Output the signature S
1912 * RSASSA-PKCS1-V1_5-VERIFY
1914 * See {@link http://tools.ietf.org/html/rfc3447#section-8.2.2 RFC3447#section-8.2.2}.
1920 function _rsassa_pkcs1_v1_5_verify($m, $s)
1924 if (strlen($s) != $this->k) {
1925 user_error('Invalid signature', E_USER_NOTICE);
1931 $s = $this->_os2ip($s);
1932 $m2 = $this->_rsavp1($s);
1933 if ($m2 === false) {
1934 user_error('Invalid signature', E_USER_NOTICE);
1937 $em = $this->_i2osp($m2, $this->k);
1938 if ($em === false) {
1939 user_error('Invalid signature', E_USER_NOTICE);
1943 // EMSA-PKCS1-v1_5 encoding
1945 $em2 = $this->_emsa_pkcs1_v1_5_encode($m, $this->k);
1946 if ($em2 === false) {
1947 user_error('RSA modulus too short', E_USER_NOTICE);
1953 return $em === $em2;
1957 * Set Encryption Mode
1959 * Valid values include CRYPT_RSA_ENCRYPTION_OAEP and CRYPT_RSA_ENCRYPTION_PKCS1.
1962 * @param Integer $mode
1964 function setEncryptionMode($mode)
1966 $this->encryptionMode = $mode;
1970 * Set Signature Mode
1972 * Valid values include CRYPT_RSA_SIGNATURE_PSS and CRYPT_RSA_SIGNATURE_PKCS1
1975 * @param Integer $mode
1977 function setSignatureMode($mode)
1979 $this->signatureMode = $mode;
1985 * Both CRYPT_RSA_ENCRYPTION_OAEP and CRYPT_RSA_ENCRYPTION_PKCS1 both place limits on how long $plaintext can be.
1986 * If $plaintext exceeds those limits it will be broken up so that it does and the resultant ciphertext's will
1987 * be concatenated together.
1991 * @param String $plaintext
1994 function encrypt($plaintext)
1996 switch ($this->encryptionMode) {
1997 case CRYPT_RSA_ENCRYPTION_PKCS1:
1998 $length = $this->k - 11;
2003 $plaintext = str_split($plaintext, $length);
2005 foreach ($plaintext as $m) {
2006 $ciphertext.= $this->_rsaes_pkcs1_v1_5_encrypt($m);
2009 //case CRYPT_RSA_ENCRYPTION_OAEP:
2011 $length = $this->k - 2 * $this->hLen - 2;
2016 $plaintext = str_split($plaintext, $length);
2018 foreach ($plaintext as $m) {
2019 $ciphertext.= $this->_rsaes_oaep_encrypt($m);
2030 * @param String $plaintext
2033 function decrypt($ciphertext)
2035 if ($this->k <= 0) {
2039 $ciphertext = str_split($ciphertext, $this->k);
2042 switch ($this->encryptionMode) {
2043 case CRYPT_RSA_ENCRYPTION_PKCS1:
2044 $decrypt = '_rsaes_pkcs1_v1_5_decrypt';
2046 //case CRYPT_RSA_ENCRYPTION_OAEP:
2048 $decrypt = '_rsaes_oaep_decrypt';
2051 foreach ($ciphertext as $c) {
2052 $temp = $this->$decrypt($c);
2053 if ($temp === false) {
2063 * Create a signature
2067 * @param String $message
2070 function sign($message)
2072 if (empty($this->modulus) || empty($this->exponent)) {
2076 switch ($this->signatureMode) {
2077 case CRYPT_RSA_SIGNATURE_PKCS1:
2078 return $this->_rsassa_pkcs1_v1_5_sign($message);
2079 //case CRYPT_RSA_SIGNATURE_PSS:
2081 return $this->_rsassa_pss_sign($message);
2086 * Verifies a signature
2090 * @param String $message
2091 * @param String $signature
2094 function verify($message, $signature)
2096 if (empty($this->modulus) || empty($this->exponent)) {
2100 switch ($this->signatureMode) {
2101 case CRYPT_RSA_SIGNATURE_PKCS1:
2102 return $this->_rsassa_pkcs1_v1_5_verify($message, $signature);
2103 //case CRYPT_RSA_SIGNATURE_PSS:
2105 return $this->_rsassa_pss_verify($message, $signature);