12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693 |
- <?php
- if (!function_exists('crypt_random_string')) {
- require_once('Random.php');
- }
- if (!class_exists('Crypt_Hash')) {
- require_once('Hash.php');
- }
- define('CRYPT_RSA_ENCRYPTION_OAEP', 1);
- define('CRYPT_RSA_ENCRYPTION_PKCS1', 2);
- define('CRYPT_RSA_SIGNATURE_PSS', 1);
- define('CRYPT_RSA_SIGNATURE_PKCS1', 2);
- define('CRYPT_RSA_ASN1_INTEGER', 2);
- define('CRYPT_RSA_ASN1_BITSTRING', 3);
- define('CRYPT_RSA_ASN1_SEQUENCE', 48);
- define('CRYPT_RSA_MODE_INTERNAL', 1);
- define('CRYPT_RSA_MODE_OPENSSL', 2);
- define('CRYPT_RSA_OPENSSL_CONFIG', __DIR__.'/../openssl.cnf');
- define('CRYPT_RSA_PRIVATE_FORMAT_PKCS1', 0);
- define('CRYPT_RSA_PRIVATE_FORMAT_PUTTY', 1);
- define('CRYPT_RSA_PRIVATE_FORMAT_XML', 2);
- define('CRYPT_RSA_PUBLIC_FORMAT_RAW', 3);
- define('CRYPT_RSA_PUBLIC_FORMAT_PKCS1_RAW', 4);
- define('CRYPT_RSA_PUBLIC_FORMAT_XML', 5);
- define('CRYPT_RSA_PUBLIC_FORMAT_OPENSSH', 6);
- define('CRYPT_RSA_PUBLIC_FORMAT_PKCS1', 7);
- class Crypt_RSA {
-
- var $zero;
-
- var $one;
-
- var $privateKeyFormat = CRYPT_RSA_PRIVATE_FORMAT_PKCS1;
-
- var $publicKeyFormat = CRYPT_RSA_PUBLIC_FORMAT_PKCS1;
-
- var $modulus;
-
- var $k;
-
- var $exponent;
-
- var $primes;
-
- var $exponents;
-
- var $coefficients;
-
- var $hashName;
-
- var $hash;
-
- var $hLen;
-
- var $sLen;
-
- var $mgfHash;
-
- var $mgfHLen;
-
- var $encryptionMode = CRYPT_RSA_ENCRYPTION_OAEP;
-
- var $signatureMode = CRYPT_RSA_SIGNATURE_PSS;
-
- var $publicExponent = false;
-
- var $password = false;
-
- var $components = array();
-
- var $current;
-
- var $configFile;
-
- var $comment = 'phpseclib-generated-key';
-
- function Crypt_RSA()
- {
- if (!class_exists('Math_BigInteger')) {
- require_once('Math/BigInteger.php');
- }
- $this->configFile = CRYPT_RSA_OPENSSL_CONFIG;
- if ( !defined('CRYPT_RSA_MODE') ) {
- switch (true) {
- case extension_loaded('openssl') && version_compare(PHP_VERSION, '4.2.0', '>=') && file_exists($this->configFile):
- define('CRYPT_RSA_MODE', CRYPT_RSA_MODE_OPENSSL);
- break;
- default:
- define('CRYPT_RSA_MODE', CRYPT_RSA_MODE_INTERNAL);
- }
- }
- $this->zero = new Math_BigInteger();
- $this->one = new Math_BigInteger(1);
- $this->hash = new Crypt_Hash('sha1');
- $this->hLen = $this->hash->getLength();
- $this->hashName = 'sha1';
- $this->mgfHash = new Crypt_Hash('sha1');
- $this->mgfHLen = $this->mgfHash->getLength();
- }
-
- function createKey($bits = 1024, $timeout = false, $partial = array())
- {
- if (!defined('CRYPT_RSA_EXPONENT')) {
-
- define('CRYPT_RSA_EXPONENT', '65537');
- }
-
-
-
-
-
-
- if (!defined('CRYPT_RSA_SMALLEST_PRIME')) {
- define('CRYPT_RSA_SMALLEST_PRIME', 4096);
- }
-
- if ( CRYPT_RSA_MODE == CRYPT_RSA_MODE_OPENSSL && $bits >= 384 && CRYPT_RSA_EXPONENT == 65537) {
- $config = array();
- if (isset($this->configFile)) {
- $config['config'] = $this->configFile;
- }
- $rsa = openssl_pkey_new(array('private_key_bits' => $bits) + $config);
- openssl_pkey_export($rsa, $privatekey, NULL, $config);
- $publickey = openssl_pkey_get_details($rsa);
- $publickey = $publickey['key'];
- $privatekey = call_user_func_array(array($this, '_convertPrivateKey'), array_values($this->_parseKey($privatekey, CRYPT_RSA_PRIVATE_FORMAT_PKCS1)));
- $publickey = call_user_func_array(array($this, '_convertPublicKey'), array_values($this->_parseKey($publickey, CRYPT_RSA_PUBLIC_FORMAT_PKCS1)));
-
- while (openssl_error_string() !== false);
- return array(
- 'privatekey' => $privatekey,
- 'publickey' => $publickey,
- 'partialkey' => false
- );
- }
- static $e;
- if (!isset($e)) {
- $e = new Math_BigInteger(CRYPT_RSA_EXPONENT);
- }
- extract($this->_generateMinMax($bits));
- $absoluteMin = $min;
- $temp = $bits >> 1;
- if ($temp > CRYPT_RSA_SMALLEST_PRIME) {
- $num_primes = floor($bits / CRYPT_RSA_SMALLEST_PRIME);
- $temp = CRYPT_RSA_SMALLEST_PRIME;
- } else {
- $num_primes = 2;
- }
- extract($this->_generateMinMax($temp + $bits % $temp));
- $finalMax = $max;
- extract($this->_generateMinMax($temp));
- $generator = new Math_BigInteger();
- $n = $this->one->copy();
- if (!empty($partial)) {
- extract(unserialize($partial));
- } else {
- $exponents = $coefficients = $primes = array();
- $lcm = array(
- 'top' => $this->one->copy(),
- 'bottom' => false
- );
- }
- $start = time();
- $i0 = count($primes) + 1;
- do {
- for ($i = $i0; $i <= $num_primes; $i++) {
- if ($timeout !== false) {
- $timeout-= time() - $start;
- $start = time();
- if ($timeout <= 0) {
- return array(
- 'privatekey' => '',
- 'publickey' => '',
- 'partialkey' => serialize(array(
- 'primes' => $primes,
- 'coefficients' => $coefficients,
- 'lcm' => $lcm,
- 'exponents' => $exponents
- ))
- );
- }
- }
- if ($i == $num_primes) {
- list($min, $temp) = $absoluteMin->divide($n);
- if (!$temp->equals($this->zero)) {
- $min = $min->add($this->one);
- }
- $primes[$i] = $generator->randomPrime($min, $finalMax, $timeout);
- } else {
- $primes[$i] = $generator->randomPrime($min, $max, $timeout);
- }
- if ($primes[$i] === false) {
- if (count($primes) > 1) {
- $partialkey = '';
- } else {
- array_pop($primes);
- $partialkey = serialize(array(
- 'primes' => $primes,
- 'coefficients' => $coefficients,
- 'lcm' => $lcm,
- 'exponents' => $exponents
- ));
- }
- return array(
- 'privatekey' => '',
- 'publickey' => '',
- 'partialkey' => $partialkey
- );
- }
-
-
- if ($i > 2) {
- $coefficients[$i] = $n->modInverse($primes[$i]);
- }
- $n = $n->multiply($primes[$i]);
- $temp = $primes[$i]->subtract($this->one);
-
-
- $lcm['top'] = $lcm['top']->multiply($temp);
- $lcm['bottom'] = $lcm['bottom'] === false ? $temp : $lcm['bottom']->gcd($temp);
- $exponents[$i] = $e->modInverse($temp);
- }
- list($lcm) = $lcm['top']->divide($lcm['bottom']);
- $gcd = $lcm->gcd($e);
- $i0 = 1;
- } while (!$gcd->equals($this->one));
- $d = $e->modInverse($lcm);
- $coefficients[2] = $primes[2]->modInverse($primes[1]);
-
-
-
-
-
-
-
-
-
-
-
-
-
- return array(
- 'privatekey' => $this->_convertPrivateKey($n, $e, $d, $primes, $exponents, $coefficients),
- 'publickey' => $this->_convertPublicKey($n, $e),
- 'partialkey' => false
- );
- }
-
- function _convertPrivateKey($n, $e, $d, $primes, $exponents, $coefficients)
- {
- $num_primes = count($primes);
- $raw = array(
- 'version' => $num_primes == 2 ? chr(0) : chr(1),
- 'modulus' => $n->toBytes(true),
- 'publicExponent' => $e->toBytes(true),
- 'privateExponent' => $d->toBytes(true),
- 'prime1' => $primes[1]->toBytes(true),
- 'prime2' => $primes[2]->toBytes(true),
- 'exponent1' => $exponents[1]->toBytes(true),
- 'exponent2' => $exponents[2]->toBytes(true),
- 'coefficient' => $coefficients[2]->toBytes(true)
- );
-
-
- switch ($this->privateKeyFormat) {
- case CRYPT_RSA_PRIVATE_FORMAT_XML:
- if ($num_primes != 2) {
- return false;
- }
- return "<RSAKeyValue>\r\n" .
- ' <Modulus>' . base64_encode($raw['modulus']) . "</Modulus>\r\n" .
- ' <Exponent>' . base64_encode($raw['publicExponent']) . "</Exponent>\r\n" .
- ' <P>' . base64_encode($raw['prime1']) . "</P>\r\n" .
- ' <Q>' . base64_encode($raw['prime2']) . "</Q>\r\n" .
- ' <DP>' . base64_encode($raw['exponent1']) . "</DP>\r\n" .
- ' <DQ>' . base64_encode($raw['exponent2']) . "</DQ>\r\n" .
- ' <InverseQ>' . base64_encode($raw['coefficient']) . "</InverseQ>\r\n" .
- ' <D>' . base64_encode($raw['privateExponent']) . "</D>\r\n" .
- '</RSAKeyValue>';
- break;
- case CRYPT_RSA_PRIVATE_FORMAT_PUTTY:
- if ($num_primes != 2) {
- return false;
- }
- $key = "PuTTY-User-Key-File-2: ssh-rsa\r\nEncryption: ";
- $encryption = (!empty($this->password) || is_string($this->password)) ? 'aes256-cbc' : 'none';
- $key.= $encryption;
- $key.= "\r\nComment: " . $this->comment . "\r\n";
- $public = pack('Na*Na*Na*',
- strlen('ssh-rsa'), 'ssh-rsa', strlen($raw['publicExponent']), $raw['publicExponent'], strlen($raw['modulus']), $raw['modulus']
- );
- $source = pack('Na*Na*Na*Na*',
- strlen('ssh-rsa'), 'ssh-rsa', strlen($encryption), $encryption,
- strlen($this->comment), $this->comment, strlen($public), $public
- );
- $public = base64_encode($public);
- $key.= "Public-Lines: " . ((strlen($public) + 32) >> 6) . "\r\n";
- $key.= chunk_split($public, 64);
- $private = pack('Na*Na*Na*Na*',
- strlen($raw['privateExponent']), $raw['privateExponent'], strlen($raw['prime1']), $raw['prime1'],
- strlen($raw['prime2']), $raw['prime2'], strlen($raw['coefficient']), $raw['coefficient']
- );
- if (empty($this->password) && !is_string($this->password)) {
- $source.= pack('Na*', strlen($private), $private);
- $hashkey = 'putty-private-key-file-mac-key';
- } else {
- $private.= crypt_random_string(16 - (strlen($private) & 15));
- $source.= pack('Na*', strlen($private), $private);
- if (!class_exists('Crypt_AES')) {
- require_once('Crypt/AES.php');
- }
- $sequence = 0;
- $symkey = '';
- while (strlen($symkey) < 32) {
- $temp = pack('Na*', $sequence++, $this->password);
- $symkey.= pack('H*', sha1($temp));
- }
- $symkey = substr($symkey, 0, 32);
- $crypto = new Crypt_AES();
- $crypto->setKey($symkey);
- $crypto->disablePadding();
- $private = $crypto->encrypt($private);
- $hashkey = 'putty-private-key-file-mac-key' . $this->password;
- }
- $private = base64_encode($private);
- $key.= 'Private-Lines: ' . ((strlen($private) + 32) >> 6) . "\r\n";
- $key.= chunk_split($private, 64);
- if (!class_exists('Crypt_Hash')) {
- require_once('Crypt/Hash.php');
- }
- $hash = new Crypt_Hash('sha1');
- $hash->setKey(pack('H*', sha1($hashkey)));
- $key.= 'Private-MAC: ' . bin2hex($hash->hash($source)) . "\r\n";
- return $key;
- default:
- $components = array();
- foreach ($raw as $name => $value) {
- $components[$name] = pack('Ca*a*', CRYPT_RSA_ASN1_INTEGER, $this->_encodeLength(strlen($value)), $value);
- }
- $RSAPrivateKey = implode('', $components);
- if ($num_primes > 2) {
- $OtherPrimeInfos = '';
- for ($i = 3; $i <= $num_primes; $i++) {
-
-
-
-
-
-
-
- $OtherPrimeInfo = pack('Ca*a*', CRYPT_RSA_ASN1_INTEGER, $this->_encodeLength(strlen($primes[$i]->toBytes(true))), $primes[$i]->toBytes(true));
- $OtherPrimeInfo.= pack('Ca*a*', CRYPT_RSA_ASN1_INTEGER, $this->_encodeLength(strlen($exponents[$i]->toBytes(true))), $exponents[$i]->toBytes(true));
- $OtherPrimeInfo.= pack('Ca*a*', CRYPT_RSA_ASN1_INTEGER, $this->_encodeLength(strlen($coefficients[$i]->toBytes(true))), $coefficients[$i]->toBytes(true));
- $OtherPrimeInfos.= pack('Ca*a*', CRYPT_RSA_ASN1_SEQUENCE, $this->_encodeLength(strlen($OtherPrimeInfo)), $OtherPrimeInfo);
- }
- $RSAPrivateKey.= pack('Ca*a*', CRYPT_RSA_ASN1_SEQUENCE, $this->_encodeLength(strlen($OtherPrimeInfos)), $OtherPrimeInfos);
- }
- $RSAPrivateKey = pack('Ca*a*', CRYPT_RSA_ASN1_SEQUENCE, $this->_encodeLength(strlen($RSAPrivateKey)), $RSAPrivateKey);
- if (!empty($this->password) || is_string($this->password)) {
- $iv = crypt_random_string(8);
- $symkey = pack('H*', md5($this->password . $iv));
- $symkey.= substr(pack('H*', md5($symkey . $this->password . $iv)), 0, 8);
- if (!class_exists('Crypt_TripleDES')) {
- require_once('Crypt/TripleDES.php');
- }
- $des = new Crypt_TripleDES();
- $des->setKey($symkey);
- $des->setIV($iv);
- $iv = strtoupper(bin2hex($iv));
- $RSAPrivateKey = "-----BEGIN RSA PRIVATE KEY-----\r\n" .
- "Proc-Type: 4,ENCRYPTED\r\n" .
- "DEK-Info: DES-EDE3-CBC,$iv\r\n" .
- "\r\n" .
- chunk_split(base64_encode($des->encrypt($RSAPrivateKey)), 64) .
- '-----END RSA PRIVATE KEY-----';
- } else {
- $RSAPrivateKey = "-----BEGIN RSA PRIVATE KEY-----\r\n" .
- chunk_split(base64_encode($RSAPrivateKey), 64) .
- '-----END RSA PRIVATE KEY-----';
- }
- return $RSAPrivateKey;
- }
- }
-
- function _convertPublicKey($n, $e)
- {
- $modulus = $n->toBytes(true);
- $publicExponent = $e->toBytes(true);
- switch ($this->publicKeyFormat) {
- case CRYPT_RSA_PUBLIC_FORMAT_RAW:
- return array('e' => $e->copy(), 'n' => $n->copy());
- case CRYPT_RSA_PUBLIC_FORMAT_XML:
- return "<RSAKeyValue>\r\n" .
- ' <Modulus>' . base64_encode($modulus) . "</Modulus>\r\n" .
- ' <Exponent>' . base64_encode($publicExponent) . "</Exponent>\r\n" .
- '</RSAKeyValue>';
- break;
- case CRYPT_RSA_PUBLIC_FORMAT_OPENSSH:
-
-
-
-
- $RSAPublicKey = pack('Na*Na*Na*', strlen('ssh-rsa'), 'ssh-rsa', strlen($publicExponent), $publicExponent, strlen($modulus), $modulus);
- $RSAPublicKey = 'ssh-rsa ' . base64_encode($RSAPublicKey) . ' ' . $this->comment;
- return $RSAPublicKey;
- default:
-
-
-
-
-
- $components = array(
- 'modulus' => pack('Ca*a*', CRYPT_RSA_ASN1_INTEGER, $this->_encodeLength(strlen($modulus)), $modulus),
- 'publicExponent' => pack('Ca*a*', CRYPT_RSA_ASN1_INTEGER, $this->_encodeLength(strlen($publicExponent)), $publicExponent)
- );
- $RSAPublicKey = pack('Ca*a*a*',
- CRYPT_RSA_ASN1_SEQUENCE, $this->_encodeLength(strlen($components['modulus']) + strlen($components['publicExponent'])),
- $components['modulus'], $components['publicExponent']
- );
- if ($this->publicKeyFormat == CRYPT_RSA_PUBLIC_FORMAT_PKCS1) {
-
- $rsaOID = pack('H*', '300d06092a864886f70d0101010500');
- $RSAPublicKey = chr(0) . $RSAPublicKey;
- $RSAPublicKey = chr(3) . $this->_encodeLength(strlen($RSAPublicKey)) . $RSAPublicKey;
- $RSAPublicKey = pack('Ca*a*',
- CRYPT_RSA_ASN1_SEQUENCE, $this->_encodeLength(strlen($rsaOID . $RSAPublicKey)), $rsaOID . $RSAPublicKey
- );
- }
- $RSAPublicKey = "-----BEGIN PUBLIC KEY-----\r\n" .
- chunk_split(base64_encode($RSAPublicKey), 64) .
- '-----END PUBLIC KEY-----';
- return $RSAPublicKey;
- }
- }
-
- function _parseKey($key, $type)
- {
- if ($type != CRYPT_RSA_PUBLIC_FORMAT_RAW && !is_string($key)) {
- return false;
- }
- switch ($type) {
- case CRYPT_RSA_PUBLIC_FORMAT_RAW:
- if (!is_array($key)) {
- return false;
- }
- $components = array();
- switch (true) {
- case isset($key['e']):
- $components['publicExponent'] = $key['e']->copy();
- break;
- case isset($key['exponent']):
- $components['publicExponent'] = $key['exponent']->copy();
- break;
- case isset($key['publicExponent']):
- $components['publicExponent'] = $key['publicExponent']->copy();
- break;
- case isset($key[0]):
- $components['publicExponent'] = $key[0]->copy();
- }
- switch (true) {
- case isset($key['n']):
- $components['modulus'] = $key['n']->copy();
- break;
- case isset($key['modulo']):
- $components['modulus'] = $key['modulo']->copy();
- break;
- case isset($key['modulus']):
- $components['modulus'] = $key['modulus']->copy();
- break;
- case isset($key[1]):
- $components['modulus'] = $key[1]->copy();
- }
- return isset($components['modulus']) && isset($components['publicExponent']) ? $components : false;
- case CRYPT_RSA_PRIVATE_FORMAT_PKCS1:
- case CRYPT_RSA_PUBLIC_FORMAT_PKCS1:
-
- if (preg_match('#DEK-Info: (.+),(.+)#', $key, $matches)) {
- $iv = pack('H*', trim($matches[2]));
- $symkey = pack('H*', md5($this->password . substr($iv, 0, 8)));
- $symkey.= pack('H*', md5($symkey . $this->password . substr($iv, 0, 8)));
- $ciphertext = preg_replace('#.+(\r|\n|\r\n)\1|[\r\n]|-.+-| #s', '', $key);
- $ciphertext = preg_match('#^[a-zA-Z\d/+]*={0,2}$#', $ciphertext) ? base64_decode($ciphertext) : false;
- if ($ciphertext === false) {
- $ciphertext = $key;
- }
- switch ($matches[1]) {
- case 'AES-256-CBC':
- if (!class_exists('Crypt_AES')) {
- require_once('Crypt/AES.php');
- }
- $crypto = new Crypt_AES();
- break;
- case 'AES-128-CBC':
- if (!class_exists('Crypt_AES')) {
- require_once('Crypt/AES.php');
- }
- $symkey = substr($symkey, 0, 16);
- $crypto = new Crypt_AES();
- break;
- case 'DES-EDE3-CFB':
- if (!class_exists('Crypt_TripleDES')) {
- require_once('Crypt/TripleDES.php');
- }
- $crypto = new Crypt_TripleDES(CRYPT_DES_MODE_CFB);
- break;
- case 'DES-EDE3-CBC':
- if (!class_exists('Crypt_TripleDES')) {
- require_once('Crypt/TripleDES.php');
- }
- $symkey = substr($symkey, 0, 24);
- $crypto = new Crypt_TripleDES();
- break;
- case 'DES-CBC':
- if (!class_exists('Crypt_DES')) {
- require_once('Crypt/DES.php');
- }
- $crypto = new Crypt_DES();
- break;
- default:
- return false;
- }
- $crypto->setKey($symkey);
- $crypto->setIV($iv);
- $decoded = $crypto->decrypt($ciphertext);
- } else {
- $decoded = preg_replace('#-.+-|[\r\n]| #', '', $key);
- $decoded = preg_match('#^[a-zA-Z\d/+]*={0,2}$#', $decoded) ? base64_decode($decoded) : false;
- }
- if ($decoded !== false) {
- $key = $decoded;
- }
- $components = array();
- if (ord($this->_string_shift($key)) != CRYPT_RSA_ASN1_SEQUENCE) {
- return false;
- }
- if ($this->_decodeLength($key) != strlen($key)) {
- return false;
- }
- $tag = ord($this->_string_shift($key));
-
- if ($tag == CRYPT_RSA_ASN1_INTEGER && substr($key, 0, 3) == "\x01\x00\x30") {
- $this->_string_shift($key, 3);
- $tag = CRYPT_RSA_ASN1_SEQUENCE;
- }
- if ($tag == CRYPT_RSA_ASN1_SEQUENCE) {
-
- $this->_string_shift($key, $this->_decodeLength($key));
- $tag = ord($this->_string_shift($key));
- $this->_decodeLength($key);
-
-
-
- if ($tag == CRYPT_RSA_ASN1_BITSTRING) {
- $this->_string_shift($key);
- }
- if (ord($this->_string_shift($key)) != CRYPT_RSA_ASN1_SEQUENCE) {
- return false;
- }
- if ($this->_decodeLength($key) != strlen($key)) {
- return false;
- }
- $tag = ord($this->_string_shift($key));
- }
- if ($tag != CRYPT_RSA_ASN1_INTEGER) {
- return false;
- }
- $length = $this->_decodeLength($key);
- $temp = $this->_string_shift($key, $length);
- if (strlen($temp) != 1 || ord($temp) > 2) {
- $components['modulus'] = new Math_BigInteger($temp, 256);
- $this->_string_shift($key);
- $length = $this->_decodeLength($key);
- $components[$type == CRYPT_RSA_PUBLIC_FORMAT_PKCS1 ? 'publicExponent' : 'privateExponent'] = new Math_BigInteger($this->_string_shift($key, $length), 256);
- return $components;
- }
- if (ord($this->_string_shift($key)) != CRYPT_RSA_ASN1_INTEGER) {
- return false;
- }
- $length = $this->_decodeLength($key);
- $components['modulus'] = new Math_BigInteger($this->_string_shift($key, $length), 256);
- $this->_string_shift($key);
- $length = $this->_decodeLength($key);
- $components['publicExponent'] = new Math_BigInteger($this->_string_shift($key, $length), 256);
- $this->_string_shift($key);
- $length = $this->_decodeLength($key);
- $components['privateExponent'] = new Math_BigInteger($this->_string_shift($key, $length), 256);
- $this->_string_shift($key);
- $length = $this->_decodeLength($key);
- $components['primes'] = array(1 => new Math_BigInteger($this->_string_shift($key, $length), 256));
- $this->_string_shift($key);
- $length = $this->_decodeLength($key);
- $components['primes'][] = new Math_BigInteger($this->_string_shift($key, $length), 256);
- $this->_string_shift($key);
- $length = $this->_decodeLength($key);
- $components['exponents'] = array(1 => new Math_BigInteger($this->_string_shift($key, $length), 256));
- $this->_string_shift($key);
- $length = $this->_decodeLength($key);
- $components['exponents'][] = new Math_BigInteger($this->_string_shift($key, $length), 256);
- $this->_string_shift($key);
- $length = $this->_decodeLength($key);
- $components['coefficients'] = array(2 => new Math_BigInteger($this->_string_shift($key, $length), 256));
- if (!empty($key)) {
- if (ord($this->_string_shift($key)) != CRYPT_RSA_ASN1_SEQUENCE) {
- return false;
- }
- $this->_decodeLength($key);
- while (!empty($key)) {
- if (ord($this->_string_shift($key)) != CRYPT_RSA_ASN1_SEQUENCE) {
- return false;
- }
- $this->_decodeLength($key);
- $key = substr($key, 1);
- $length = $this->_decodeLength($key);
- $components['primes'][] = new Math_BigInteger($this->_string_shift($key, $length), 256);
- $this->_string_shift($key);
- $length = $this->_decodeLength($key);
- $components['exponents'][] = new Math_BigInteger($this->_string_shift($key, $length), 256);
- $this->_string_shift($key);
- $length = $this->_decodeLength($key);
- $components['coefficients'][] = new Math_BigInteger($this->_string_shift($key, $length), 256);
- }
- }
- return $components;
- case CRYPT_RSA_PUBLIC_FORMAT_OPENSSH:
- $parts = explode(' ', $key, 3);
- $key = isset($parts[1]) ? base64_decode($parts[1]) : false;
- if ($key === false) {
- return false;
- }
- $comment = isset($parts[2]) ? $parts[2] : false;
- $cleanup = substr($key, 0, 11) == "\0\0\0\7ssh-rsa";
- if (strlen($key) <= 4) {
- return false;
- }
- extract(unpack('Nlength', $this->_string_shift($key, 4)));
- $publicExponent = new Math_BigInteger($this->_string_shift($key, $length), -256);
- if (strlen($key) <= 4) {
- return false;
- }
- extract(unpack('Nlength', $this->_string_shift($key, 4)));
- $modulus = new Math_BigInteger($this->_string_shift($key, $length), -256);
- if ($cleanup && strlen($key)) {
- if (strlen($key) <= 4) {
- return false;
- }
- extract(unpack('Nlength', $this->_string_shift($key, 4)));
- $realModulus = new Math_BigInteger($this->_string_shift($key, $length), -256);
- return strlen($key) ? false : array(
- 'modulus' => $realModulus,
- 'publicExponent' => $modulus,
- 'comment' => $comment
- );
- } else {
- return strlen($key) ? false : array(
- 'modulus' => $modulus,
- 'publicExponent' => $publicExponent,
- 'comment' => $comment
- );
- }
-
-
- case CRYPT_RSA_PRIVATE_FORMAT_XML:
- case CRYPT_RSA_PUBLIC_FORMAT_XML:
- $this->components = array();
- $xml = xml_parser_create('UTF-8');
- xml_set_object($xml, $this);
- xml_set_element_handler($xml, '_start_element_handler', '_stop_element_handler');
- xml_set_character_data_handler($xml, '_data_handler');
-
- if (!xml_parse($xml, '<xml>' . $key . '</xml>')) {
- return false;
- }
- return isset($this->components['modulus']) && isset($this->components['publicExponent']) ? $this->components : false;
-
- case CRYPT_RSA_PRIVATE_FORMAT_PUTTY:
- $components = array();
- $key = preg_split('#\r\n|\r|\n#', $key);
- $type = trim(preg_replace('#PuTTY-User-Key-File-2: (.+)#', '$1', $key[0]));
- if ($type != 'ssh-rsa') {
- return false;
- }
- $encryption = trim(preg_replace('#Encryption: (.+)#', '$1', $key[1]));
- $comment = trim(preg_replace('#Comment: (.+)#', '$1', $key[2]));
- $publicLength = trim(preg_replace('#Public-Lines: (\d+)#', '$1', $key[3]));
- $public = base64_decode(implode('', array_map('trim', array_slice($key, 4, $publicLength))));
- $public = substr($public, 11);
- extract(unpack('Nlength', $this->_string_shift($public, 4)));
- $components['publicExponent'] = new Math_BigInteger($this->_string_shift($public, $length), -256);
- extract(unpack('Nlength', $this->_string_shift($public, 4)));
- $components['modulus'] = new Math_BigInteger($this->_string_shift($public, $length), -256);
- $privateLength = trim(preg_replace('#Private-Lines: (\d+)#', '$1', $key[$publicLength + 4]));
- $private = base64_decode(implode('', array_map('trim', array_slice($key, $publicLength + 5, $privateLength))));
- switch ($encryption) {
- case 'aes256-cbc':
- if (!class_exists('Crypt_AES')) {
- require_once('Crypt/AES.php');
- }
- $symkey = '';
- $sequence = 0;
- while (strlen($symkey) < 32) {
- $temp = pack('Na*', $sequence++, $this->password);
- $symkey.= pack('H*', sha1($temp));
- }
- $symkey = substr($symkey, 0, 32);
- $crypto = new Crypt_AES();
- }
- if ($encryption != 'none') {
- $crypto->setKey($symkey);
- $crypto->disablePadding();
- $private = $crypto->decrypt($private);
- if ($private === false) {
- return false;
- }
- }
- extract(unpack('Nlength', $this->_string_shift($private, 4)));
- if (strlen($private) < $length) {
- return false;
- }
- $components['privateExponent'] = new Math_BigInteger($this->_string_shift($private, $length), -256);
- extract(unpack('Nlength', $this->_string_shift($private, 4)));
- if (strlen($private) < $length) {
- return false;
- }
- $components['primes'] = array(1 => new Math_BigInteger($this->_string_shift($private, $length), -256));
- extract(unpack('Nlength', $this->_string_shift($private, 4)));
- if (strlen($private) < $length) {
- return false;
- }
- $components['primes'][] = new Math_BigInteger($this->_string_shift($private, $length), -256);
- $temp = $components['primes'][1]->subtract($this->one);
- $components['exponents'] = array(1 => $components['publicExponent']->modInverse($temp));
- $temp = $components['primes'][2]->subtract($this->one);
- $components['exponents'][] = $components['publicExponent']->modInverse($temp);
- extract(unpack('Nlength', $this->_string_shift($private, 4)));
- if (strlen($private) < $length) {
- return false;
- }
- $components['coefficients'] = array(2 => new Math_BigInteger($this->_string_shift($private, $length), -256));
- return $components;
- }
- }
-
- function getSize()
- {
- return !isset($this->modulus) ? 0 : strlen($this->modulus->toBits());
- }
-
- function _start_element_handler($parser, $name, $attribs)
- {
-
- switch ($name) {
- case 'MODULUS':
- $this->current = &$this->components['modulus'];
- break;
- case 'EXPONENT':
- $this->current = &$this->components['publicExponent'];
- break;
- case 'P':
- $this->current = &$this->components['primes'][1];
- break;
- case 'Q':
- $this->current = &$this->components['primes'][2];
- break;
- case 'DP':
- $this->current = &$this->components['exponents'][1];
- break;
- case 'DQ':
- $this->current = &$this->components['exponents'][2];
- break;
- case 'INVERSEQ':
- $this->current = &$this->components['coefficients'][2];
- break;
- case 'D':
- $this->current = &$this->components['privateExponent'];
- break;
- default:
- unset($this->current);
- }
- $this->current = '';
- }
-
- function _stop_element_handler($parser, $name)
- {
-
- if ($name == 'RSAKEYVALUE') {
- return;
- }
- $this->current = new Math_BigInteger(base64_decode($this->current), 256);
- }
-
- function _data_handler($parser, $data)
- {
- if (!isset($this->current) || is_object($this->current)) {
- return;
- }
- $this->current.= trim($data);
- }
-
- function loadKey($key, $type = false)
- {
- if ($type === false) {
- $types = array(
- CRYPT_RSA_PUBLIC_FORMAT_RAW,
- CRYPT_RSA_PRIVATE_FORMAT_PKCS1,
- CRYPT_RSA_PRIVATE_FORMAT_XML,
- CRYPT_RSA_PRIVATE_FORMAT_PUTTY,
- CRYPT_RSA_PUBLIC_FORMAT_OPENSSH
- );
- foreach ($types as $type) {
- $components = $this->_parseKey($key, $type);
- if ($components !== false) {
- break;
- }
- }
-
- } else {
- $components = $this->_parseKey($key, $type);
- }
- if ($components === false) {
- return false;
- }
- if (isset($components['comment']) && $components['comment'] !== false) {
- $this->comment = $components['comment'];
- }
- $this->modulus = $components['modulus'];
- $this->k = strlen($this->modulus->toBytes());
- $this->exponent = isset($components['privateExponent']) ? $components['privateExponent'] : $components['publicExponent'];
- if (isset($components['primes'])) {
- $this->primes = $components['primes'];
- $this->exponents = $components['exponents'];
- $this->coefficients = $components['coefficients'];
- $this->publicExponent = $components['publicExponent'];
- } else {
- $this->primes = array();
- $this->exponents = array();
- $this->coefficients = array();
- $this->publicExponent = false;
- }
- return true;
- }
-
- function setPassword($password = false)
- {
- $this->password = $password;
- }
-
- function setPublicKey($key = false, $type = false)
- {
- if ($key === false && !empty($this->modulus)) {
- $this->publicExponent = $this->exponent;
- return true;
- }
- if ($type === false) {
- $types = array(
- CRYPT_RSA_PUBLIC_FORMAT_RAW,
- CRYPT_RSA_PUBLIC_FORMAT_PKCS1,
- CRYPT_RSA_PUBLIC_FORMAT_XML,
- CRYPT_RSA_PUBLIC_FORMAT_OPENSSH
- );
- foreach ($types as $type) {
- $components = $this->_parseKey($key, $type);
- if ($components !== false) {
- break;
- }
- }
- } else {
- $components = $this->_parseKey($key, $type);
- }
- if ($components === false) {
- return false;
- }
- if (empty($this->modulus) || !$this->modulus->equals($components['modulus'])) {
- $this->modulus = $components['modulus'];
- $this->exponent = $this->publicExponent = $components['publicExponent'];
- return true;
- }
- $this->publicExponent = $components['publicExponent'];
- return true;
- }
-
- function getPublicKey($type = CRYPT_RSA_PUBLIC_FORMAT_PKCS1)
- {
- if (empty($this->modulus) || empty($this->publicExponent)) {
- return false;
- }
- $oldFormat = $this->publicKeyFormat;
- $this->publicKeyFormat = $type;
- $temp = $this->_convertPublicKey($this->modulus, $this->publicExponent);
- $this->publicKeyFormat = $oldFormat;
- return $temp;
- }
-
- function getPrivateKey($type = CRYPT_RSA_PUBLIC_FORMAT_PKCS1)
- {
- if (empty($this->primes)) {
- return false;
- }
- $oldFormat = $this->privateKeyFormat;
- $this->privateKeyFormat = $type;
- $temp = $this->_convertPrivateKey($this->modulus, $this->publicExponent, $this->exponent, $this->primes, $this->exponents, $this->coefficients);
- $this->privateKeyFormat = $oldFormat;
- return $temp;
- }
-
- function _getPrivatePublicKey($mode = CRYPT_RSA_PUBLIC_FORMAT_PKCS1)
- {
- if (empty($this->modulus) || empty($this->exponent)) {
- return false;
- }
- $oldFormat = $this->publicKeyFormat;
- $this->publicKeyFormat = $mode;
- $temp = $this->_convertPublicKey($this->modulus, $this->exponent);
- $this->publicKeyFormat = $oldFormat;
- return $temp;
- }
-
- function __toString()
- {
- $key = $this->getPrivateKey($this->privateKeyFormat);
- if ($key !== false) {
- return $key;
- }
- $key = $this->_getPrivatePublicKey($this->publicKeyFormat);
- return $key !== false ? $key : '';
- }
-
- function _generateMinMax($bits)
- {
- $bytes = $bits >> 3;
- $min = str_repeat(chr(0), $bytes);
- $max = str_repeat(chr(0xFF), $bytes);
- $msb = $bits & 7;
- if ($msb) {
- $min = chr(1 << ($msb - 1)) . $min;
- $max = chr((1 << $msb) - 1) . $max;
- } else {
- $min[0] = chr(0x80);
- }
- return array(
- 'min' => new Math_BigInteger($min, 256),
- 'max' => new Math_BigInteger($max, 256)
- );
- }
-
- function _decodeLength(&$string)
- {
- $length = ord($this->_string_shift($string));
- if ( $length & 0x80 ) {
- $length&= 0x7F;
- $temp = $this->_string_shift($string, $length);
- list(, $length) = unpack('N', substr(str_pad($temp, 4, chr(0), STR_PAD_LEFT), -4));
- }
- return $length;
- }
-
- function _encodeLength($length)
- {
- if ($length <= 0x7F) {
- return chr($length);
- }
- $temp = ltrim(pack('N', $length), chr(0));
- return pack('Ca*', 0x80 | strlen($temp), $temp);
- }
-
- function _string_shift(&$string, $index = 1)
- {
- $substr = substr($string, 0, $index);
- $string = substr($string, $index);
- return $substr;
- }
-
- function setPrivateKeyFormat($format)
- {
- $this->privateKeyFormat = $format;
- }
-
- function setPublicKeyFormat($format)
- {
- $this->publicKeyFormat = $format;
- }
-
- function setHash($hash)
- {
-
- switch ($hash) {
- case 'md2':
- case 'md5':
- case 'sha1':
- case 'sha256':
- case 'sha384':
- case 'sha512':
- $this->hash = new Crypt_Hash($hash);
- $this->hashName = $hash;
- break;
- default:
- $this->hash = new Crypt_Hash('sha1');
- $this->hashName = 'sha1';
- }
- $this->hLen = $this->hash->getLength();
- }
-
- function setMGFHash($hash)
- {
-
- switch ($hash) {
- case 'md2':
- case 'md5':
- case 'sha1':
- case 'sha256':
- case 'sha384':
- case 'sha512':
- $this->mgfHash = new Crypt_Hash($hash);
- break;
- default:
- $this->mgfHash = new Crypt_Hash('sha1');
- }
- $this->mgfHLen = $this->mgfHash->getLength();
- }
-
- function setSaltLength($sLen)
- {
- $this->sLen = $sLen;
- }
-
- function _i2osp($x, $xLen)
- {
- $x = $x->toBytes();
- if (strlen($x) > $xLen) {
- user_error('Integer too large');
- return false;
- }
- return str_pad($x, $xLen, chr(0), STR_PAD_LEFT);
- }
-
- function _os2ip($x)
- {
- return new Math_BigInteger($x, 256);
- }
-
- function _exponentiate($x)
- {
- if (empty($this->primes) || empty($this->coefficients) || empty($this->exponents)) {
- return $x->modPow($this->exponent, $this->modulus);
- }
- $num_primes = count($this->primes);
- if (defined('CRYPT_RSA_DISABLE_BLINDING')) {
- $m_i = array(
- 1 => $x->modPow($this->exponents[1], $this->primes[1]),
- 2 => $x->modPow($this->exponents[2], $this->primes[2])
- );
- $h = $m_i[1]->subtract($m_i[2]);
- $h = $h->multiply($this->coefficients[2]);
- list(, $h) = $h->divide($this->primes[1]);
- $m = $m_i[2]->add($h->multiply($this->primes[2]));
- $r = $this->primes[1];
- for ($i = 3; $i <= $num_primes; $i++) {
- $m_i = $x->modPow($this->exponents[$i], $this->primes[$i]);
- $r = $r->multiply($this->primes[$i - 1]);
- $h = $m_i->subtract($m);
- $h = $h->multiply($this->coefficients[$i]);
- list(, $h) = $h->divide($this->primes[$i]);
- $m = $m->add($r->multiply($h));
- }
- } else {
- $smallest = $this->primes[1];
- for ($i = 2; $i <= $num_primes; $i++) {
- if ($smallest->compare($this->primes[$i]) > 0) {
- $smallest = $this->primes[$i];
- }
- }
- $one = new Math_BigInteger(1);
- $r = $one->random($one, $smallest->subtract($one));
- $m_i = array(
- 1 => $this->_blind($x, $r, 1),
- 2 => $this->_blind($x, $r, 2)
- );
- $h = $m_i[1]->subtract($m_i[2]);
- $h = $h->multiply($this->coefficients[2]);
- list(, $h) = $h->divide($this->primes[1]);
- $m = $m_i[2]->add($h->multiply($this->primes[2]));
- $r = $this->primes[1];
- for ($i = 3; $i <= $num_primes; $i++) {
- $m_i = $this->_blind($x, $r, $i);
- $r = $r->multiply($this->primes[$i - 1]);
- $h = $m_i->subtract($m);
- $h = $h->multiply($this->coefficients[$i]);
- list(, $h) = $h->divide($this->primes[$i]);
- $m = $m->add($r->multiply($h));
- }
- }
- return $m;
- }
-
- function _blind($x, $r, $i)
- {
- $x = $x->multiply($r->modPow($this->publicExponent, $this->primes[$i]));
- $x = $x->modPow($this->exponents[$i], $this->primes[$i]);
- $r = $r->modInverse($this->primes[$i]);
- $x = $x->multiply($r);
- list(, $x) = $x->divide($this->primes[$i]);
- return $x;
- }
-
- function _equals($x, $y)
- {
- if (strlen($x) != strlen($y)) {
- return false;
- }
- $result = 0;
- for ($i = 0; $i < strlen($x); $i++) {
- $result |= ord($x[$i]) ^ ord($y[$i]);
- }
- return $result == 0;
- }
-
- function _rsaep($m)
- {
- if ($m->compare($this->zero) < 0 || $m->compare($this->modulus) > 0) {
- user_error('Message representative out of range');
- return false;
- }
- return $this->_exponentiate($m);
- }
-
- function _rsadp($c)
- {
- if ($c->compare($this->zero) < 0 || $c->compare($this->modulus) > 0) {
- user_error('Ciphertext representative out of range');
- return false;
- }
- return $this->_exponentiate($c);
- }
-
- function _rsasp1($m)
- {
- if ($m->compare($this->zero) < 0 || $m->compare($this->modulus) > 0) {
- user_error('Message representative out of range');
- return false;
- }
- return $this->_exponentiate($m);
- }
-
- function _rsavp1($s)
- {
- if ($s->compare($this->zero) < 0 || $s->compare($this->modulus) > 0) {
- user_error('Signature representative out of range');
- return false;
- }
- return $this->_exponentiate($s);
- }
-
- function _mgf1($mgfSeed, $maskLen)
- {
-
- $t = '';
- $count = ceil($maskLen / $this->mgfHLen);
- for ($i = 0; $i < $count; $i++) {
- $c = pack('N', $i);
- $t.= $this->mgfHash->hash($mgfSeed . $c);
- }
- return substr($t, 0, $maskLen);
- }
-
- function _rsaes_oaep_encrypt($m, $l = '')
- {
- $mLen = strlen($m);
-
-
-
- if ($mLen > $this->k - 2 * $this->hLen - 2) {
- user_error('Message too long');
- return false;
- }
-
- $lHash = $this->hash->hash($l);
- $ps = str_repeat(chr(0), $this->k - $mLen - 2 * $this->hLen - 2);
- $db = $lHash . $ps . chr(1) . $m;
- $seed = crypt_random_string($this->hLen);
- $dbMask = $this->_mgf1($seed, $this->k - $this->hLen - 1);
- $maskedDB = $db ^ $dbMask;
- $seedMask = $this->_mgf1($maskedDB, $this->hLen);
- $maskedSeed = $seed ^ $seedMask;
- $em = chr(0) . $maskedSeed . $maskedDB;
-
- $m = $this->_os2ip($em);
- $c = $this->_rsaep($m);
- $c = $this->_i2osp($c, $this->k);
-
- return $c;
- }
-
- function _rsaes_oaep_decrypt($c, $l = '')
- {
-
-
-
- if (strlen($c) != $this->k || $this->k < 2 * $this->hLen + 2) {
- user_error('Decryption error');
- return false;
- }
-
- $c = $this->_os2ip($c);
- $m = $this->_rsadp($c);
- if ($m === false) {
- user_error('Decryption error');
- return false;
- }
- $em = $this->_i2osp($m, $this->k);
-
- $lHash = $this->hash->hash($l);
- $y = ord($em[0]);
- $maskedSeed = substr($em, 1, $this->hLen);
- $maskedDB = substr($em, $this->hLen + 1);
- $seedMask = $this->_mgf1($maskedDB, $this->hLen);
- $seed = $maskedSeed ^ $seedMask;
- $dbMask = $this->_mgf1($seed, $this->k - $this->hLen - 1);
- $db = $maskedDB ^ $dbMask;
- $lHash2 = substr($db, 0, $this->hLen);
- $m = substr($db, $this->hLen);
- if ($lHash != $lHash2) {
- user_error('Decryption error');
- return false;
- }
- $m = ltrim($m, chr(0));
- if (ord($m[0]) != 1) {
- user_error('Decryption error');
- return false;
- }
-
- return substr($m, 1);
- }
-
- function _rsaes_pkcs1_v1_5_encrypt($m)
- {
- $mLen = strlen($m);
-
- if ($mLen > $this->k - 11) {
- user_error('Message too long');
- return false;
- }
-
- $psLen = $this->k - $mLen - 3;
- $ps = '';
- while (strlen($ps) != $psLen) {
- $temp = crypt_random_string($psLen - strlen($ps));
- $temp = str_replace("\x00", '', $temp);
- $ps.= $temp;
- }
- $type = 2;
-
- if (defined('CRYPT_RSA_PKCS15_COMPAT') && (!isset($this->publicExponent) || $this->exponent !== $this->publicExponent)) {
- $type = 1;
-
- $ps = str_repeat("\xFF", $psLen);
- }
- $em = chr(0) . chr($type) . $ps . chr(0) . $m;
-
- $m = $this->_os2ip($em);
- $c = $this->_rsaep($m);
- $c = $this->_i2osp($c, $this->k);
-
- return $c;
- }
-
- function _rsaes_pkcs1_v1_5_decrypt($c)
- {
-
- if (strlen($c) != $this->k) {
- user_error('Decryption error');
- return false;
- }
-
- $c = $this->_os2ip($c);
- $m = $this->_rsadp($c);
- if ($m === false) {
- user_error('Decryption error');
- return false;
- }
- $em = $this->_i2osp($m, $this->k);
-
- if (ord($em[0]) != 0 || ord($em[1]) > 2) {
- user_error('Decryption error');
- return false;
- }
- $ps = substr($em, 2, strpos($em, chr(0), 2) - 2);
- $m = substr($em, strlen($ps) + 3);
- if (strlen($ps) < 8) {
- user_error('Decryption error');
- return false;
- }
-
- return $m;
- }
-
- function _emsa_pss_encode($m, $emBits)
- {
-
-
- $emLen = ($emBits + 1) >> 3;
- $sLen = $this->sLen == false ? $this->hLen : $this->sLen;
- $mHash = $this->hash->hash($m);
- if ($emLen < $this->hLen + $sLen + 2) {
- user_error('Encoding error');
- return false;
- }
- $salt = crypt_random_string($sLen);
- $m2 = "\0\0\0\0\0\0\0\0" . $mHash . $salt;
- $h = $this->hash->hash($m2);
- $ps = str_repeat(chr(0), $emLen - $sLen - $this->hLen - 2);
- $db = $ps . chr(1) . $salt;
- $dbMask = $this->_mgf1($h, $emLen - $this->hLen - 1);
- $maskedDB = $db ^ $dbMask;
- $maskedDB[0] = ~chr(0xFF << ($emBits & 7)) & $maskedDB[0];
- $em = $maskedDB . $h . chr(0xBC);
- return $em;
- }
-
- function _emsa_pss_verify($m, $em, $emBits)
- {
-
-
- $emLen = ($emBits + 1) >> 3;
- $sLen = $this->sLen == false ? $this->hLen : $this->sLen;
- $mHash = $this->hash->hash($m);
- if ($emLen < $this->hLen + $sLen + 2) {
- return false;
- }
- if ($em[strlen($em) - 1] != chr(0xBC)) {
- return false;
- }
- $maskedDB = substr($em, 0, -$this->hLen - 1);
- $h = substr($em, -$this->hLen - 1, $this->hLen);
- $temp = chr(0xFF << ($emBits & 7));
- if ((~$maskedDB[0] & $temp) != $temp) {
- return false;
- }
- $dbMask = $this->_mgf1($h, $emLen - $this->hLen - 1);
- $db = $maskedDB ^ $dbMask;
- $db[0] = ~chr(0xFF << ($emBits & 7)) & $db[0];
- $temp = $emLen - $this->hLen - $sLen - 2;
- if (substr($db, 0, $temp) != str_repeat(chr(0), $temp) || ord($db[$temp]) != 1) {
- return false;
- }
- $salt = substr($db, $temp + 1);
- $m2 = "\0\0\0\0\0\0\0\0" . $mHash . $salt;
- $h2 = $this->hash->hash($m2);
- return $this->_equals($h, $h2);
- }
-
- function _rsassa_pss_sign($m)
- {
-
- $em = $this->_emsa_pss_encode($m, 8 * $this->k - 1);
-
- $m = $this->_os2ip($em);
- $s = $this->_rsasp1($m);
- $s = $this->_i2osp($s, $this->k);
-
- return $s;
- }
-
- function _rsassa_pss_verify($m, $s)
- {
-
- if (strlen($s) != $this->k) {
- user_error('Invalid signature');
- return false;
- }
-
- $modBits = 8 * $this->k;
- $s2 = $this->_os2ip($s);
- $m2 = $this->_rsavp1($s2);
- if ($m2 === false) {
- user_error('Invalid signature');
- return false;
- }
- $em = $this->_i2osp($m2, $modBits >> 3);
- if ($em === false) {
- user_error('Invalid signature');
- return false;
- }
-
- return $this->_emsa_pss_verify($m, $em, $modBits - 1);
- }
-
- function _emsa_pkcs1_v1_5_encode($m, $emLen)
- {
- $h = $this->hash->hash($m);
- if ($h === false) {
- return false;
- }
-
- switch ($this->hashName) {
- case 'md2':
- $t = pack('H*', '3020300c06082a864886f70d020205000410');
- break;
- case 'md5':
- $t = pack('H*', '3020300c06082a864886f70d020505000410');
- break;
- case 'sha1':
- $t = pack('H*', '3021300906052b0e03021a05000414');
- break;
- case 'sha256':
- $t = pack('H*', '3031300d060960864801650304020105000420');
- break;
- case 'sha384':
- $t = pack('H*', '3041300d060960864801650304020205000430');
- break;
- case 'sha512':
- $t = pack('H*', '3051300d060960864801650304020305000440');
- }
- $t.= $h;
- $tLen = strlen($t);
- if ($emLen < $tLen + 11) {
- user_error('Intended encoded message length too short');
- return false;
- }
- $ps = str_repeat(chr(0xFF), $emLen - $tLen - 3);
- $em = "\0\1$ps\0$t";
- return $em;
- }
-
- function _rsassa_pkcs1_v1_5_sign($m)
- {
-
- $em = $this->_emsa_pkcs1_v1_5_encode($m, $this->k);
- if ($em === false) {
- user_error('RSA modulus too short');
- return false;
- }
-
- $m = $this->_os2ip($em);
- $s = $this->_rsasp1($m);
- $s = $this->_i2osp($s, $this->k);
-
- return $s;
- }
-
- function _rsassa_pkcs1_v1_5_verify($m, $s)
- {
-
- if (strlen($s) != $this->k) {
- user_error('Invalid signature');
- return false;
- }
-
- $s = $this->_os2ip($s);
- $m2 = $this->_rsavp1($s);
- if ($m2 === false) {
- user_error('Invalid signature');
- return false;
- }
- $em = $this->_i2osp($m2, $this->k);
- if ($em === false) {
- user_error('Invalid signature');
- return false;
- }
-
- $em2 = $this->_emsa_pkcs1_v1_5_encode($m, $this->k);
- if ($em2 === false) {
- user_error('RSA modulus too short');
- return false;
- }
-
- return $this->_equals($em, $em2);
- }
-
- function setEncryptionMode($mode)
- {
- $this->encryptionMode = $mode;
- }
-
- function setSignatureMode($mode)
- {
- $this->signatureMode = $mode;
- }
-
- function setComment($comment)
- {
- $this->comment = $comment;
- }
-
- function getComment()
- {
- return $this->comment;
- }
-
- function encrypt($plaintext)
- {
- switch ($this->encryptionMode) {
- case CRYPT_RSA_ENCRYPTION_PKCS1:
- $length = $this->k - 11;
- if ($length <= 0) {
- return false;
- }
- $plaintext = str_split($plaintext, $length);
- $ciphertext = '';
- foreach ($plaintext as $m) {
- $ciphertext.= $this->_rsaes_pkcs1_v1_5_encrypt($m);
- }
- return $ciphertext;
-
- default:
- $length = $this->k - 2 * $this->hLen - 2;
- if ($length <= 0) {
- return false;
- }
- $plaintext = str_split($plaintext, $length);
- $ciphertext = '';
- foreach ($plaintext as $m) {
- $ciphertext.= $this->_rsaes_oaep_encrypt($m);
- }
- return $ciphertext;
- }
- }
-
- function decrypt($ciphertext)
- {
- if ($this->k <= 0) {
- return false;
- }
- $ciphertext = str_split($ciphertext, $this->k);
- $ciphertext[count($ciphertext) - 1] = str_pad($ciphertext[count($ciphertext) - 1], $this->k, chr(0), STR_PAD_LEFT);
- $plaintext = '';
- switch ($this->encryptionMode) {
- case CRYPT_RSA_ENCRYPTION_PKCS1:
- $decrypt = '_rsaes_pkcs1_v1_5_decrypt';
- break;
-
- default:
- $decrypt = '_rsaes_oaep_decrypt';
- }
- foreach ($ciphertext as $c) {
- $temp = $this->$decrypt($c);
- if ($temp === false) {
- return false;
- }
- $plaintext.= $temp;
- }
- return $plaintext;
- }
-
- function sign($message)
- {
- if (empty($this->modulus) || empty($this->exponent)) {
- return false;
- }
- switch ($this->signatureMode) {
- case CRYPT_RSA_SIGNATURE_PKCS1:
- return $this->_rsassa_pkcs1_v1_5_sign($message);
-
- default:
- return $this->_rsassa_pss_sign($message);
- }
- }
-
- function verify($message, $signature)
- {
- if (empty($this->modulus) || empty($this->exponent)) {
- return false;
- }
- switch ($this->signatureMode) {
- case CRYPT_RSA_SIGNATURE_PKCS1:
- return $this->_rsassa_pkcs1_v1_5_verify($message, $signature);
-
- default:
- return $this->_rsassa_pss_verify($message, $signature);
- }
- }
- }
|