| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251 |
- <?php
- namespace phpseclib\Crypt;
- use ParagonIE\ConstantTime\Base64;
- use phpseclib\File\ASN1;
- use phpseclib\Math\BigInteger;
- class RSA
- {
-
-
- const PADDING_OAEP = 1;
-
- const PADDING_PKCS1 = 2;
-
- const PADDING_NONE = 3;
-
- const PADDING_PKCS15_COMPAT = 6;
-
-
-
- const PADDING_PSS = 4;
-
- const PADDING_RELAXED_PKCS1 = 5;
-
-
-
- const ASN1_INTEGER = 2;
-
- const ASN1_BITSTRING = 3;
-
- const ASN1_OCTETSTRING = 4;
-
- const ASN1_OBJECT = 6;
-
- const ASN1_SEQUENCE = 48;
-
-
-
- const MODE_INTERNAL = 1;
-
- const MODE_OPENSSL = 2;
-
-
- static $zero;
-
- static $one;
-
- var $privateKeyFormat = 'PKCS1';
-
- var $publicKeyFormat = 'PKCS8';
-
- 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 $publicExponent = false;
-
- var $password = false;
-
- var $format = false;
-
- static $configFile;
-
- static $fileFormats = false;
-
- static $origFileFormats = false;
-
- static function _initialize_static_variables()
- {
- if (!isset(self::$zero)) {
- self::$zero= new BigInteger(0);
- self::$one = new BigInteger(1);
- self::$configFile = __DIR__ . '/../openssl.cnf';
- if (self::$fileFormats === false) {
- self::$fileFormats = array();
- foreach (glob(__DIR__ . '/RSA/*.php') as $file) {
- $name = pathinfo($file, PATHINFO_FILENAME);
- $type = 'phpseclib\Crypt\RSA\\' . $name;
- $meta = new \ReflectionClass($type);
- if (!$meta->isAbstract()) {
- self::$fileFormats[strtolower($name)] = $type;
- self::$origFileFormats[] = $name;
- }
- }
- }
- }
- }
-
- function __construct()
- {
- self::_initialize_static_variables();
- $this->hash = new Hash('sha256');
- $this->hLen = $this->hash->getLength();
- $this->hashName = 'sha256';
- $this->mgfHash = new Hash('sha256');
- $this->mgfHLen = $this->mgfHash->getLength();
- }
-
- static function createKey($bits = 2048, $timeout = false, $partial = array())
- {
- self::_initialize_static_variables();
- if (!defined('CRYPT_RSA_MODE')) {
- switch (true) {
-
-
-
- case defined('MATH_BIGINTEGER_OPENSSL_DISABLE'):
- define('CRYPT_RSA_MODE', self::MODE_INTERNAL);
- break;
- case extension_loaded('openssl') && file_exists(self::$configFile):
- define('CRYPT_RSA_MODE', self::MODE_OPENSSL);
- break;
- default:
- define('CRYPT_RSA_MODE', self::MODE_INTERNAL);
- }
- }
- 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 == self::MODE_OPENSSL && $bits >= 384 && CRYPT_RSA_EXPONENT == 65537) {
- $config = array();
- if (isset(self::$configFile)) {
- $config['config'] = self::$configFile;
- }
- $rsa = openssl_pkey_new(array('private_key_bits' => $bits) + $config);
- openssl_pkey_export($rsa, $privatekeystr, null, $config);
- $privatekey = new RSA();
- $privatekey->load($privatekeystr);
- $publickeyarr = openssl_pkey_get_details($rsa);
- $publickey = new RSA();
- $publickey->load($publickeyarr['key']);
-
- while (openssl_error_string() !== false) {
- }
- return array(
- 'privatekey' => $privatekey,
- 'publickey' => $publickey,
- 'partialkey' => false
- );
- }
- static $e;
- if (!isset($e)) {
- $e = new BigInteger(CRYPT_RSA_EXPONENT);
- }
- extract(self::_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(self::_generateMinMax($temp + $bits % $temp));
- $finalMax = $max;
- extract(self::_generateMinMax($temp));
- $n = clone self::$one;
- if (!empty($partial)) {
- extract(unserialize($partial));
- } else {
- $exponents = $coefficients = $primes = array();
- $lcm = array(
- 'top' => clone self::$one,
- '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(self::$zero)) {
- $min = $min->add(self::$one);
- }
- $primes[$i] = BigInteger::randomPrime($min, $finalMax, $timeout);
- } else {
- $primes[$i] = BigInteger::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' => false,
- 'publickey' => false,
- 'partialkey' => $partialkey
- );
- }
-
-
- if ($i > 2) {
- $coefficients[$i] = $n->modInverse($primes[$i]);
- }
- $n = $n->multiply($primes[$i]);
- $temp = $primes[$i]->subtract(self::$one);
-
-
- $lcm['top'] = $lcm['top']->multiply($temp);
- $lcm['bottom'] = $lcm['bottom'] === false ? $temp : $lcm['bottom']->gcd($temp);
- $exponents[$i] = $e->modInverse($temp);
- }
- list($temp) = $lcm['top']->divide($lcm['bottom']);
- $gcd = $temp->gcd($e);
- $i0 = 1;
- } while (!$gcd->equals(self::$one));
- $d = $e->modInverse($temp);
- $coefficients[2] = $primes[2]->modInverse($primes[1]);
-
-
-
-
-
-
-
-
-
-
-
-
-
- $privatekey = new RSA();
- $privatekey->modulus = $n;
- $privatekey->k = $bits >> 3;
- $privatekey->publicExponent = $e;
- $privatekey->exponent = $d;
- $privatekey->privateExponent = $e;
- $privatekey->primes = $primes;
- $privatekey->exponents = $exponents;
- $privatekey->coefficients = $coefficients;
- $publickey = new RSA();
- $publickey->modulus = $n;
- $publickey->k = $bits >> 3;
- $publickey->exponent = $e;
- return array(
- 'privatekey' => $privatekey,
- 'publickey' => $publickey,
- 'partialkey' => false
- );
- }
-
- static function addFileFormat($fullname)
- {
- self::_initialize_static_variables();
- if (class_exists($fullname)) {
- $meta = new \ReflectionClass($path);
- $shortname = $meta->getShortName();
- self::$fileFormats[strtolower($shortname)] = $fullname;
- self::$origFileFormats[] = $shortname;
- }
- }
-
- static function getSupportedFormats()
- {
- self::_initialize_static_variables();
- return self::$origFileFormats;
- }
-
- function load($key, $type = false)
- {
- if ($key instanceof RSA) {
- $this->privateKeyFormat = $key->privateKeyFormat;
- $this->publicKeyFormat = $key->publicKeyFormat;
- $this->k = $key->k;
- $this->hLen = $key->hLen;
- $this->sLen = $key->sLen;
- $this->mgfHLen = $key->mgfHLen;
- $this->password = $key->password;
- if (is_object($key->hash)) {
- $this->hash = new Hash($key->hash->getHash());
- }
- if (is_object($key->mgfHash)) {
- $this->mgfHash = new Hash($key->mgfHash->getHash());
- }
- if (is_object($key->modulus)) {
- $this->modulus = clone $key->modulus;
- }
- if (is_object($key->exponent)) {
- $this->exponent = clone $key->exponent;
- }
- if (is_object($key->publicExponent)) {
- $this->publicExponent = clone $key->publicExponent;
- }
- $this->primes = array();
- $this->exponents = array();
- $this->coefficients = array();
- foreach ($this->primes as $prime) {
- $this->primes[] = clone $prime;
- }
- foreach ($this->exponents as $exponent) {
- $this->exponents[] = clone $exponent;
- }
- foreach ($this->coefficients as $coefficient) {
- $this->coefficients[] = clone $coefficient;
- }
- return true;
- }
- $components = false;
- if ($type === false) {
- foreach (self::$fileFormats as $format) {
- try {
- $components = $format::load($key, $this->password);
- } catch (\Exception $e) {
- $components = false;
- }
- if ($components !== false) {
- break;
- }
- }
- } else {
- $format = strtolower($type);
- if (isset(self::$fileFormats[$format])) {
- $format = self::$fileFormats[$format];
- try {
- $components = $format::load($key, $this->password);
- } catch (\Exception $e) {
- $components = false;
- }
- }
- }
- if ($components === false) {
- $this->format = false;
- return false;
- }
- $this->format = $format;
- $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;
- }
- if ($components['isPublicKey']) {
- $this->setPublicKey();
- }
- return true;
- }
-
- function getLoadedFormat()
- {
- if ($this->format === false) {
- return false;
- }
- $meta = new \ReflectionClass($this->format);
- return $meta->getShortName();
- }
-
- function getPrivateKey($type = 'PKCS1')
- {
- $type = strtolower($type);
- if (!isset(self::$fileFormats[$type])) {
- return false;
- }
- $type = self::$fileFormats[$type];
- if (!method_exists($type, 'savePrivateKey')) {
- return false;
- }
- if (empty($this->primes)) {
- return false;
- }
- $oldFormat = $this->privateKeyFormat;
- $this->privateKeyFormat = $type;
- $temp = $type::savePrivateKey($this->modulus, $this->publicExponent, $this->exponent, $this->primes, $this->exponents, $this->coefficients, $this->password);
- $this->privateKeyFormat = $oldFormat;
- return $temp;
- }
-
- function getSize()
- {
- return !isset($this->modulus) ? 0 : strlen($this->modulus->toBits());
- }
-
- function setPassword($password = false)
- {
- $this->password = $password;
- }
-
- function setPublicKey($key = false, $type = false)
- {
-
- if (!empty($this->publicExponent)) {
- return false;
- }
- if ($key === false && !empty($this->modulus)) {
- $this->publicExponent = $this->exponent;
- return true;
- }
- $components = false;
- if ($type === false) {
- foreach (self::$fileFormats as $format) {
- if (!method_exists($format, 'savePublicKey')) {
- continue;
- }
- try {
- $components = $format::load($key, $this->password);
- } catch (\Exception $e) {
- $components = false;
- }
- if ($components !== false) {
- break;
- }
- }
- } else {
- $format = strtolower($type);
- if (isset(self::$fileFormats[$format])) {
- $format = self::$fileFormats[$format];
- try {
- $components = $format::load($key, $this->password);
- } catch (\Exception $e) {
- $components = false;
- }
- }
- }
- if ($components === false) {
- $this->format = false;
- return false;
- }
- $this->format = $format;
- 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 setPrivateKey($key = false, $type = false)
- {
- if ($key === false && !empty($this->publicExponent)) {
- $this->publicExponent = false;
- return true;
- }
- $rsa = new RSA();
- if (!$rsa->load($key, $type)) {
- return false;
- }
- $rsa->publicExponent = false;
-
- $this->load($rsa);
- return true;
- }
-
- function getPublicKey($type = 'PKCS8')
- {
- $type = strtolower($type);
- if (!isset(self::$fileFormats[$type])) {
- return false;
- }
- $type = self::$fileFormats[$type];
- if (!method_exists($type, 'savePublicKey')) {
- return false;
- }
- if (empty($this->modulus) || empty($this->publicExponent)) {
- return false;
- }
- $oldFormat = $this->publicKeyFormat;
- $this->publicKeyFormat = $type;
- $temp = $type::savePublicKey($this->modulus, $this->publicExponent);
- $this->publicKeyFormat = $oldFormat;
- return $temp;
- }
-
- function getPublicKeyFingerprint($algorithm = 'md5')
- {
- if (empty($this->modulus) || empty($this->publicExponent)) {
- return false;
- }
- $modulus = $this->modulus->toBytes(true);
- $publicExponent = $this->publicExponent->toBytes(true);
- $RSAPublicKey = pack('Na*Na*Na*', strlen('ssh-rsa'), 'ssh-rsa', strlen($publicExponent), $publicExponent, strlen($modulus), $modulus);
- switch ($algorithm) {
- case 'sha256':
- $hash = new Hash('sha256');
- $base = Base64::encode($hash->hash($RSAPublicKey));
- return substr($base, 0, strlen($base) - 1);
- case 'md5':
- return substr(chunk_split(md5($RSAPublicKey), 2, ':'), 0, -1);
- default:
- return false;
- }
- }
-
- function _getPrivatePublicKey($type = 'PKCS8')
- {
- $type = strtolower($type);
- if (!isset(self::$fileFormats[$type])) {
- return false;
- }
- $type = self::$fileFormats[$type];
- if (!method_exists($type, 'savePublicKey')) {
- return false;
- }
- if (empty($this->modulus) || empty($this->exponent)) {
- return false;
- }
- $oldFormat = $this->publicKeyFormat;
- $this->publicKeyFormat = $type;
- $temp = $type::savePublicKey($this->modulus, $this->exponent);
- $this->publicKeyFormat = $oldFormat;
- return $temp;
- }
-
- function __toString()
- {
- $key = $this->getPrivateKey($this->privateKeyFormat);
- if (is_string($key)) {
- return $key;
- }
- $key = $this->_getPrivatePublicKey($this->publicKeyFormat);
- return is_string($key) ? $key : '';
- }
-
- function __clone()
- {
- $key = new RSA();
- $key->load($this);
- return $key;
- }
-
- static 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 BigInteger($min, 256),
- 'max' => new 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':
- case 'sha224':
- case 'sha512/224':
- case 'sha512/256':
- $this->hash = new Hash($hash);
- $this->hashName = $hash;
- break;
- default:
- $this->hash = new Hash('sha256');
- $this->hashName = 'sha256';
- }
- $this->hLen = $this->hash->getLength();
- }
-
- function setMGFHash($hash)
- {
-
- switch ($hash) {
- case 'md2':
- case 'md5':
- case 'sha1':
- case 'sha256':
- case 'sha384':
- case 'sha512':
- case 'sha224':
- case 'sha512/224':
- case 'sha512/256':
- $this->mgfHash = new Hash($hash);
- break;
- default:
- $this->mgfHash = new Hash('sha256');
- }
- $this->mgfHLen = $this->mgfHash->getLength();
- }
-
- function setSaltLength($sLen)
- {
- $this->sLen = $sLen;
- }
-
- function _i2osp($x, $xLen)
- {
- if ($x === false) {
- return false;
- }
- $x = $x->toBytes();
- if (strlen($x) > $xLen) {
- return false;
- }
- return str_pad($x, $xLen, chr(0), STR_PAD_LEFT);
- }
-
- function _os2ip($x)
- {
- return new BigInteger($x, 256);
- }
-
- function _exponentiate($x)
- {
- switch (true) {
- case empty($this->primes):
- case $this->primes[1]->equals(self::$zero):
- case empty($this->coefficients):
- case $this->coefficients[2]->equals(self::$zero):
- case empty($this->exponents):
- case $this->exponents[1]->equals(self::$zero):
- 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];
- }
- }
- $r = BigInteger::random(self::$one, $smallest->subtract(self::$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(self::$zero) < 0 || $m->compare($this->modulus) > 0) {
- return false;
- }
- return $this->_exponentiate($m);
- }
-
- function _rsadp($c)
- {
- if ($c->compare(self::$zero) < 0 || $c->compare($this->modulus) > 0) {
- return false;
- }
- return $this->_exponentiate($c);
- }
-
- function _rsasp1($m)
- {
- if ($m->compare(self::$zero) < 0 || $m->compare($this->modulus) > 0) {
- return false;
- }
- return $this->_exponentiate($m);
- }
-
- function _rsavp1($s)
- {
- if ($s->compare(self::$zero) < 0 || $s->compare($this->modulus) > 0) {
- 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) {
- throw new \OutOfBoundsException('Message too long');
- }
-
- $lHash = $this->hash->hash($l);
- $ps = str_repeat(chr(0), $this->k - $mLen - 2 * $this->hLen - 2);
- $db = $lHash . $ps . chr(1) . $m;
- $seed = 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) {
- return false;
- }
-
- $c = $this->_os2ip($c);
- $m = $this->_rsadp($c);
- $em = $this->_i2osp($m, $this->k);
- if ($em === false) {
- return false;
- }
-
- $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) {
- return false;
- }
- $m = ltrim($m, chr(0));
- if (ord($m[0]) != 1) {
- return false;
- }
-
- return substr($m, 1);
- }
-
- function _raw_encrypt($m)
- {
- if (strlen($m) > $this->k) {
- throw new \OutOfBoundsException('Message too long');
- }
- $temp = $this->_os2ip($m);
- $temp = $this->_rsaep($temp);
- return $this->_i2osp($temp, $this->k);
- }
-
- function _rsaes_pkcs1_v1_5_encrypt($m, $pkcs15_compat = false)
- {
- $mLen = strlen($m);
-
- if ($mLen > $this->k - 11) {
- throw new \OutOfBoundsException('Message too long');
- }
-
- $psLen = $this->k - $mLen - 3;
- $ps = '';
- while (strlen($ps) != $psLen) {
- $temp = Random::string($psLen - strlen($ps));
- $temp = str_replace("\x00", '', $temp);
- $ps.= $temp;
- }
- $type = 2;
-
- if ($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) {
- return false;
- }
-
- $c = $this->_os2ip($c);
- $m = $this->_rsadp($c);
- $em = $this->_i2osp($m, $this->k);
- if ($em === false) {
- return false;
- }
-
- if (ord($em[0]) != 0 || ord($em[1]) > 2) {
- return false;
- }
- $ps = substr($em, 2, strpos($em, chr(0), 2) - 2);
- $m = substr($em, strlen($ps) + 3);
- if (strlen($ps) < 8) {
- return false;
- }
-
- return $m;
- }
-
- function _emsa_pss_encode($m, $emBits)
- {
-
-
- $emLen = ($emBits + 1) >> 3;
- $sLen = $this->sLen ? $this->sLen : $this->hLen;
- $mHash = $this->hash->hash($m);
- if ($emLen < $this->hLen + $sLen + 2) {
- return false;
- }
- $salt = Random::string($sLen);
- $m2 = "\0\0\0\0\0\0\0\0" . $mHash . $salt;
- $h = $this->hash->hash($m2);
- $ps = str_repeat(chr(0), $emLen - $sLen - $this->hLen - 2);
- $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 ? $this->sLen : $this->hLen;
- $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) {
- return false;
- }
-
- $modBits = 8 * $this->k;
- $s2 = $this->_os2ip($s);
- $m2 = $this->_rsavp1($s2);
- $em = $this->_i2osp($m2, $modBits >> 3);
- if ($em === false) {
- return false;
- }
-
- return $this->_emsa_pss_verify($m, $em, $modBits - 1);
- }
-
- function _emsa_pkcs1_v1_5_encode($m, $emLen)
- {
- $h = $this->hash->hash($m);
-
- switch ($this->hashName) {
- case 'md2':
- $t = "\x30\x20\x30\x0c\x06\x08\x2a\x86\x48\x86\xf7\x0d\x02\x02\x05\x00\x04\x10";
- break;
- case 'md5':
- $t = "\x30\x20\x30\x0c\x06\x08\x2a\x86\x48\x86\xf7\x0d\x02\x05\x05\x00\x04\x10";
- break;
- case 'sha1':
- $t = "\x30\x21\x30\x09\x06\x05\x2b\x0e\x03\x02\x1a\x05\x00\x04\x14";
- break;
- case 'sha256':
- $t = "\x30\x31\x30\x0d\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x01\x05\x00\x04\x20";
- break;
- case 'sha384':
- $t = "\x30\x41\x30\x0d\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x02\x05\x00\x04\x30";
- break;
- case 'sha512':
- $t = "\x30\x51\x30\x0d\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x03\x05\x00\x04\x40";
- break;
-
- case 'sha224':
- $t = "\x30\x2d\x30\x0d\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x04\x05\x00\x04\x1c";
- break;
- case 'sha512/224':
- $t = "\x30\x2d\x30\x0d\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x05\x05\x00\x04\x1c";
- break;
- case 'sha512/256':
- $t = "\x30\x31\x30\x0d\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x06\x05\x00\x04\x20";
- }
- $t.= $h;
- $tLen = strlen($t);
- if ($emLen < $tLen + 11) {
- throw new \LengthException('Intended encoded message length too short');
- }
- $ps = str_repeat(chr(0xFF), $emLen - $tLen - 3);
- $em = "\0\1$ps\0$t";
- return $em;
- }
-
- function _rsassa_pkcs1_v1_5_sign($m)
- {
-
-
-
- try {
- $em = $this->_emsa_pkcs1_v1_5_encode($m, $this->k);
- } catch (\LengthException $e) {
- throw new \LengthException('RSA modulus too short');
- }
-
- $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) {
- return false;
- }
-
- $s = $this->_os2ip($s);
- $m2 = $this->_rsavp1($s);
- $em = $this->_i2osp($m2, $this->k);
- if ($em === false) {
- return false;
- }
-
-
-
- try {
- $em2 = $this->_emsa_pkcs1_v1_5_encode($m, $this->k);
- } catch (\LengthException $e) {
- throw new \LengthException('RSA modulus too short');
- }
-
- return $this->_equals($em, $em2);
- }
-
- function _rsassa_pkcs1_v1_5_relaxed_verify($m, $s)
- {
-
- if (strlen($s) != $this->k) {
- return false;
- }
-
- $s = $this->_os2ip($s);
- $m2 = $this->_rsavp1($s);
- if ($m2 === false) {
- return false;
- }
- $em = $this->_i2osp($m2, $this->k);
- if ($em === false) {
- return false;
- }
- if ($this->_string_shift($em, 2) != "\0\1") {
- return false;
- }
- $em = ltrim($em, "\xFF");
- if ($this->_string_shift($em) != "\0") {
- return false;
- }
- $asn1 = new ASN1();
- $decoded = $asn1->decodeBER($em);
- if (!is_array($decoded) || empty($decoded[0]) || strlen($em) > $decoded[0]['length']) {
- return false;
- }
- $AlgorithmIdentifier = array(
- 'type' => ASN1::TYPE_SEQUENCE,
- 'children' => array(
- 'algorithm' => array('type' => ASN1::TYPE_OBJECT_IDENTIFIER),
- 'parameters' => array(
- 'type' => ASN1::TYPE_ANY,
- 'optional' => true
- )
- )
- );
- $DigestInfo = array(
- 'type' => ASN1::TYPE_SEQUENCE,
- 'children' => array(
- 'digestAlgorithm' => $AlgorithmIdentifier,
- 'digest' => array('type' => ASN1::TYPE_OCTET_STRING)
- )
- );
- $oids = array(
- '1.2.840.113549.2.2' => 'md2',
- '1.2.840.113549.2.4' => 'md4',
- '1.2.840.113549.2.5' => 'md5',
- '1.3.14.3.2.26' => 'sha1',
- '2.16.840.1.101.3.4.2.1' => 'sha256',
- '2.16.840.1.101.3.4.2.2' => 'sha384',
- '2.16.840.1.101.3.4.2.3' => 'sha512',
-
- '2.16.840.1.101.3.4.2.4' => 'sha224',
- '2.16.840.1.101.3.4.2.5' => 'sha512/224',
- '2.16.840.1.101.3.4.2.6' => 'sha512/256',
- );
- $asn1->loadOIDs($oids);
- $decoded = $asn1->asn1map($decoded[0], $DigestInfo);
- if (!isset($decoded) || $decoded === false) {
- return false;
- }
- if (!in_array($decoded['digestAlgorithm']['algorithm'], $oids)) {
- return false;
- }
- $hash = new Hash($decoded['digestAlgorithm']['algorithm']);
- $em = $hash->hash($m);
- $em2 = Base64::decode($decoded['digest']);
- return $this->_equals($em, $em2);
- }
-
- function encrypt($plaintext, $padding = self::PADDING_OAEP)
- {
- switch ($padding) {
- case self::PADDING_NONE:
- return $this->_raw_encrypt($plaintext);
- case self::PADDING_PKCS15_COMPAT:
- case self::PADDING_PKCS1:
- return $this->_rsaes_pkcs1_v1_5_encrypt($plaintext, $padding == self::PADDING_PKCS15_COMPAT);
-
- default:
- return $this->_rsaes_oaep_encrypt($plaintext);
- }
- }
-
- function decrypt($ciphertext, $padding = self::PADDING_OAEP)
- {
- switch ($padding) {
- case self::PADDING_NONE:
- return $this->_raw_encrypt($ciphertext);
- case self::PADDING_PKCS1:
- return $this->_rsaes_pkcs1_v1_5_decrypt($ciphertext);
-
- default:
- return $this->_rsaes_oaep_decrypt($ciphertext);
- }
- }
-
- function sign($message, $padding = self::PADDING_PSS)
- {
- if (empty($this->modulus) || empty($this->exponent)) {
- return false;
- }
- switch ($padding) {
- case self::PADDING_PKCS1:
- case self::PADDING_RELAXED_PKCS1:
- return $this->_rsassa_pkcs1_v1_5_sign($message);
-
- default:
- return $this->_rsassa_pss_sign($message);
- }
- }
-
- function verify($message, $signature, $padding = self::PADDING_PSS)
- {
- if (empty($this->modulus) || empty($this->exponent)) {
- return false;
- }
- switch ($padding) {
- case self::PADDING_RELAXED_PKCS1:
- return $this->_rsassa_pkcs1_v1_5_relaxed_verify($message, $signature);
- case self::PADDING_PKCS1:
- return $this->_rsassa_pkcs1_v1_5_verify($message, $signature);
-
- default:
- return $this->_rsassa_pss_verify($message, $signature);
- }
- }
- }
|