PHPSECLIB 0.3.1 added to the project to support SFTP transfers of lab orders and...
[openemr.git] / library / phpseclib / Crypt / RSA.php
blob7df1ded760e51db9835519f1479ef358b54c1909
1 <?php
2 /* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
4 /**
5 * Pure-PHP PKCS#1 (v2.1) compliant implementation of RSA.
7 * PHP versions 4 and 5
9 * Here's an example of how to encrypt and decrypt text with this library:
10 * <code>
11 * <?php
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);
24 * ?>
25 * </code>
27 * Here's an example of how to create signatures and verify signatures with this library:
28 * <code>
29 * <?php
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';
42 * ?>
43 * </code>
45 * LICENSE: Permission is hereby granted, free of charge, to any person obtaining a copy
46 * of this software and associated documentation files (the "Software"), to deal
47 * in the Software without restriction, including without limitation the rights
48 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
49 * copies of the Software, and to permit persons to whom the Software is
50 * furnished to do so, subject to the following conditions:
52 * The above copyright notice and this permission notice shall be included in
53 * all copies or substantial portions of the Software.
55 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
56 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
57 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
58 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
59 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
60 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
61 * THE SOFTWARE.
63 * @category Crypt
64 * @package Crypt_RSA
65 * @author Jim Wigginton <terrafrost@php.net>
66 * @copyright MMIX Jim Wigginton
67 * @license http://www.opensource.org/licenses/mit-license.html MIT License
68 * @version $Id: RSA.php,v 1.19 2010/09/12 21:58:54 terrafrost Exp $
69 * @link http://phpseclib.sourceforge.net
72 /**
73 * Include Math_BigInteger
75 if (!class_exists('Math_BigInteger')) {
76 require_once('Math/BigInteger.php');
79 /**
80 * Include Crypt_Random
82 // the class_exists() will only be called if the crypt_random function hasn't been defined and
83 // will trigger a call to __autoload() if you're wanting to auto-load classes
84 // call function_exists() a second time to stop the require_once from being called outside
85 // of the auto loader
86 if (!function_exists('crypt_random') && !class_exists('Crypt_Random') && !function_exists('crypt_random')) {
87 require_once('Crypt/Random.php');
90 /**
91 * Include Crypt_Hash
93 if (!class_exists('Crypt_Hash')) {
94 require_once('Crypt/Hash.php');
97 /**#@+
98 * @access public
99 * @see Crypt_RSA::encrypt()
100 * @see Crypt_RSA::decrypt()
103 * Use {@link http://en.wikipedia.org/wiki/Optimal_Asymmetric_Encryption_Padding Optimal Asymmetric Encryption Padding}
104 * (OAEP) for encryption / decryption.
106 * Uses sha1 by default.
108 * @see Crypt_RSA::setHash()
109 * @see Crypt_RSA::setMGFHash()
111 define('CRYPT_RSA_ENCRYPTION_OAEP', 1);
113 * Use PKCS#1 padding.
115 * Although CRYPT_RSA_ENCRYPTION_OAEP offers more security, including PKCS#1 padding is necessary for purposes of backwards
116 * compatability with protocols (like SSH-1) written before OAEP's introduction.
118 define('CRYPT_RSA_ENCRYPTION_PKCS1', 2);
119 /**#@-*/
121 /**#@+
122 * @access public
123 * @see Crypt_RSA::sign()
124 * @see Crypt_RSA::verify()
125 * @see Crypt_RSA::setHash()
128 * Use the Probabilistic Signature Scheme for signing
130 * Uses sha1 by default.
132 * @see Crypt_RSA::setSaltLength()
133 * @see Crypt_RSA::setMGFHash()
135 define('CRYPT_RSA_SIGNATURE_PSS', 1);
137 * Use the PKCS#1 scheme by default.
139 * Although CRYPT_RSA_SIGNATURE_PSS offers more security, including PKCS#1 signing is necessary for purposes of backwards
140 * compatability with protocols (like SSH-2) written before PSS's introduction.
142 define('CRYPT_RSA_SIGNATURE_PKCS1', 2);
143 /**#@-*/
145 /**#@+
146 * @access private
147 * @see Crypt_RSA::createKey()
150 * ASN1 Integer
152 define('CRYPT_RSA_ASN1_INTEGER', 2);
154 * ASN1 Bit String
156 define('CRYPT_RSA_ASN1_BITSTRING', 3);
158 * ASN1 Sequence (with the constucted bit set)
160 define('CRYPT_RSA_ASN1_SEQUENCE', 48);
161 /**#@-*/
163 /**#@+
164 * @access private
165 * @see Crypt_RSA::Crypt_RSA()
168 * To use the pure-PHP implementation
170 define('CRYPT_RSA_MODE_INTERNAL', 1);
172 * To use the OpenSSL library
174 * (if enabled; otherwise, the internal implementation will be used)
176 define('CRYPT_RSA_MODE_OPENSSL', 2);
177 /**#@-*/
179 /**#@+
180 * @access public
181 * @see Crypt_RSA::createKey()
182 * @see Crypt_RSA::setPrivateKeyFormat()
185 * PKCS#1 formatted private key
187 * Used by OpenSSH
189 define('CRYPT_RSA_PRIVATE_FORMAT_PKCS1', 0);
191 * PuTTY formatted private key
193 define('CRYPT_RSA_PRIVATE_FORMAT_PUTTY', 1);
195 * XML formatted private key
197 define('CRYPT_RSA_PRIVATE_FORMAT_XML', 2);
198 /**#@-*/
200 /**#@+
201 * @access public
202 * @see Crypt_RSA::createKey()
203 * @see Crypt_RSA::setPublicKeyFormat()
206 * Raw public key
208 * An array containing two Math_BigInteger objects.
210 * The exponent can be indexed with any of the following:
212 * 0, e, exponent, publicExponent
214 * The modulus can be indexed with any of the following:
216 * 1, n, modulo, modulus
218 define('CRYPT_RSA_PUBLIC_FORMAT_RAW', 3);
220 * PKCS#1 formatted public key (raw)
222 * Used by File/X509.php
224 define('CRYPT_RSA_PUBLIC_FORMAT_PKCS1_RAW', 4);
226 * XML formatted public key
228 define('CRYPT_RSA_PUBLIC_FORMAT_XML', 5);
230 * OpenSSH formatted public key
232 * Place in $HOME/.ssh/authorized_keys
234 define('CRYPT_RSA_PUBLIC_FORMAT_OPENSSH', 6);
236 * PKCS#1 formatted public key (encapsulated)
238 * Used by PHP's openssl_public_encrypt() and openssl's rsautl (when -pubin is set)
240 define('CRYPT_RSA_PUBLIC_FORMAT_PKCS1', 7);
241 /**#@-*/
244 * Pure-PHP PKCS#1 compliant implementation of RSA.
246 * @author Jim Wigginton <terrafrost@php.net>
247 * @version 0.1.0
248 * @access public
249 * @package Crypt_RSA
251 class Crypt_RSA {
253 * Precomputed Zero
255 * @var Array
256 * @access private
258 var $zero;
261 * Precomputed One
263 * @var Array
264 * @access private
266 var $one;
269 * Private Key Format
271 * @var Integer
272 * @access private
274 var $privateKeyFormat = CRYPT_RSA_PRIVATE_FORMAT_PKCS1;
277 * Public Key Format
279 * @var Integer
280 * @access public
282 var $publicKeyFormat = CRYPT_RSA_PUBLIC_FORMAT_PKCS1;
285 * Modulus (ie. n)
287 * @var Math_BigInteger
288 * @access private
290 var $modulus;
293 * Modulus length
295 * @var Math_BigInteger
296 * @access private
298 var $k;
301 * Exponent (ie. e or d)
303 * @var Math_BigInteger
304 * @access private
306 var $exponent;
309 * Primes for Chinese Remainder Theorem (ie. p and q)
311 * @var Array
312 * @access private
314 var $primes;
317 * Exponents for Chinese Remainder Theorem (ie. dP and dQ)
319 * @var Array
320 * @access private
322 var $exponents;
325 * Coefficients for Chinese Remainder Theorem (ie. qInv)
327 * @var Array
328 * @access private
330 var $coefficients;
333 * Hash name
335 * @var String
336 * @access private
338 var $hashName;
341 * Hash function
343 * @var Crypt_Hash
344 * @access private
346 var $hash;
349 * Length of hash function output
351 * @var Integer
352 * @access private
354 var $hLen;
357 * Length of salt
359 * @var Integer
360 * @access private
362 var $sLen;
365 * Hash function for the Mask Generation Function
367 * @var Crypt_Hash
368 * @access private
370 var $mgfHash;
373 * Length of MGF hash function output
375 * @var Integer
376 * @access private
378 var $mgfHLen;
381 * Encryption mode
383 * @var Integer
384 * @access private
386 var $encryptionMode = CRYPT_RSA_ENCRYPTION_OAEP;
389 * Signature mode
391 * @var Integer
392 * @access private
394 var $signatureMode = CRYPT_RSA_SIGNATURE_PSS;
397 * Public Exponent
399 * @var Mixed
400 * @access private
402 var $publicExponent = false;
405 * Password
407 * @var String
408 * @access private
410 var $password = false;
413 * Components
415 * For use with parsing XML formatted keys. PHP's XML Parser functions use utilized - instead of PHP's DOM functions -
416 * because PHP's XML Parser functions work on PHP4 whereas PHP's DOM functions - although surperior - don't.
418 * @see Crypt_RSA::_start_element_handler()
419 * @var Array
420 * @access private
422 var $components = array();
425 * Current String
427 * For use with parsing XML formatted keys.
429 * @see Crypt_RSA::_character_handler()
430 * @see Crypt_RSA::_stop_element_handler()
431 * @var Mixed
432 * @access private
434 var $current;
437 * The constructor
439 * If you want to make use of the openssl extension, you'll need to set the mode manually, yourself. The reason
440 * Crypt_RSA doesn't do it is because OpenSSL doesn't fail gracefully. openssl_pkey_new(), in particular, requires
441 * openssl.cnf be present somewhere and, unfortunately, the only real way to find out is too late.
443 * @return Crypt_RSA
444 * @access public
446 function Crypt_RSA()
448 if ( !defined('CRYPT_RSA_MODE') ) {
449 switch (true) {
450 case extension_loaded('openssl') && version_compare(PHP_VERSION, '4.2.0', '>='):
451 define('CRYPT_RSA_MODE', CRYPT_RSA_MODE_OPENSSL);
452 break;
453 default:
454 define('CRYPT_RSA_MODE', CRYPT_RSA_MODE_INTERNAL);
458 if (!defined('CRYPT_RSA_COMMENT')) {
459 define('CRYPT_RSA_COMMENT', 'phpseclib-generated-key');
462 $this->zero = new Math_BigInteger();
463 $this->one = new Math_BigInteger(1);
465 $this->hash = new Crypt_Hash('sha1');
466 $this->hLen = $this->hash->getLength();
467 $this->hashName = 'sha1';
468 $this->mgfHash = new Crypt_Hash('sha1');
469 $this->mgfHLen = $this->mgfHash->getLength();
473 * Create public / private key pair
475 * Returns an array with the following three elements:
476 * - 'privatekey': The private key.
477 * - 'publickey': The public key.
478 * - 'partialkey': A partially computed key (if the execution time exceeded $timeout).
479 * Will need to be passed back to Crypt_RSA::createKey() as the third parameter for further processing.
481 * @access public
482 * @param optional Integer $bits
483 * @param optional Integer $timeout
484 * @param optional Math_BigInteger $p
486 function createKey($bits = 1024, $timeout = false, $partial = array())
488 if (!defined('CRYPT_RSA_EXPONENT')) {
489 // http://en.wikipedia.org/wiki/65537_%28number%29
490 define('CRYPT_RSA_EXPONENT', '65537');
492 // per <http://cseweb.ucsd.edu/~hovav/dist/survey.pdf#page=5>, this number ought not result in primes smaller
493 // 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
494 // to 384 bits then you're going to get a 384 bit prime and a 640 bit prime (384 + 1024 % 384). at least if
495 // CRYPT_RSA_MODE is set to CRYPT_RSA_MODE_INTERNAL. if CRYPT_RSA_MODE is set to CRYPT_RSA_MODE_OPENSSL then
496 // CRYPT_RSA_SMALLEST_PRIME is ignored (ie. multi-prime RSA support is more intended as a way to speed up RSA key
497 // generation when there's a chance neither gmp nor OpenSSL are installed)
498 if (!defined('CRYPT_RSA_SMALLEST_PRIME')) {
499 define('CRYPT_RSA_SMALLEST_PRIME', 4096);
502 // OpenSSL uses 65537 as the exponent and requires RSA keys be 384 bits minimum
503 if ( CRYPT_RSA_MODE == CRYPT_RSA_MODE_OPENSSL && $bits >= 384 && CRYPT_RSA_EXPONENT == 65537) {
504 $rsa = openssl_pkey_new(array(
505 'private_key_bits' => $bits,
506 'config' => dirname(__FILE__) . '/../openssl.cnf'
509 openssl_pkey_export($rsa, $privatekey, NULL, array('config' => dirname(__FILE__) . '/../openssl.cnf'));
510 $publickey = openssl_pkey_get_details($rsa);
511 $publickey = $publickey['key'];
513 $privatekey = call_user_func_array(array($this, '_convertPrivateKey'), array_values($this->_parseKey($privatekey, CRYPT_RSA_PRIVATE_FORMAT_PKCS1)));
514 $publickey = call_user_func_array(array($this, '_convertPublicKey'), array_values($this->_parseKey($publickey, CRYPT_RSA_PUBLIC_FORMAT_PKCS1)));
516 // clear the buffer of error strings stemming from a minimalistic openssl.cnf
517 while (openssl_error_string() !== false);
519 return array(
520 'privatekey' => $privatekey,
521 'publickey' => $publickey,
522 'partialkey' => false
526 static $e;
527 if (!isset($e)) {
528 $e = new Math_BigInteger(CRYPT_RSA_EXPONENT);
531 extract($this->_generateMinMax($bits));
532 $absoluteMin = $min;
533 $temp = $bits >> 1; // divide by two to see how many bits P and Q would be
534 if ($temp > CRYPT_RSA_SMALLEST_PRIME) {
535 $num_primes = floor($bits / CRYPT_RSA_SMALLEST_PRIME);
536 $temp = CRYPT_RSA_SMALLEST_PRIME;
537 } else {
538 $num_primes = 2;
540 extract($this->_generateMinMax($temp + $bits % $temp));
541 $finalMax = $max;
542 extract($this->_generateMinMax($temp));
544 $generator = new Math_BigInteger();
545 $generator->setRandomGenerator('crypt_random');
547 $n = $this->one->copy();
548 if (!empty($partial)) {
549 extract(unserialize($partial));
550 } else {
551 $exponents = $coefficients = $primes = array();
552 $lcm = array(
553 'top' => $this->one->copy(),
554 'bottom' => false
558 $start = time();
559 $i0 = count($primes) + 1;
561 do {
562 for ($i = $i0; $i <= $num_primes; $i++) {
563 if ($timeout !== false) {
564 $timeout-= time() - $start;
565 $start = time();
566 if ($timeout <= 0) {
567 return array(
568 'privatekey' => '',
569 'publickey' => '',
570 'partialkey' => serialize(array(
571 'primes' => $primes,
572 'coefficients' => $coefficients,
573 'lcm' => $lcm,
574 'exponents' => $exponents
580 if ($i == $num_primes) {
581 list($min, $temp) = $absoluteMin->divide($n);
582 if (!$temp->equals($this->zero)) {
583 $min = $min->add($this->one); // ie. ceil()
585 $primes[$i] = $generator->randomPrime($min, $finalMax, $timeout);
586 } else {
587 $primes[$i] = $generator->randomPrime($min, $max, $timeout);
590 if ($primes[$i] === false) { // if we've reached the timeout
591 if (count($primes) > 1) {
592 $partialkey = '';
593 } else {
594 array_pop($primes);
595 $partialkey = serialize(array(
596 'primes' => $primes,
597 'coefficients' => $coefficients,
598 'lcm' => $lcm,
599 'exponents' => $exponents
603 return array(
604 'privatekey' => '',
605 'publickey' => '',
606 'partialkey' => $partialkey
610 // the first coefficient is calculated differently from the rest
611 // ie. instead of being $primes[1]->modInverse($primes[2]), it's $primes[2]->modInverse($primes[1])
612 if ($i > 2) {
613 $coefficients[$i] = $n->modInverse($primes[$i]);
616 $n = $n->multiply($primes[$i]);
618 $temp = $primes[$i]->subtract($this->one);
620 // textbook RSA implementations use Euler's totient function instead of the least common multiple.
621 // see http://en.wikipedia.org/wiki/Euler%27s_totient_function
622 $lcm['top'] = $lcm['top']->multiply($temp);
623 $lcm['bottom'] = $lcm['bottom'] === false ? $temp : $lcm['bottom']->gcd($temp);
625 $exponents[$i] = $e->modInverse($temp);
628 list($lcm) = $lcm['top']->divide($lcm['bottom']);
629 $gcd = $lcm->gcd($e);
630 $i0 = 1;
631 } while (!$gcd->equals($this->one));
633 $d = $e->modInverse($lcm);
635 $coefficients[2] = $primes[2]->modInverse($primes[1]);
637 // from <http://tools.ietf.org/html/rfc3447#appendix-A.1.2>:
638 // RSAPrivateKey ::= SEQUENCE {
639 // version Version,
640 // modulus INTEGER, -- n
641 // publicExponent INTEGER, -- e
642 // privateExponent INTEGER, -- d
643 // prime1 INTEGER, -- p
644 // prime2 INTEGER, -- q
645 // exponent1 INTEGER, -- d mod (p-1)
646 // exponent2 INTEGER, -- d mod (q-1)
647 // coefficient INTEGER, -- (inverse of q) mod p
648 // otherPrimeInfos OtherPrimeInfos OPTIONAL
649 // }
651 return array(
652 'privatekey' => $this->_convertPrivateKey($n, $e, $d, $primes, $exponents, $coefficients),
653 'publickey' => $this->_convertPublicKey($n, $e),
654 'partialkey' => false
659 * Convert a private key to the appropriate format.
661 * @access private
662 * @see setPrivateKeyFormat()
663 * @param String $RSAPrivateKey
664 * @return String
666 function _convertPrivateKey($n, $e, $d, $primes, $exponents, $coefficients)
668 $num_primes = count($primes);
669 $raw = array(
670 'version' => $num_primes == 2 ? chr(0) : chr(1), // two-prime vs. multi
671 'modulus' => $n->toBytes(true),
672 'publicExponent' => $e->toBytes(true),
673 'privateExponent' => $d->toBytes(true),
674 'prime1' => $primes[1]->toBytes(true),
675 'prime2' => $primes[2]->toBytes(true),
676 'exponent1' => $exponents[1]->toBytes(true),
677 'exponent2' => $exponents[2]->toBytes(true),
678 'coefficient' => $coefficients[2]->toBytes(true)
681 // if the format in question does not support multi-prime rsa and multi-prime rsa was used,
682 // call _convertPublicKey() instead.
683 switch ($this->privateKeyFormat) {
684 case CRYPT_RSA_PRIVATE_FORMAT_XML:
685 if ($num_primes != 2) {
686 return false;
688 return "<RSAKeyValue>\r\n" .
689 ' <Modulus>' . base64_encode($raw['modulus']) . "</Modulus>\r\n" .
690 ' <Exponent>' . base64_encode($raw['publicExponent']) . "</Exponent>\r\n" .
691 ' <P>' . base64_encode($raw['prime1']) . "</P>\r\n" .
692 ' <Q>' . base64_encode($raw['prime2']) . "</Q>\r\n" .
693 ' <DP>' . base64_encode($raw['exponent1']) . "</DP>\r\n" .
694 ' <DQ>' . base64_encode($raw['exponent2']) . "</DQ>\r\n" .
695 ' <InverseQ>' . base64_encode($raw['coefficient']) . "</InverseQ>\r\n" .
696 ' <D>' . base64_encode($raw['privateExponent']) . "</D>\r\n" .
697 '</RSAKeyValue>';
698 break;
699 case CRYPT_RSA_PRIVATE_FORMAT_PUTTY:
700 if ($num_primes != 2) {
701 return false;
703 $key = "PuTTY-User-Key-File-2: ssh-rsa\r\nEncryption: ";
704 $encryption = (!empty($this->password) || is_string($this->password)) ? 'aes256-cbc' : 'none';
705 $key.= $encryption;
706 $key.= "\r\nComment: " . CRYPT_RSA_COMMENT . "\r\n";
707 $public = pack('Na*Na*Na*',
708 strlen('ssh-rsa'), 'ssh-rsa', strlen($raw['publicExponent']), $raw['publicExponent'], strlen($raw['modulus']), $raw['modulus']
710 $source = pack('Na*Na*Na*Na*',
711 strlen('ssh-rsa'), 'ssh-rsa', strlen($encryption), $encryption,
712 strlen(CRYPT_RSA_COMMENT), CRYPT_RSA_COMMENT, strlen($public), $public
714 $public = base64_encode($public);
715 $key.= "Public-Lines: " . ((strlen($public) + 32) >> 6) . "\r\n";
716 $key.= chunk_split($public, 64);
717 $private = pack('Na*Na*Na*Na*',
718 strlen($raw['privateExponent']), $raw['privateExponent'], strlen($raw['prime1']), $raw['prime1'],
719 strlen($raw['prime2']), $raw['prime2'], strlen($raw['coefficient']), $raw['coefficient']
721 if (empty($this->password) && !is_string($this->password)) {
722 $source.= pack('Na*', strlen($private), $private);
723 $hashkey = 'putty-private-key-file-mac-key';
724 } else {
725 $private.= $this->_random(16 - (strlen($private) & 15));
726 $source.= pack('Na*', strlen($private), $private);
727 if (!class_exists('Crypt_AES')) {
728 require_once('Crypt/AES.php');
730 $sequence = 0;
731 $symkey = '';
732 while (strlen($symkey) < 32) {
733 $temp = pack('Na*', $sequence++, $this->password);
734 $symkey.= pack('H*', sha1($temp));
736 $symkey = substr($symkey, 0, 32);
737 $crypto = new Crypt_AES();
739 $crypto->setKey($symkey);
740 $crypto->disablePadding();
741 $private = $crypto->encrypt($private);
742 $hashkey = 'putty-private-key-file-mac-key' . $this->password;
745 $private = base64_encode($private);
746 $key.= 'Private-Lines: ' . ((strlen($private) + 32) >> 6) . "\r\n";
747 $key.= chunk_split($private, 64);
748 if (!class_exists('Crypt_Hash')) {
749 require_once('Crypt/Hash.php');
751 $hash = new Crypt_Hash('sha1');
752 $hash->setKey(pack('H*', sha1($hashkey)));
753 $key.= 'Private-MAC: ' . bin2hex($hash->hash($source)) . "\r\n";
755 return $key;
756 default: // eg. CRYPT_RSA_PRIVATE_FORMAT_PKCS1
757 $components = array();
758 foreach ($raw as $name => $value) {
759 $components[$name] = pack('Ca*a*', CRYPT_RSA_ASN1_INTEGER, $this->_encodeLength(strlen($value)), $value);
762 $RSAPrivateKey = implode('', $components);
764 if ($num_primes > 2) {
765 $OtherPrimeInfos = '';
766 for ($i = 3; $i <= $num_primes; $i++) {
767 // OtherPrimeInfos ::= SEQUENCE SIZE(1..MAX) OF OtherPrimeInfo
769 // OtherPrimeInfo ::= SEQUENCE {
770 // prime INTEGER, -- ri
771 // exponent INTEGER, -- di
772 // coefficient INTEGER -- ti
773 // }
774 $OtherPrimeInfo = pack('Ca*a*', CRYPT_RSA_ASN1_INTEGER, $this->_encodeLength(strlen($primes[$i]->toBytes(true))), $primes[$i]->toBytes(true));
775 $OtherPrimeInfo.= pack('Ca*a*', CRYPT_RSA_ASN1_INTEGER, $this->_encodeLength(strlen($exponents[$i]->toBytes(true))), $exponents[$i]->toBytes(true));
776 $OtherPrimeInfo.= pack('Ca*a*', CRYPT_RSA_ASN1_INTEGER, $this->_encodeLength(strlen($coefficients[$i]->toBytes(true))), $coefficients[$i]->toBytes(true));
777 $OtherPrimeInfos.= pack('Ca*a*', CRYPT_RSA_ASN1_SEQUENCE, $this->_encodeLength(strlen($OtherPrimeInfo)), $OtherPrimeInfo);
779 $RSAPrivateKey.= pack('Ca*a*', CRYPT_RSA_ASN1_SEQUENCE, $this->_encodeLength(strlen($OtherPrimeInfos)), $OtherPrimeInfos);
782 $RSAPrivateKey = pack('Ca*a*', CRYPT_RSA_ASN1_SEQUENCE, $this->_encodeLength(strlen($RSAPrivateKey)), $RSAPrivateKey);
784 if (!empty($this->password) || is_string($this->password)) {
785 $iv = $this->_random(8);
786 $symkey = pack('H*', md5($this->password . $iv)); // symkey is short for symmetric key
787 $symkey.= substr(pack('H*', md5($symkey . $this->password . $iv)), 0, 8);
788 if (!class_exists('Crypt_TripleDES')) {
789 require_once('Crypt/TripleDES.php');
791 $des = new Crypt_TripleDES();
792 $des->setKey($symkey);
793 $des->setIV($iv);
794 $iv = strtoupper(bin2hex($iv));
795 $RSAPrivateKey = "-----BEGIN RSA PRIVATE KEY-----\r\n" .
796 "Proc-Type: 4,ENCRYPTED\r\n" .
797 "DEK-Info: DES-EDE3-CBC,$iv\r\n" .
798 "\r\n" .
799 chunk_split(base64_encode($des->encrypt($RSAPrivateKey))) .
800 '-----END RSA PRIVATE KEY-----';
801 } else {
802 $RSAPrivateKey = "-----BEGIN RSA PRIVATE KEY-----\r\n" .
803 chunk_split(base64_encode($RSAPrivateKey)) .
804 '-----END RSA PRIVATE KEY-----';
807 return $RSAPrivateKey;
812 * Convert a public key to the appropriate format
814 * @access private
815 * @see setPublicKeyFormat()
816 * @param String $RSAPrivateKey
817 * @return String
819 function _convertPublicKey($n, $e)
821 $modulus = $n->toBytes(true);
822 $publicExponent = $e->toBytes(true);
824 switch ($this->publicKeyFormat) {
825 case CRYPT_RSA_PUBLIC_FORMAT_RAW:
826 return array('e' => $e->copy(), 'n' => $n->copy());
827 case CRYPT_RSA_PUBLIC_FORMAT_XML:
828 return "<RSAKeyValue>\r\n" .
829 ' <Modulus>' . base64_encode($modulus) . "</Modulus>\r\n" .
830 ' <Exponent>' . base64_encode($publicExponent) . "</Exponent>\r\n" .
831 '</RSAKeyValue>';
832 break;
833 case CRYPT_RSA_PUBLIC_FORMAT_OPENSSH:
834 // from <http://tools.ietf.org/html/rfc4253#page-15>:
835 // string "ssh-rsa"
836 // mpint e
837 // mpint n
838 $RSAPublicKey = pack('Na*Na*Na*', strlen('ssh-rsa'), 'ssh-rsa', strlen($publicExponent), $publicExponent, strlen($modulus), $modulus);
839 $RSAPublicKey = 'ssh-rsa ' . base64_encode($RSAPublicKey) . ' ' . CRYPT_RSA_COMMENT;
841 return $RSAPublicKey;
842 default: // eg. CRYPT_RSA_PUBLIC_FORMAT_PKCS1_RAW or CRYPT_RSA_PUBLIC_FORMAT_PKCS1
843 // from <http://tools.ietf.org/html/rfc3447#appendix-A.1.1>:
844 // RSAPublicKey ::= SEQUENCE {
845 // modulus INTEGER, -- n
846 // publicExponent INTEGER -- e
847 // }
848 $components = array(
849 'modulus' => pack('Ca*a*', CRYPT_RSA_ASN1_INTEGER, $this->_encodeLength(strlen($modulus)), $modulus),
850 'publicExponent' => pack('Ca*a*', CRYPT_RSA_ASN1_INTEGER, $this->_encodeLength(strlen($publicExponent)), $publicExponent)
853 $RSAPublicKey = pack('Ca*a*a*',
854 CRYPT_RSA_ASN1_SEQUENCE, $this->_encodeLength(strlen($components['modulus']) + strlen($components['publicExponent'])),
855 $components['modulus'], $components['publicExponent']
858 if ($this->publicKeyFormat == CRYPT_RSA_PUBLIC_FORMAT_PKCS1) {
859 // sequence(oid(1.2.840.113549.1.1.1), null)) = rsaEncryption.
860 $rsaOID = pack('H*', '300d06092a864886f70d0101010500'); // hex version of MA0GCSqGSIb3DQEBAQUA
861 $RSAPublicKey = chr(0) . $RSAPublicKey;
862 $RSAPublicKey = chr(3) . $this->_encodeLength(strlen($RSAPublicKey)) . $RSAPublicKey;
864 $RSAPublicKey = pack('Ca*a*',
865 CRYPT_RSA_ASN1_SEQUENCE, $this->_encodeLength(strlen($rsaOID . $RSAPublicKey)), $rsaOID . $RSAPublicKey
869 $RSAPublicKey = "-----BEGIN PUBLIC KEY-----\r\n" .
870 chunk_split(base64_encode($RSAPublicKey)) .
871 '-----END PUBLIC KEY-----';
873 return $RSAPublicKey;
878 * Break a public or private key down into its constituant components
880 * @access private
881 * @see _convertPublicKey()
882 * @see _convertPrivateKey()
883 * @param String $key
884 * @param Integer $type
885 * @return Array
887 function _parseKey($key, $type)
889 if ($type != CRYPT_RSA_PUBLIC_FORMAT_RAW && !is_string($key)) {
890 return false;
893 switch ($type) {
894 case CRYPT_RSA_PUBLIC_FORMAT_RAW:
895 if (!is_array($key)) {
896 return false;
898 $components = array();
899 switch (true) {
900 case isset($key['e']):
901 $components['publicExponent'] = $key['e']->copy();
902 break;
903 case isset($key['exponent']):
904 $components['publicExponent'] = $key['exponent']->copy();
905 break;
906 case isset($key['publicExponent']):
907 $components['publicExponent'] = $key['publicExponent']->copy();
908 break;
909 case isset($key[0]):
910 $components['publicExponent'] = $key[0]->copy();
912 switch (true) {
913 case isset($key['n']):
914 $components['modulus'] = $key['n']->copy();
915 break;
916 case isset($key['modulo']):
917 $components['modulus'] = $key['modulo']->copy();
918 break;
919 case isset($key['modulus']):
920 $components['modulus'] = $key['modulus']->copy();
921 break;
922 case isset($key[1]):
923 $components['modulus'] = $key[1]->copy();
925 return isset($components['modulus']) && isset($components['publicExponent']) ? $components : false;
926 case CRYPT_RSA_PRIVATE_FORMAT_PKCS1:
927 case CRYPT_RSA_PUBLIC_FORMAT_PKCS1:
928 /* Although PKCS#1 proposes a format that public and private keys can use, encrypting them is
929 "outside the scope" of PKCS#1. PKCS#1 then refers you to PKCS#12 and PKCS#15 if you're wanting to
930 protect private keys, however, that's not what OpenSSL* does. OpenSSL protects private keys by adding
931 two new "fields" to the key - DEK-Info and Proc-Type. These fields are discussed here:
933 http://tools.ietf.org/html/rfc1421#section-4.6.1.1
934 http://tools.ietf.org/html/rfc1421#section-4.6.1.3
936 DES-EDE3-CBC as an algorithm, however, is not discussed anywhere, near as I can tell.
937 DES-CBC and DES-EDE are discussed in RFC1423, however, DES-EDE3-CBC isn't, nor is its key derivation
938 function. As is, the definitive authority on this encoding scheme isn't the IETF but rather OpenSSL's
939 own implementation. ie. the implementation *is* the standard and any bugs that may exist in that
940 implementation are part of the standard, as well.
942 * OpenSSL is the de facto standard. It's utilized by OpenSSH and other projects */
943 if (preg_match('#DEK-Info: (.+),(.+)#', $key, $matches)) {
944 $iv = pack('H*', trim($matches[2]));
945 $symkey = pack('H*', md5($this->password . substr($iv, 0, 8))); // symkey is short for symmetric key
946 $symkey.= substr(pack('H*', md5($symkey . $this->password . $iv)), 0, 8);
947 $ciphertext = preg_replace('#.+(\r|\n|\r\n)\1|[\r\n]|-.+-| #s', '', $key);
948 $ciphertext = preg_match('#^[a-zA-Z\d/+]*={0,2}$#', $ciphertext) ? base64_decode($ciphertext) : false;
949 if ($ciphertext === false) {
950 $ciphertext = $key;
952 switch ($matches[1]) {
953 case 'AES-128-CBC':
954 if (!class_exists('Crypt_AES')) {
955 require_once('Crypt/AES.php');
957 $symkey = substr($symkey, 0, 16);
958 $crypto = new Crypt_AES();
959 break;
960 case 'DES-EDE3-CFB':
961 if (!class_exists('Crypt_TripleDES')) {
962 require_once('Crypt/TripleDES.php');
964 $crypto = new Crypt_TripleDES(CRYPT_DES_MODE_CFB);
965 break;
966 case 'DES-EDE3-CBC':
967 if (!class_exists('Crypt_TripleDES')) {
968 require_once('Crypt/TripleDES.php');
970 $crypto = new Crypt_TripleDES();
971 break;
972 case 'DES-CBC':
973 if (!class_exists('Crypt_DES')) {
974 require_once('Crypt/DES.php');
976 $crypto = new Crypt_DES();
977 break;
978 default:
979 return false;
981 $crypto->setKey($symkey);
982 $crypto->setIV($iv);
983 $decoded = $crypto->decrypt($ciphertext);
984 } else {
985 $decoded = preg_replace('#-.+-|[\r\n]| #', '', $key);
986 $decoded = preg_match('#^[a-zA-Z\d/+]*={0,2}$#', $decoded) ? base64_decode($decoded) : false;
989 if ($decoded !== false) {
990 $key = $decoded;
993 $components = array();
995 if (ord($this->_string_shift($key)) != CRYPT_RSA_ASN1_SEQUENCE) {
996 return false;
998 if ($this->_decodeLength($key) != strlen($key)) {
999 return false;
1002 $tag = ord($this->_string_shift($key));
1003 /* intended for keys for which OpenSSL's asn1parse returns the following:
1005 0:d=0 hl=4 l= 631 cons: SEQUENCE
1006 4:d=1 hl=2 l= 1 prim: INTEGER :00
1007 7:d=1 hl=2 l= 13 cons: SEQUENCE
1008 9:d=2 hl=2 l= 9 prim: OBJECT :rsaEncryption
1009 20:d=2 hl=2 l= 0 prim: NULL
1010 22:d=1 hl=4 l= 609 prim: OCTET STRING */
1012 if ($tag == CRYPT_RSA_ASN1_INTEGER && substr($key, 0, 3) == "\x01\x00\x30") {
1013 $this->_string_shift($key, 3);
1014 $tag = CRYPT_RSA_ASN1_SEQUENCE;
1017 if ($tag == CRYPT_RSA_ASN1_SEQUENCE) {
1018 /* intended for keys for which OpenSSL's asn1parse returns the following:
1020 0:d=0 hl=4 l= 290 cons: SEQUENCE
1021 4:d=1 hl=2 l= 13 cons: SEQUENCE
1022 6:d=2 hl=2 l= 9 prim: OBJECT :rsaEncryption
1023 17:d=2 hl=2 l= 0 prim: NULL
1024 19:d=1 hl=4 l= 271 prim: BIT STRING */
1025 $this->_string_shift($key, $this->_decodeLength($key));
1026 $tag = ord($this->_string_shift($key)); // skip over the BIT STRING / OCTET STRING tag
1027 $this->_decodeLength($key); // skip over the BIT STRING / OCTET STRING length
1028 // "The initial octet shall encode, as an unsigned binary integer wtih bit 1 as the least significant bit, the number of
1029 // unused bits in the final subsequent octet. The number shall be in the range zero to seven."
1030 // -- http://www.itu.int/ITU-T/studygroups/com17/languages/X.690-0207.pdf (section 8.6.2.2)
1031 if ($tag == CRYPT_RSA_ASN1_BITSTRING) {
1032 $this->_string_shift($key);
1034 if (ord($this->_string_shift($key)) != CRYPT_RSA_ASN1_SEQUENCE) {
1035 return false;
1037 if ($this->_decodeLength($key) != strlen($key)) {
1038 return false;
1040 $tag = ord($this->_string_shift($key));
1042 if ($tag != CRYPT_RSA_ASN1_INTEGER) {
1043 return false;
1046 $length = $this->_decodeLength($key);
1047 $temp = $this->_string_shift($key, $length);
1048 if (strlen($temp) != 1 || ord($temp) > 2) {
1049 $components['modulus'] = new Math_BigInteger($temp, 256);
1050 $this->_string_shift($key); // skip over CRYPT_RSA_ASN1_INTEGER
1051 $length = $this->_decodeLength($key);
1052 $components[$type == CRYPT_RSA_PUBLIC_FORMAT_PKCS1 ? 'publicExponent' : 'privateExponent'] = new Math_BigInteger($this->_string_shift($key, $length), 256);
1054 return $components;
1056 if (ord($this->_string_shift($key)) != CRYPT_RSA_ASN1_INTEGER) {
1057 return false;
1059 $length = $this->_decodeLength($key);
1060 $components['modulus'] = new Math_BigInteger($this->_string_shift($key, $length), 256);
1061 $this->_string_shift($key);
1062 $length = $this->_decodeLength($key);
1063 $components['publicExponent'] = new Math_BigInteger($this->_string_shift($key, $length), 256);
1064 $this->_string_shift($key);
1065 $length = $this->_decodeLength($key);
1066 $components['privateExponent'] = new Math_BigInteger($this->_string_shift($key, $length), 256);
1067 $this->_string_shift($key);
1068 $length = $this->_decodeLength($key);
1069 $components['primes'] = array(1 => new Math_BigInteger($this->_string_shift($key, $length), 256));
1070 $this->_string_shift($key);
1071 $length = $this->_decodeLength($key);
1072 $components['primes'][] = new Math_BigInteger($this->_string_shift($key, $length), 256);
1073 $this->_string_shift($key);
1074 $length = $this->_decodeLength($key);
1075 $components['exponents'] = array(1 => new Math_BigInteger($this->_string_shift($key, $length), 256));
1076 $this->_string_shift($key);
1077 $length = $this->_decodeLength($key);
1078 $components['exponents'][] = new Math_BigInteger($this->_string_shift($key, $length), 256);
1079 $this->_string_shift($key);
1080 $length = $this->_decodeLength($key);
1081 $components['coefficients'] = array(2 => new Math_BigInteger($this->_string_shift($key, $length), 256));
1083 if (!empty($key)) {
1084 if (ord($this->_string_shift($key)) != CRYPT_RSA_ASN1_SEQUENCE) {
1085 return false;
1087 $this->_decodeLength($key);
1088 while (!empty($key)) {
1089 if (ord($this->_string_shift($key)) != CRYPT_RSA_ASN1_SEQUENCE) {
1090 return false;
1092 $this->_decodeLength($key);
1093 $key = substr($key, 1);
1094 $length = $this->_decodeLength($key);
1095 $components['primes'][] = new Math_BigInteger($this->_string_shift($key, $length), 256);
1096 $this->_string_shift($key);
1097 $length = $this->_decodeLength($key);
1098 $components['exponents'][] = new Math_BigInteger($this->_string_shift($key, $length), 256);
1099 $this->_string_shift($key);
1100 $length = $this->_decodeLength($key);
1101 $components['coefficients'][] = new Math_BigInteger($this->_string_shift($key, $length), 256);
1105 return $components;
1106 case CRYPT_RSA_PUBLIC_FORMAT_OPENSSH:
1107 $key = base64_decode(preg_replace('#^ssh-rsa | .+$#', '', $key));
1108 if ($key === false) {
1109 return false;
1112 $cleanup = substr($key, 0, 11) == "\0\0\0\7ssh-rsa";
1114 if (strlen($key) <= 4) {
1115 return false;
1117 extract(unpack('Nlength', $this->_string_shift($key, 4)));
1118 $publicExponent = new Math_BigInteger($this->_string_shift($key, $length), -256);
1119 if (strlen($key) <= 4) {
1120 return false;
1122 extract(unpack('Nlength', $this->_string_shift($key, 4)));
1123 $modulus = new Math_BigInteger($this->_string_shift($key, $length), -256);
1125 if ($cleanup && strlen($key)) {
1126 if (strlen($key) <= 4) {
1127 return false;
1129 extract(unpack('Nlength', $this->_string_shift($key, 4)));
1130 $realModulus = new Math_BigInteger($this->_string_shift($key, $length), -256);
1131 return strlen($key) ? false : array(
1132 'modulus' => $realModulus,
1133 'publicExponent' => $modulus
1135 } else {
1136 return strlen($key) ? false : array(
1137 'modulus' => $modulus,
1138 'publicExponent' => $publicExponent
1141 // http://www.w3.org/TR/xmldsig-core/#sec-RSAKeyValue
1142 // http://en.wikipedia.org/wiki/XML_Signature
1143 case CRYPT_RSA_PRIVATE_FORMAT_XML:
1144 case CRYPT_RSA_PUBLIC_FORMAT_XML:
1145 $this->components = array();
1147 $xml = xml_parser_create('UTF-8');
1148 xml_set_object($xml, $this);
1149 xml_set_element_handler($xml, '_start_element_handler', '_stop_element_handler');
1150 xml_set_character_data_handler($xml, '_data_handler');
1151 if (!xml_parse($xml, $key)) {
1152 return false;
1155 return isset($this->components['modulus']) && isset($this->components['publicExponent']) ? $this->components : false;
1156 // from PuTTY's SSHPUBK.C
1157 case CRYPT_RSA_PRIVATE_FORMAT_PUTTY:
1158 $components = array();
1159 $key = preg_split('#\r\n|\r|\n#', $key);
1160 $type = trim(preg_replace('#PuTTY-User-Key-File-2: (.+)#', '$1', $key[0]));
1161 if ($type != 'ssh-rsa') {
1162 return false;
1164 $encryption = trim(preg_replace('#Encryption: (.+)#', '$1', $key[1]));
1166 $publicLength = trim(preg_replace('#Public-Lines: (\d+)#', '$1', $key[3]));
1167 $public = base64_decode(implode('', array_map('trim', array_slice($key, 4, $publicLength))));
1168 $public = substr($public, 11);
1169 extract(unpack('Nlength', $this->_string_shift($public, 4)));
1170 $components['publicExponent'] = new Math_BigInteger($this->_string_shift($public, $length), -256);
1171 extract(unpack('Nlength', $this->_string_shift($public, 4)));
1172 $components['modulus'] = new Math_BigInteger($this->_string_shift($public, $length), -256);
1174 $privateLength = trim(preg_replace('#Private-Lines: (\d+)#', '$1', $key[$publicLength + 4]));
1175 $private = base64_decode(implode('', array_map('trim', array_slice($key, $publicLength + 5, $privateLength))));
1177 switch ($encryption) {
1178 case 'aes256-cbc':
1179 if (!class_exists('Crypt_AES')) {
1180 require_once('Crypt/AES.php');
1182 $symkey = '';
1183 $sequence = 0;
1184 while (strlen($symkey) < 32) {
1185 $temp = pack('Na*', $sequence++, $this->password);
1186 $symkey.= pack('H*', sha1($temp));
1188 $symkey = substr($symkey, 0, 32);
1189 $crypto = new Crypt_AES();
1192 if ($encryption != 'none') {
1193 $crypto->setKey($symkey);
1194 $crypto->disablePadding();
1195 $private = $crypto->decrypt($private);
1196 if ($private === false) {
1197 return false;
1201 extract(unpack('Nlength', $this->_string_shift($private, 4)));
1202 if (strlen($private) < $length) {
1203 return false;
1205 $components['privateExponent'] = new Math_BigInteger($this->_string_shift($private, $length), -256);
1206 extract(unpack('Nlength', $this->_string_shift($private, 4)));
1207 if (strlen($private) < $length) {
1208 return false;
1210 $components['primes'] = array(1 => new Math_BigInteger($this->_string_shift($private, $length), -256));
1211 extract(unpack('Nlength', $this->_string_shift($private, 4)));
1212 if (strlen($private) < $length) {
1213 return false;
1215 $components['primes'][] = new Math_BigInteger($this->_string_shift($private, $length), -256);
1217 $temp = $components['primes'][1]->subtract($this->one);
1218 $components['exponents'] = array(1 => $components['publicExponent']->modInverse($temp));
1219 $temp = $components['primes'][2]->subtract($this->one);
1220 $components['exponents'][] = $components['publicExponent']->modInverse($temp);
1222 extract(unpack('Nlength', $this->_string_shift($private, 4)));
1223 if (strlen($private) < $length) {
1224 return false;
1226 $components['coefficients'] = array(2 => new Math_BigInteger($this->_string_shift($private, $length), -256));
1228 return $components;
1233 * Returns the key size
1235 * More specifically, this returns the size of the modulo in bits.
1237 * @access public
1238 * @return Integer
1240 function getSize()
1242 return !isset($this->modulus) ? 0 : strlen($this->modulus->toBits());
1246 * Start Element Handler
1248 * Called by xml_set_element_handler()
1250 * @access private
1251 * @param Resource $parser
1252 * @param String $name
1253 * @param Array $attribs
1255 function _start_element_handler($parser, $name, $attribs)
1257 //$name = strtoupper($name);
1258 switch ($name) {
1259 case 'MODULUS':
1260 $this->current = &$this->components['modulus'];
1261 break;
1262 case 'EXPONENT':
1263 $this->current = &$this->components['publicExponent'];
1264 break;
1265 case 'P':
1266 $this->current = &$this->components['primes'][1];
1267 break;
1268 case 'Q':
1269 $this->current = &$this->components['primes'][2];
1270 break;
1271 case 'DP':
1272 $this->current = &$this->components['exponents'][1];
1273 break;
1274 case 'DQ':
1275 $this->current = &$this->components['exponents'][2];
1276 break;
1277 case 'INVERSEQ':
1278 $this->current = &$this->components['coefficients'][2];
1279 break;
1280 case 'D':
1281 $this->current = &$this->components['privateExponent'];
1282 break;
1283 default:
1284 unset($this->current);
1286 $this->current = '';
1290 * Stop Element Handler
1292 * Called by xml_set_element_handler()
1294 * @access private
1295 * @param Resource $parser
1296 * @param String $name
1298 function _stop_element_handler($parser, $name)
1300 //$name = strtoupper($name);
1301 if ($name == 'RSAKEYVALUE') {
1302 return;
1304 $this->current = new Math_BigInteger(base64_decode($this->current), 256);
1308 * Data Handler
1310 * Called by xml_set_character_data_handler()
1312 * @access private
1313 * @param Resource $parser
1314 * @param String $data
1316 function _data_handler($parser, $data)
1318 if (!isset($this->current) || is_object($this->current)) {
1319 return;
1321 $this->current.= trim($data);
1325 * Loads a public or private key
1327 * Returns true on success and false on failure (ie. an incorrect password was provided or the key was malformed)
1329 * @access public
1330 * @param String $key
1331 * @param Integer $type optional
1333 function loadKey($key, $type = false)
1335 if ($type === false) {
1336 $types = array(
1337 CRYPT_RSA_PUBLIC_FORMAT_RAW,
1338 CRYPT_RSA_PRIVATE_FORMAT_PKCS1,
1339 CRYPT_RSA_PRIVATE_FORMAT_XML,
1340 CRYPT_RSA_PRIVATE_FORMAT_PUTTY,
1341 CRYPT_RSA_PUBLIC_FORMAT_OPENSSH
1343 foreach ($types as $type) {
1344 $components = $this->_parseKey($key, $type);
1345 if ($components !== false) {
1346 break;
1350 } else {
1351 $components = $this->_parseKey($key, $type);
1354 if ($components === false) {
1355 return false;
1358 $this->modulus = $components['modulus'];
1359 $this->k = strlen($this->modulus->toBytes());
1360 $this->exponent = isset($components['privateExponent']) ? $components['privateExponent'] : $components['publicExponent'];
1361 if (isset($components['primes'])) {
1362 $this->primes = $components['primes'];
1363 $this->exponents = $components['exponents'];
1364 $this->coefficients = $components['coefficients'];
1365 $this->publicExponent = $components['publicExponent'];
1366 } else {
1367 $this->primes = array();
1368 $this->exponents = array();
1369 $this->coefficients = array();
1370 $this->publicExponent = false;
1373 return true;
1377 * Sets the password
1379 * Private keys can be encrypted with a password. To unset the password, pass in the empty string or false.
1380 * Or rather, pass in $password such that empty($password) && !is_string($password) is true.
1382 * @see createKey()
1383 * @see loadKey()
1384 * @access public
1385 * @param String $password
1387 function setPassword($password = false)
1389 $this->password = $password;
1393 * Defines the public key
1395 * Some private key formats define the public exponent and some don't. Those that don't define it are problematic when
1396 * used in certain contexts. For example, in SSH-2, RSA authentication works by sending the public key along with a
1397 * message signed by the private key to the server. The SSH-2 server looks the public key up in an index of public keys
1398 * and if it's present then proceeds to verify the signature. Problem is, if your private key doesn't include the public
1399 * exponent this won't work unless you manually add the public exponent.
1401 * Do note that when a new key is loaded the index will be cleared.
1403 * Returns true on success, false on failure
1405 * @see getPublicKey()
1406 * @access public
1407 * @param String $key optional
1408 * @param Integer $type optional
1409 * @return Boolean
1411 function setPublicKey($key = false, $type = false)
1413 if ($key === false && !empty($this->modulus)) {
1414 $this->publicExponent = $this->exponent;
1415 return true;
1418 if ($type === false) {
1419 $types = array(
1420 CRYPT_RSA_PUBLIC_FORMAT_RAW,
1421 CRYPT_RSA_PUBLIC_FORMAT_PKCS1,
1422 CRYPT_RSA_PUBLIC_FORMAT_XML,
1423 CRYPT_RSA_PUBLIC_FORMAT_OPENSSH
1425 foreach ($types as $type) {
1426 $components = $this->_parseKey($key, $type);
1427 if ($components !== false) {
1428 break;
1431 } else {
1432 $components = $this->_parseKey($key, $type);
1435 if ($components === false) {
1436 return false;
1439 if (empty($this->modulus) || !$this->modulus->equals($components['modulus'])) {
1440 $this->modulus = $components['modulus'];
1441 $this->exponent = $this->publicExponent = $components['publicExponent'];
1442 return true;
1445 $this->publicExponent = $components['publicExponent'];
1447 return true;
1451 * Returns the public key
1453 * The public key is only returned under two circumstances - if the private key had the public key embedded within it
1454 * or if the public key was set via setPublicKey(). If the currently loaded key is supposed to be the public key this
1455 * function won't return it since this library, for the most part, doesn't distinguish between public and private keys.
1457 * @see getPublicKey()
1458 * @access public
1459 * @param String $key
1460 * @param Integer $type optional
1462 function getPublicKey($type = CRYPT_RSA_PUBLIC_FORMAT_PKCS1)
1464 if (empty($this->modulus) || empty($this->publicExponent)) {
1465 return false;
1468 $oldFormat = $this->publicKeyFormat;
1469 $this->publicKeyFormat = $type;
1470 $temp = $this->_convertPublicKey($this->modulus, $this->publicExponent);
1471 $this->publicKeyFormat = $oldFormat;
1472 return $temp;
1476 * Returns the private key
1478 * The private key is only returned if the currently loaded key contains the constituent prime numbers.
1480 * @see getPublicKey()
1481 * @access public
1482 * @param String $key
1483 * @param Integer $type optional
1485 function getPrivateKey($type = CRYPT_RSA_PUBLIC_FORMAT_PKCS1)
1487 if (empty($this->primes)) {
1488 return false;
1491 $oldFormat = $this->privateKeyFormat;
1492 $this->privateKeyFormat = $type;
1493 $temp = $this->_convertPrivateKey($this->modulus, $this->publicExponent, $this->exponent, $this->primes, $this->exponents, $this->coefficients);
1494 $this->privateKeyFormat = $oldFormat;
1495 return $temp;
1499 * Returns a minimalistic private key
1501 * Returns the private key without the prime number constituants. Structurally identical to a public key that
1502 * hasn't been set as the public key
1504 * @see getPrivateKey()
1505 * @access private
1506 * @param String $key
1507 * @param Integer $type optional
1509 function _getPrivatePublicKey($mode = CRYPT_RSA_PUBLIC_FORMAT_PKCS1)
1511 if (empty($this->modulus) || empty($this->exponent)) {
1512 return false;
1515 $oldFormat = $this->publicKeyFormat;
1516 $this->publicKeyFormat = $mode;
1517 $temp = $this->_convertPublicKey($this->modulus, $this->exponent);
1518 $this->publicKeyFormat = $oldFormat;
1519 return $temp;
1523 * __toString() magic method
1525 * @access public
1527 function __toString()
1529 $key = $this->getPrivateKey($this->privateKeyFormat);
1530 if ($key !== false) {
1531 return $key;
1533 $key = $this->_getPrivatePublicKey($this->publicKeyFormat);
1534 return $key !== false ? $key : '';
1538 * Generates the smallest and largest numbers requiring $bits bits
1540 * @access private
1541 * @param Integer $bits
1542 * @return Array
1544 function _generateMinMax($bits)
1546 $bytes = $bits >> 3;
1547 $min = str_repeat(chr(0), $bytes);
1548 $max = str_repeat(chr(0xFF), $bytes);
1549 $msb = $bits & 7;
1550 if ($msb) {
1551 $min = chr(1 << ($msb - 1)) . $min;
1552 $max = chr((1 << $msb) - 1) . $max;
1553 } else {
1554 $min[0] = chr(0x80);
1557 return array(
1558 'min' => new Math_BigInteger($min, 256),
1559 'max' => new Math_BigInteger($max, 256)
1564 * DER-decode the length
1566 * DER supports lengths up to (2**8)**127, however, we'll only support lengths up to (2**8)**4. See
1567 * {@link http://itu.int/ITU-T/studygroups/com17/languages/X.690-0207.pdf#p=13 X.690 § 8.1.3} for more information.
1569 * @access private
1570 * @param String $string
1571 * @return Integer
1573 function _decodeLength(&$string)
1575 $length = ord($this->_string_shift($string));
1576 if ( $length & 0x80 ) { // definite length, long form
1577 $length&= 0x7F;
1578 $temp = $this->_string_shift($string, $length);
1579 list(, $length) = unpack('N', substr(str_pad($temp, 4, chr(0), STR_PAD_LEFT), -4));
1581 return $length;
1585 * DER-encode the length
1587 * DER supports lengths up to (2**8)**127, however, we'll only support lengths up to (2**8)**4. See
1588 * {@link http://itu.int/ITU-T/studygroups/com17/languages/X.690-0207.pdf#p=13 X.690 § 8.1.3} for more information.
1590 * @access private
1591 * @param Integer $length
1592 * @return String
1594 function _encodeLength($length)
1596 if ($length <= 0x7F) {
1597 return chr($length);
1600 $temp = ltrim(pack('N', $length), chr(0));
1601 return pack('Ca*', 0x80 | strlen($temp), $temp);
1605 * String Shift
1607 * Inspired by array_shift
1609 * @param String $string
1610 * @param optional Integer $index
1611 * @return String
1612 * @access private
1614 function _string_shift(&$string, $index = 1)
1616 $substr = substr($string, 0, $index);
1617 $string = substr($string, $index);
1618 return $substr;
1622 * Determines the private key format
1624 * @see createKey()
1625 * @access public
1626 * @param Integer $format
1628 function setPrivateKeyFormat($format)
1630 $this->privateKeyFormat = $format;
1634 * Determines the public key format
1636 * @see createKey()
1637 * @access public
1638 * @param Integer $format
1640 function setPublicKeyFormat($format)
1642 $this->publicKeyFormat = $format;
1646 * Determines which hashing function should be used
1648 * Used with signature production / verification and (if the encryption mode is CRYPT_RSA_ENCRYPTION_OAEP) encryption and
1649 * decryption. If $hash isn't supported, sha1 is used.
1651 * @access public
1652 * @param String $hash
1654 function setHash($hash)
1656 // Crypt_Hash supports algorithms that PKCS#1 doesn't support. md5-96 and sha1-96, for example.
1657 switch ($hash) {
1658 case 'md2':
1659 case 'md5':
1660 case 'sha1':
1661 case 'sha256':
1662 case 'sha384':
1663 case 'sha512':
1664 $this->hash = new Crypt_Hash($hash);
1665 $this->hashName = $hash;
1666 break;
1667 default:
1668 $this->hash = new Crypt_Hash('sha1');
1669 $this->hashName = 'sha1';
1671 $this->hLen = $this->hash->getLength();
1675 * Determines which hashing function should be used for the mask generation function
1677 * The mask generation function is used by CRYPT_RSA_ENCRYPTION_OAEP and CRYPT_RSA_SIGNATURE_PSS and although it's
1678 * best if Hash and MGFHash are set to the same thing this is not a requirement.
1680 * @access public
1681 * @param String $hash
1683 function setMGFHash($hash)
1685 // Crypt_Hash supports algorithms that PKCS#1 doesn't support. md5-96 and sha1-96, for example.
1686 switch ($hash) {
1687 case 'md2':
1688 case 'md5':
1689 case 'sha1':
1690 case 'sha256':
1691 case 'sha384':
1692 case 'sha512':
1693 $this->mgfHash = new Crypt_Hash($hash);
1694 break;
1695 default:
1696 $this->mgfHash = new Crypt_Hash('sha1');
1698 $this->mgfHLen = $this->mgfHash->getLength();
1702 * Determines the salt length
1704 * To quote from {@link http://tools.ietf.org/html/rfc3447#page-38 RFC3447#page-38}:
1706 * Typical salt lengths in octets are hLen (the length of the output
1707 * of the hash function Hash) and 0.
1709 * @access public
1710 * @param Integer $format
1712 function setSaltLength($sLen)
1714 $this->sLen = $sLen;
1718 * Generates a random string x bytes long
1720 * @access public
1721 * @param Integer $bytes
1722 * @param optional Integer $nonzero
1723 * @return String
1725 function _random($bytes, $nonzero = false)
1727 $temp = '';
1728 for ($i = 0; $i < $bytes; $i++) {
1729 $temp.= chr(crypt_random($nonzero, 255));
1731 return $temp;
1735 * Integer-to-Octet-String primitive
1737 * See {@link http://tools.ietf.org/html/rfc3447#section-4.1 RFC3447#section-4.1}.
1739 * @access private
1740 * @param Math_BigInteger $x
1741 * @param Integer $xLen
1742 * @return String
1744 function _i2osp($x, $xLen)
1746 $x = $x->toBytes();
1747 if (strlen($x) > $xLen) {
1748 user_error('Integer too large', E_USER_NOTICE);
1749 return false;
1751 return str_pad($x, $xLen, chr(0), STR_PAD_LEFT);
1755 * Octet-String-to-Integer primitive
1757 * See {@link http://tools.ietf.org/html/rfc3447#section-4.2 RFC3447#section-4.2}.
1759 * @access private
1760 * @param String $x
1761 * @return Math_BigInteger
1763 function _os2ip($x)
1765 return new Math_BigInteger($x, 256);
1769 * Exponentiate with or without Chinese Remainder Theorem
1771 * See {@link http://tools.ietf.org/html/rfc3447#section-5.1.1 RFC3447#section-5.1.2}.
1773 * @access private
1774 * @param Math_BigInteger $x
1775 * @return Math_BigInteger
1777 function _exponentiate($x)
1779 if (empty($this->primes) || empty($this->coefficients) || empty($this->exponents)) {
1780 return $x->modPow($this->exponent, $this->modulus);
1783 $num_primes = count($this->primes);
1785 if (defined('CRYPT_RSA_DISABLE_BLINDING')) {
1786 $m_i = array(
1787 1 => $x->modPow($this->exponents[1], $this->primes[1]),
1788 2 => $x->modPow($this->exponents[2], $this->primes[2])
1790 $h = $m_i[1]->subtract($m_i[2]);
1791 $h = $h->multiply($this->coefficients[2]);
1792 list(, $h) = $h->divide($this->primes[1]);
1793 $m = $m_i[2]->add($h->multiply($this->primes[2]));
1795 $r = $this->primes[1];
1796 for ($i = 3; $i <= $num_primes; $i++) {
1797 $m_i = $x->modPow($this->exponents[$i], $this->primes[$i]);
1799 $r = $r->multiply($this->primes[$i - 1]);
1801 $h = $m_i->subtract($m);
1802 $h = $h->multiply($this->coefficients[$i]);
1803 list(, $h) = $h->divide($this->primes[$i]);
1805 $m = $m->add($r->multiply($h));
1807 } else {
1808 $smallest = $this->primes[1];
1809 for ($i = 2; $i <= $num_primes; $i++) {
1810 if ($smallest->compare($this->primes[$i]) > 0) {
1811 $smallest = $this->primes[$i];
1815 $one = new Math_BigInteger(1);
1816 $one->setRandomGenerator('crypt_random');
1818 $r = $one->random($one, $smallest->subtract($one));
1820 $m_i = array(
1821 1 => $this->_blind($x, $r, 1),
1822 2 => $this->_blind($x, $r, 2)
1824 $h = $m_i[1]->subtract($m_i[2]);
1825 $h = $h->multiply($this->coefficients[2]);
1826 list(, $h) = $h->divide($this->primes[1]);
1827 $m = $m_i[2]->add($h->multiply($this->primes[2]));
1829 $r = $this->primes[1];
1830 for ($i = 3; $i <= $num_primes; $i++) {
1831 $m_i = $this->_blind($x, $r, $i);
1833 $r = $r->multiply($this->primes[$i - 1]);
1835 $h = $m_i->subtract($m);
1836 $h = $h->multiply($this->coefficients[$i]);
1837 list(, $h) = $h->divide($this->primes[$i]);
1839 $m = $m->add($r->multiply($h));
1843 return $m;
1847 * Performs RSA Blinding
1849 * Protects against timing attacks by employing RSA Blinding.
1850 * Returns $x->modPow($this->exponents[$i], $this->primes[$i])
1852 * @access private
1853 * @param Math_BigInteger $x
1854 * @param Math_BigInteger $r
1855 * @param Integer $i
1856 * @return Math_BigInteger
1858 function _blind($x, $r, $i)
1860 $x = $x->multiply($r->modPow($this->publicExponent, $this->primes[$i]));
1861 $x = $x->modPow($this->exponents[$i], $this->primes[$i]);
1863 $r = $r->modInverse($this->primes[$i]);
1864 $x = $x->multiply($r);
1865 list(, $x) = $x->divide($this->primes[$i]);
1867 return $x;
1871 * Performs blinded RSA equality testing
1873 * Protects against a particular type of timing attack described.
1875 * See {@link http://codahale.com/a-lesson-in-timing-attacks/ A Lesson In Timing Attacks (or, Don’t use MessageDigest.isEquals)}
1877 * Thanks for the heads up singpolyma!
1879 * @access private
1880 * @param String $x
1881 * @param String $y
1882 * @return Boolean
1884 function _equals($x, $y)
1886 if (strlen($x) != strlen($y)) {
1887 return false;
1890 $result = 0;
1891 for ($i = 0; $i < strlen($x); $i++) {
1892 $result |= ord($x[$i]) ^ ord($y[$i]);
1895 return $result == 0;
1899 * RSAEP
1901 * See {@link http://tools.ietf.org/html/rfc3447#section-5.1.1 RFC3447#section-5.1.1}.
1903 * @access private
1904 * @param Math_BigInteger $m
1905 * @return Math_BigInteger
1907 function _rsaep($m)
1909 if ($m->compare($this->zero) < 0 || $m->compare($this->modulus) > 0) {
1910 user_error('Message representative out of range', E_USER_NOTICE);
1911 return false;
1913 return $this->_exponentiate($m);
1917 * RSADP
1919 * See {@link http://tools.ietf.org/html/rfc3447#section-5.1.2 RFC3447#section-5.1.2}.
1921 * @access private
1922 * @param Math_BigInteger $c
1923 * @return Math_BigInteger
1925 function _rsadp($c)
1927 if ($c->compare($this->zero) < 0 || $c->compare($this->modulus) > 0) {
1928 user_error('Ciphertext representative out of range', E_USER_NOTICE);
1929 return false;
1931 return $this->_exponentiate($c);
1935 * RSASP1
1937 * See {@link http://tools.ietf.org/html/rfc3447#section-5.2.1 RFC3447#section-5.2.1}.
1939 * @access private
1940 * @param Math_BigInteger $m
1941 * @return Math_BigInteger
1943 function _rsasp1($m)
1945 if ($m->compare($this->zero) < 0 || $m->compare($this->modulus) > 0) {
1946 user_error('Message representative out of range', E_USER_NOTICE);
1947 return false;
1949 return $this->_exponentiate($m);
1953 * RSAVP1
1955 * See {@link http://tools.ietf.org/html/rfc3447#section-5.2.2 RFC3447#section-5.2.2}.
1957 * @access private
1958 * @param Math_BigInteger $s
1959 * @return Math_BigInteger
1961 function _rsavp1($s)
1963 if ($s->compare($this->zero) < 0 || $s->compare($this->modulus) > 0) {
1964 user_error('Signature representative out of range', E_USER_NOTICE);
1965 return false;
1967 return $this->_exponentiate($s);
1971 * MGF1
1973 * See {@link http://tools.ietf.org/html/rfc3447#appendix-B.2.1 RFC3447#appendix-B.2.1}.
1975 * @access private
1976 * @param String $mgfSeed
1977 * @param Integer $mgfLen
1978 * @return String
1980 function _mgf1($mgfSeed, $maskLen)
1982 // if $maskLen would yield strings larger than 4GB, PKCS#1 suggests a "Mask too long" error be output.
1984 $t = '';
1985 $count = ceil($maskLen / $this->mgfHLen);
1986 for ($i = 0; $i < $count; $i++) {
1987 $c = pack('N', $i);
1988 $t.= $this->mgfHash->hash($mgfSeed . $c);
1991 return substr($t, 0, $maskLen);
1995 * RSAES-OAEP-ENCRYPT
1997 * See {@link http://tools.ietf.org/html/rfc3447#section-7.1.1 RFC3447#section-7.1.1} and
1998 * {http://en.wikipedia.org/wiki/Optimal_Asymmetric_Encryption_Padding OAES}.
2000 * @access private
2001 * @param String $m
2002 * @param String $l
2003 * @return String
2005 function _rsaes_oaep_encrypt($m, $l = '')
2007 $mLen = strlen($m);
2009 // Length checking
2011 // if $l is larger than two million terrabytes and you're using sha1, PKCS#1 suggests a "Label too long" error
2012 // be output.
2014 if ($mLen > $this->k - 2 * $this->hLen - 2) {
2015 user_error('Message too long', E_USER_NOTICE);
2016 return false;
2019 // EME-OAEP encoding
2021 $lHash = $this->hash->hash($l);
2022 $ps = str_repeat(chr(0), $this->k - $mLen - 2 * $this->hLen - 2);
2023 $db = $lHash . $ps . chr(1) . $m;
2024 $seed = $this->_random($this->hLen);
2025 $dbMask = $this->_mgf1($seed, $this->k - $this->hLen - 1);
2026 $maskedDB = $db ^ $dbMask;
2027 $seedMask = $this->_mgf1($maskedDB, $this->hLen);
2028 $maskedSeed = $seed ^ $seedMask;
2029 $em = chr(0) . $maskedSeed . $maskedDB;
2031 // RSA encryption
2033 $m = $this->_os2ip($em);
2034 $c = $this->_rsaep($m);
2035 $c = $this->_i2osp($c, $this->k);
2037 // Output the ciphertext C
2039 return $c;
2043 * RSAES-OAEP-DECRYPT
2045 * See {@link http://tools.ietf.org/html/rfc3447#section-7.1.2 RFC3447#section-7.1.2}. The fact that the error
2046 * messages aren't distinguishable from one another hinders debugging, but, to quote from RFC3447#section-7.1.2:
2048 * Note. Care must be taken to ensure that an opponent cannot
2049 * distinguish the different error conditions in Step 3.g, whether by
2050 * error message or timing, or, more generally, learn partial
2051 * information about the encoded message EM. Otherwise an opponent may
2052 * be able to obtain useful information about the decryption of the
2053 * ciphertext C, leading to a chosen-ciphertext attack such as the one
2054 * observed by Manger [36].
2056 * As for $l... to quote from {@link http://tools.ietf.org/html/rfc3447#page-17 RFC3447#page-17}:
2058 * Both the encryption and the decryption operations of RSAES-OAEP take
2059 * the value of a label L as input. In this version of PKCS #1, L is
2060 * the empty string; other uses of the label are outside the scope of
2061 * this document.
2063 * @access private
2064 * @param String $c
2065 * @param String $l
2066 * @return String
2068 function _rsaes_oaep_decrypt($c, $l = '')
2070 // Length checking
2072 // if $l is larger than two million terrabytes and you're using sha1, PKCS#1 suggests a "Label too long" error
2073 // be output.
2075 if (strlen($c) != $this->k || $this->k < 2 * $this->hLen + 2) {
2076 user_error('Decryption error', E_USER_NOTICE);
2077 return false;
2080 // RSA decryption
2082 $c = $this->_os2ip($c);
2083 $m = $this->_rsadp($c);
2084 if ($m === false) {
2085 user_error('Decryption error', E_USER_NOTICE);
2086 return false;
2088 $em = $this->_i2osp($m, $this->k);
2090 // EME-OAEP decoding
2092 $lHash = $this->hash->hash($l);
2093 $y = ord($em[0]);
2094 $maskedSeed = substr($em, 1, $this->hLen);
2095 $maskedDB = substr($em, $this->hLen + 1);
2096 $seedMask = $this->_mgf1($maskedDB, $this->hLen);
2097 $seed = $maskedSeed ^ $seedMask;
2098 $dbMask = $this->_mgf1($seed, $this->k - $this->hLen - 1);
2099 $db = $maskedDB ^ $dbMask;
2100 $lHash2 = substr($db, 0, $this->hLen);
2101 $m = substr($db, $this->hLen);
2102 if ($lHash != $lHash2) {
2103 user_error('Decryption error', E_USER_NOTICE);
2104 return false;
2106 $m = ltrim($m, chr(0));
2107 if (ord($m[0]) != 1) {
2108 user_error('Decryption error', E_USER_NOTICE);
2109 return false;
2112 // Output the message M
2114 return substr($m, 1);
2118 * RSAES-PKCS1-V1_5-ENCRYPT
2120 * See {@link http://tools.ietf.org/html/rfc3447#section-7.2.1 RFC3447#section-7.2.1}.
2122 * @access private
2123 * @param String $m
2124 * @return String
2126 function _rsaes_pkcs1_v1_5_encrypt($m)
2128 $mLen = strlen($m);
2130 // Length checking
2132 if ($mLen > $this->k - 11) {
2133 user_error('Message too long', E_USER_NOTICE);
2134 return false;
2137 // EME-PKCS1-v1_5 encoding
2139 $ps = $this->_random($this->k - $mLen - 3, true);
2140 $em = chr(0) . chr(2) . $ps . chr(0) . $m;
2142 // RSA encryption
2143 $m = $this->_os2ip($em);
2144 $c = $this->_rsaep($m);
2145 $c = $this->_i2osp($c, $this->k);
2147 // Output the ciphertext C
2149 return $c;
2153 * RSAES-PKCS1-V1_5-DECRYPT
2155 * See {@link http://tools.ietf.org/html/rfc3447#section-7.2.2 RFC3447#section-7.2.2}.
2157 * For compatability purposes, this function departs slightly from the description given in RFC3447.
2158 * The reason being that RFC2313#section-8.1 (PKCS#1 v1.5) states that ciphertext's encrypted by the
2159 * private key should have the second byte set to either 0 or 1 and that ciphertext's encrypted by the
2160 * public key should have the second byte set to 2. In RFC3447 (PKCS#1 v2.1), the second byte is supposed
2161 * to be 2 regardless of which key is used. For compatability purposes, we'll just check to make sure the
2162 * second byte is 2 or less. If it is, we'll accept the decrypted string as valid.
2164 * As a consequence of this, a private key encrypted ciphertext produced with Crypt_RSA may not decrypt
2165 * with a strictly PKCS#1 v1.5 compliant RSA implementation. Public key encrypted ciphertext's should but
2166 * not private key encrypted ciphertext's.
2168 * @access private
2169 * @param String $c
2170 * @return String
2172 function _rsaes_pkcs1_v1_5_decrypt($c)
2174 // Length checking
2176 if (strlen($c) != $this->k) { // or if k < 11
2177 user_error('Decryption error', E_USER_NOTICE);
2178 return false;
2181 // RSA decryption
2183 $c = $this->_os2ip($c);
2184 $m = $this->_rsadp($c);
2186 if ($m === false) {
2187 user_error('Decryption error', E_USER_NOTICE);
2188 return false;
2190 $em = $this->_i2osp($m, $this->k);
2192 // EME-PKCS1-v1_5 decoding
2194 if (ord($em[0]) != 0 || ord($em[1]) > 2) {
2195 user_error('Decryption error', E_USER_NOTICE);
2196 return false;
2199 $ps = substr($em, 2, strpos($em, chr(0), 2) - 2);
2200 $m = substr($em, strlen($ps) + 3);
2202 if (strlen($ps) < 8) {
2203 user_error('Decryption error', E_USER_NOTICE);
2204 return false;
2207 // Output M
2209 return $m;
2213 * EMSA-PSS-ENCODE
2215 * See {@link http://tools.ietf.org/html/rfc3447#section-9.1.1 RFC3447#section-9.1.1}.
2217 * @access private
2218 * @param String $m
2219 * @param Integer $emBits
2221 function _emsa_pss_encode($m, $emBits)
2223 // if $m is larger than two million terrabytes and you're using sha1, PKCS#1 suggests a "Label too long" error
2224 // be output.
2226 $emLen = ($emBits + 1) >> 3; // ie. ceil($emBits / 8)
2227 $sLen = $this->sLen == false ? $this->hLen : $this->sLen;
2229 $mHash = $this->hash->hash($m);
2230 if ($emLen < $this->hLen + $sLen + 2) {
2231 user_error('Encoding error', E_USER_NOTICE);
2232 return false;
2235 $salt = $this->_random($sLen);
2236 $m2 = "\0\0\0\0\0\0\0\0" . $mHash . $salt;
2237 $h = $this->hash->hash($m2);
2238 $ps = str_repeat(chr(0), $emLen - $sLen - $this->hLen - 2);
2239 $db = $ps . chr(1) . $salt;
2240 $dbMask = $this->_mgf1($h, $emLen - $this->hLen - 1);
2241 $maskedDB = $db ^ $dbMask;
2242 $maskedDB[0] = ~chr(0xFF << ($emBits & 7)) & $maskedDB[0];
2243 $em = $maskedDB . $h . chr(0xBC);
2245 return $em;
2249 * EMSA-PSS-VERIFY
2251 * See {@link http://tools.ietf.org/html/rfc3447#section-9.1.2 RFC3447#section-9.1.2}.
2253 * @access private
2254 * @param String $m
2255 * @param String $em
2256 * @param Integer $emBits
2257 * @return String
2259 function _emsa_pss_verify($m, $em, $emBits)
2261 // if $m is larger than two million terrabytes and you're using sha1, PKCS#1 suggests a "Label too long" error
2262 // be output.
2264 $emLen = ($emBits + 1) >> 3; // ie. ceil($emBits / 8);
2265 $sLen = $this->sLen == false ? $this->hLen : $this->sLen;
2267 $mHash = $this->hash->hash($m);
2268 if ($emLen < $this->hLen + $sLen + 2) {
2269 return false;
2272 if ($em[strlen($em) - 1] != chr(0xBC)) {
2273 return false;
2276 $maskedDB = substr($em, 0, -$this->hLen - 1);
2277 $h = substr($em, -$this->hLen - 1, $this->hLen);
2278 $temp = chr(0xFF << ($emBits & 7));
2279 if ((~$maskedDB[0] & $temp) != $temp) {
2280 return false;
2282 $dbMask = $this->_mgf1($h, $emLen - $this->hLen - 1);
2283 $db = $maskedDB ^ $dbMask;
2284 $db[0] = ~chr(0xFF << ($emBits & 7)) & $db[0];
2285 $temp = $emLen - $this->hLen - $sLen - 2;
2286 if (substr($db, 0, $temp) != str_repeat(chr(0), $temp) || ord($db[$temp]) != 1) {
2287 return false;
2289 $salt = substr($db, $temp + 1); // should be $sLen long
2290 $m2 = "\0\0\0\0\0\0\0\0" . $mHash . $salt;
2291 $h2 = $this->hash->hash($m2);
2292 return $this->_equals($h, $h2);
2296 * RSASSA-PSS-SIGN
2298 * See {@link http://tools.ietf.org/html/rfc3447#section-8.1.1 RFC3447#section-8.1.1}.
2300 * @access private
2301 * @param String $m
2302 * @return String
2304 function _rsassa_pss_sign($m)
2306 // EMSA-PSS encoding
2308 $em = $this->_emsa_pss_encode($m, 8 * $this->k - 1);
2310 // RSA signature
2312 $m = $this->_os2ip($em);
2313 $s = $this->_rsasp1($m);
2314 $s = $this->_i2osp($s, $this->k);
2316 // Output the signature S
2318 return $s;
2322 * RSASSA-PSS-VERIFY
2324 * See {@link http://tools.ietf.org/html/rfc3447#section-8.1.2 RFC3447#section-8.1.2}.
2326 * @access private
2327 * @param String $m
2328 * @param String $s
2329 * @return String
2331 function _rsassa_pss_verify($m, $s)
2333 // Length checking
2335 if (strlen($s) != $this->k) {
2336 user_error('Invalid signature', E_USER_NOTICE);
2337 return false;
2340 // RSA verification
2342 $modBits = 8 * $this->k;
2344 $s2 = $this->_os2ip($s);
2345 $m2 = $this->_rsavp1($s2);
2346 if ($m2 === false) {
2347 user_error('Invalid signature', E_USER_NOTICE);
2348 return false;
2350 $em = $this->_i2osp($m2, $modBits >> 3);
2351 if ($em === false) {
2352 user_error('Invalid signature', E_USER_NOTICE);
2353 return false;
2356 // EMSA-PSS verification
2358 return $this->_emsa_pss_verify($m, $em, $modBits - 1);
2362 * EMSA-PKCS1-V1_5-ENCODE
2364 * See {@link http://tools.ietf.org/html/rfc3447#section-9.2 RFC3447#section-9.2}.
2366 * @access private
2367 * @param String $m
2368 * @param Integer $emLen
2369 * @return String
2371 function _emsa_pkcs1_v1_5_encode($m, $emLen)
2373 $h = $this->hash->hash($m);
2374 if ($h === false) {
2375 return false;
2378 // see http://tools.ietf.org/html/rfc3447#page-43
2379 switch ($this->hashName) {
2380 case 'md2':
2381 $t = pack('H*', '3020300c06082a864886f70d020205000410');
2382 break;
2383 case 'md5':
2384 $t = pack('H*', '3020300c06082a864886f70d020505000410');
2385 break;
2386 case 'sha1':
2387 $t = pack('H*', '3021300906052b0e03021a05000414');
2388 break;
2389 case 'sha256':
2390 $t = pack('H*', '3031300d060960864801650304020105000420');
2391 break;
2392 case 'sha384':
2393 $t = pack('H*', '3041300d060960864801650304020205000430');
2394 break;
2395 case 'sha512':
2396 $t = pack('H*', '3051300d060960864801650304020305000440');
2398 $t.= $h;
2399 $tLen = strlen($t);
2401 if ($emLen < $tLen + 11) {
2402 user_error('Intended encoded message length too short', E_USER_NOTICE);
2403 return false;
2406 $ps = str_repeat(chr(0xFF), $emLen - $tLen - 3);
2408 $em = "\0\1$ps\0$t";
2410 return $em;
2414 * RSASSA-PKCS1-V1_5-SIGN
2416 * See {@link http://tools.ietf.org/html/rfc3447#section-8.2.1 RFC3447#section-8.2.1}.
2418 * @access private
2419 * @param String $m
2420 * @return String
2422 function _rsassa_pkcs1_v1_5_sign($m)
2424 // EMSA-PKCS1-v1_5 encoding
2426 $em = $this->_emsa_pkcs1_v1_5_encode($m, $this->k);
2427 if ($em === false) {
2428 user_error('RSA modulus too short', E_USER_NOTICE);
2429 return false;
2432 // RSA signature
2434 $m = $this->_os2ip($em);
2435 $s = $this->_rsasp1($m);
2436 $s = $this->_i2osp($s, $this->k);
2438 // Output the signature S
2440 return $s;
2444 * RSASSA-PKCS1-V1_5-VERIFY
2446 * See {@link http://tools.ietf.org/html/rfc3447#section-8.2.2 RFC3447#section-8.2.2}.
2448 * @access private
2449 * @param String $m
2450 * @return String
2452 function _rsassa_pkcs1_v1_5_verify($m, $s)
2454 // Length checking
2456 if (strlen($s) != $this->k) {
2457 user_error('Invalid signature', E_USER_NOTICE);
2458 return false;
2461 // RSA verification
2463 $s = $this->_os2ip($s);
2464 $m2 = $this->_rsavp1($s);
2465 if ($m2 === false) {
2466 user_error('Invalid signature', E_USER_NOTICE);
2467 return false;
2469 $em = $this->_i2osp($m2, $this->k);
2470 if ($em === false) {
2471 user_error('Invalid signature', E_USER_NOTICE);
2472 return false;
2475 // EMSA-PKCS1-v1_5 encoding
2477 $em2 = $this->_emsa_pkcs1_v1_5_encode($m, $this->k);
2478 if ($em2 === false) {
2479 user_error('RSA modulus too short', E_USER_NOTICE);
2480 return false;
2483 // Compare
2485 return $this->_equals($em, $em2);
2489 * Set Encryption Mode
2491 * Valid values include CRYPT_RSA_ENCRYPTION_OAEP and CRYPT_RSA_ENCRYPTION_PKCS1.
2493 * @access public
2494 * @param Integer $mode
2496 function setEncryptionMode($mode)
2498 $this->encryptionMode = $mode;
2502 * Set Signature Mode
2504 * Valid values include CRYPT_RSA_SIGNATURE_PSS and CRYPT_RSA_SIGNATURE_PKCS1
2506 * @access public
2507 * @param Integer $mode
2509 function setSignatureMode($mode)
2511 $this->signatureMode = $mode;
2515 * Encryption
2517 * Both CRYPT_RSA_ENCRYPTION_OAEP and CRYPT_RSA_ENCRYPTION_PKCS1 both place limits on how long $plaintext can be.
2518 * If $plaintext exceeds those limits it will be broken up so that it does and the resultant ciphertext's will
2519 * be concatenated together.
2521 * @see decrypt()
2522 * @access public
2523 * @param String $plaintext
2524 * @return String
2526 function encrypt($plaintext)
2528 switch ($this->encryptionMode) {
2529 case CRYPT_RSA_ENCRYPTION_PKCS1:
2530 $length = $this->k - 11;
2531 if ($length <= 0) {
2532 return false;
2535 $plaintext = str_split($plaintext, $length);
2536 $ciphertext = '';
2537 foreach ($plaintext as $m) {
2538 $ciphertext.= $this->_rsaes_pkcs1_v1_5_encrypt($m);
2540 return $ciphertext;
2541 //case CRYPT_RSA_ENCRYPTION_OAEP:
2542 default:
2543 $length = $this->k - 2 * $this->hLen - 2;
2544 if ($length <= 0) {
2545 return false;
2548 $plaintext = str_split($plaintext, $length);
2549 $ciphertext = '';
2550 foreach ($plaintext as $m) {
2551 $ciphertext.= $this->_rsaes_oaep_encrypt($m);
2553 return $ciphertext;
2558 * Decryption
2560 * @see encrypt()
2561 * @access public
2562 * @param String $plaintext
2563 * @return String
2565 function decrypt($ciphertext)
2567 if ($this->k <= 0) {
2568 return false;
2571 $ciphertext = str_split($ciphertext, $this->k);
2572 $plaintext = '';
2574 switch ($this->encryptionMode) {
2575 case CRYPT_RSA_ENCRYPTION_PKCS1:
2576 $decrypt = '_rsaes_pkcs1_v1_5_decrypt';
2577 break;
2578 //case CRYPT_RSA_ENCRYPTION_OAEP:
2579 default:
2580 $decrypt = '_rsaes_oaep_decrypt';
2583 foreach ($ciphertext as $c) {
2584 $temp = $this->$decrypt($c);
2585 if ($temp === false) {
2586 return false;
2588 $plaintext.= $temp;
2591 return $plaintext;
2595 * Create a signature
2597 * @see verify()
2598 * @access public
2599 * @param String $message
2600 * @return String
2602 function sign($message)
2604 if (empty($this->modulus) || empty($this->exponent)) {
2605 return false;
2608 switch ($this->signatureMode) {
2609 case CRYPT_RSA_SIGNATURE_PKCS1:
2610 return $this->_rsassa_pkcs1_v1_5_sign($message);
2611 //case CRYPT_RSA_SIGNATURE_PSS:
2612 default:
2613 return $this->_rsassa_pss_sign($message);
2618 * Verifies a signature
2620 * @see sign()
2621 * @access public
2622 * @param String $message
2623 * @param String $signature
2624 * @return Boolean
2626 function verify($message, $signature)
2628 if (empty($this->modulus) || empty($this->exponent)) {
2629 return false;
2632 switch ($this->signatureMode) {
2633 case CRYPT_RSA_SIGNATURE_PKCS1:
2634 return $this->_rsassa_pkcs1_v1_5_verify($message, $signature);
2635 //case CRYPT_RSA_SIGNATURE_PSS:
2636 default:
2637 return $this->_rsassa_pss_verify($message, $signature);