コード例 #1
0
ファイル: DSA.php プロジェクト: horde/horde
 /**
  * Generate a number that lies between 0 and q-1.
  *
  * @param \phpseclib\Math\BigInteger $q  Max number.
  *
  * @return \phpseclib\Math\BigInteger  Generated number.
  */
 public static function randomNumber($q)
 {
     $bytes = strlen($q->toBytes()) + 8;
     $ints = $bytes + 1 >> 2;
     $cstring = Crypt\Random::String($ints);
     $random = '';
     for ($i = 0; $i < $ints; ++$i) {
         $random .= pack('N', $cstring[$i]);
     }
     $c = new BigInteger(substr($random, 0, $bytes), 256);
     $one = new BigInteger(1);
     $result_base = $c->divide($q->subtract($one));
     return $result_base[1]->add($one);
 }
コード例 #2
0
 /**
  * Descrypts encrypted text
  *
  * @param string $ciphertext Text to decrypt
  * @return string Decrypted text or DECRYPTION_FAILED in case of failure
  */
 public static function decrypt($ciphertext)
 {
     $rsa = new RSA();
     $rsa->setEncryptionMode(RSA::ENCRYPTION_PKCS1);
     $rsa->loadKey(static::getPrivateKey());
     $s = new BigInteger($ciphertext, 16);
     // prevent library error output appearing in the dashboard
     set_error_handler(function () {
         /* ignore errors */
     });
     $cleartext = $rsa->decrypt($s->toBytes());
     restore_error_handler();
     return $cleartext;
 }
コード例 #3
0
ファイル: ASN1.php プロジェクト: BozzaCoon/SPHERE-Framework
 /**
  * ASN.1 Encode (Helper function)
  *
  * @param String  $source
  * @param String  $mapping
  * @param Integer $idx
  *
  * @return String
  * @access private
  */
 function _encode_der($source, $mapping, $idx = null, $special = array())
 {
     if ($source instanceof Element) {
         return $source->element;
     }
     // do not encode (implicitly optional) fields with value set to default
     if (isset($mapping['default']) && $source === $mapping['default']) {
         return '';
     }
     if (isset($idx)) {
         if (isset($special[$idx])) {
             $source = call_user_func($special[$idx], $source);
         }
         $this->location[] = $idx;
     }
     $tag = $mapping['type'];
     switch ($tag) {
         case self::TYPE_SET:
             // Children order is not important, thus process in sequence.
         // Children order is not important, thus process in sequence.
         case self::TYPE_SEQUENCE:
             $tag |= 0x20;
             // set the constructed bit
             $value = '';
             // ignore the min and max
             if (isset($mapping['min']) && isset($mapping['max'])) {
                 $child = $mapping['children'];
                 foreach ($source as $content) {
                     $temp = $this->_encode_der($content, $child, null, $special);
                     if ($temp === false) {
                         return false;
                     }
                     $value .= $temp;
                 }
                 break;
             }
             foreach ($mapping['children'] as $key => $child) {
                 if (!array_key_exists($key, $source)) {
                     if (!isset($child['optional'])) {
                         return false;
                     }
                     continue;
                 }
                 $temp = $this->_encode_der($source[$key], $child, $key, $special);
                 if ($temp === false) {
                     return false;
                 }
                 // An empty child encoding means it has been optimized out.
                 // Else we should have at least one tag byte.
                 if ($temp === '') {
                     continue;
                 }
                 // if isset($child['constant']) is true then isset($child['optional']) should be true as well
                 if (isset($child['constant'])) {
                     /*
                       From X.680-0207.pdf#page=58 (30.6):
                     
                       "The tagging construction specifies explicit tagging if any of the following holds:
                        ...
                        c) the "Tag Type" alternative is used and the value of "TagDefault" for the module is IMPLICIT TAGS or
                        AUTOMATIC TAGS, but the type defined by "Type" is an untagged choice type, an untagged open type, or
                        an untagged "DummyReference" (see ITU-T Rec. X.683 | ISO/IEC 8824-4, 8.3)."
                     */
                     if (isset($child['explicit']) || $child['type'] == self::TYPE_CHOICE) {
                         $subtag = chr(self::CLASS_CONTEXT_SPECIFIC << 6 | 0x20 | $child['constant']);
                         $temp = $subtag . $this->_encodeLength(strlen($temp)) . $temp;
                     } else {
                         $subtag = chr(self::CLASS_CONTEXT_SPECIFIC << 6 | ord($temp[0]) & 0x20 | $child['constant']);
                         $temp = $subtag . substr($temp, 1);
                     }
                 }
                 $value .= $temp;
             }
             break;
         case self::TYPE_CHOICE:
             $temp = false;
             foreach ($mapping['children'] as $key => $child) {
                 if (!isset($source[$key])) {
                     continue;
                 }
                 $temp = $this->_encode_der($source[$key], $child, $key, $special);
                 if ($temp === false) {
                     return false;
                 }
                 // An empty child encoding means it has been optimized out.
                 // Else we should have at least one tag byte.
                 if ($temp === '') {
                     continue;
                 }
                 $tag = ord($temp[0]);
                 // if isset($child['constant']) is true then isset($child['optional']) should be true as well
                 if (isset($child['constant'])) {
                     if (isset($child['explicit']) || $child['type'] == self::TYPE_CHOICE) {
                         $subtag = chr(self::CLASS_CONTEXT_SPECIFIC << 6 | 0x20 | $child['constant']);
                         $temp = $subtag . $this->_encodeLength(strlen($temp)) . $temp;
                     } else {
                         $subtag = chr(self::CLASS_CONTEXT_SPECIFIC << 6 | ord($temp[0]) & 0x20 | $child['constant']);
                         $temp = $subtag . substr($temp, 1);
                     }
                 }
             }
             if (isset($idx)) {
                 array_pop($this->location);
             }
             if ($temp && isset($mapping['cast'])) {
                 $temp[0] = chr($mapping['class'] << 6 | $tag & 0x20 | $mapping['cast']);
             }
             return $temp;
         case self::TYPE_INTEGER:
         case self::TYPE_ENUMERATED:
             if (!isset($mapping['mapping'])) {
                 if (is_numeric($source)) {
                     $source = new BigInteger($source);
                 }
                 $value = $source->toBytes(true);
             } else {
                 $value = array_search($source, $mapping['mapping']);
                 if ($value === false) {
                     return false;
                 }
                 $value = new BigInteger($value);
                 $value = $value->toBytes(true);
             }
             if (!strlen($value)) {
                 $value = chr(0);
             }
             break;
         case self::TYPE_UTC_TIME:
         case self::TYPE_GENERALIZED_TIME:
             $format = $mapping['type'] == self::TYPE_UTC_TIME ? 'y' : 'Y';
             $format .= 'mdHis';
             $value = @gmdate($format, strtotime($source)) . 'Z';
             break;
         case self::TYPE_BIT_STRING:
             if (isset($mapping['mapping'])) {
                 $bits = array_fill(0, count($mapping['mapping']), 0);
                 $size = 0;
                 for ($i = 0; $i < count($mapping['mapping']); $i++) {
                     if (in_array($mapping['mapping'][$i], $source)) {
                         $bits[$i] = 1;
                         $size = $i;
                     }
                 }
                 if (isset($mapping['min']) && $mapping['min'] >= 1 && $size < $mapping['min']) {
                     $size = $mapping['min'] - 1;
                 }
                 $offset = 8 - ($size + 1 & 7);
                 $offset = $offset !== 8 ? $offset : 0;
                 $value = chr($offset);
                 for ($i = $size + 1; $i < count($mapping['mapping']); $i++) {
                     unset($bits[$i]);
                 }
                 $bits = implode('', array_pad($bits, $size + $offset + 1, 0));
                 $bytes = explode(' ', rtrim(chunk_split($bits, 8, ' ')));
                 foreach ($bytes as $byte) {
                     $value .= chr(bindec($byte));
                 }
                 break;
             }
         case self::TYPE_OCTET_STRING:
             /* The initial octet shall encode, as an unsigned binary integer with bit 1 as the least significant bit,
                                the number of unused bits in the final subsequent octet. The number shall be in the range zero to seven.
             
                                -- http://www.itu.int/ITU-T/studygroups/com17/languages/X.690-0207.pdf#page=16 */
             $value = base64_decode($source);
             break;
         case self::TYPE_OBJECT_IDENTIFIER:
             $oid = preg_match('#(?:\\d+\\.)+#', $source) ? $source : array_search($source, $this->oids);
             if ($oid === false) {
                 user_error('Invalid OID');
                 return false;
             }
             $value = '';
             $parts = explode('.', $oid);
             $value = chr(40 * $parts[0] + $parts[1]);
             for ($i = 2; $i < count($parts); $i++) {
                 $temp = '';
                 if (!$parts[$i]) {
                     $temp = "";
                 } else {
                     while ($parts[$i]) {
                         $temp = chr(0x80 | $parts[$i] & 0x7f) . $temp;
                         $parts[$i] >>= 7;
                     }
                     $temp[strlen($temp) - 1] = $temp[strlen($temp) - 1] & chr(0x7f);
                 }
                 $value .= $temp;
             }
             break;
         case self::TYPE_ANY:
             $loc = $this->location;
             if (isset($idx)) {
                 array_pop($this->location);
             }
             switch (true) {
                 case !isset($source):
                     return $this->_encode_der(null, array('type' => self::TYPE_NULL) + $mapping, null, $special);
                 case is_int($source):
                 case $source instanceof BigInteger:
                     return $this->_encode_der($source, array('type' => self::TYPE_INTEGER) + $mapping, null, $special);
                 case is_float($source):
                     return $this->_encode_der($source, array('type' => self::TYPE_REAL) + $mapping, null, $special);
                 case is_bool($source):
                     return $this->_encode_der($source, array('type' => self::TYPE_BOOLEAN) + $mapping, null, $special);
                 case is_array($source) && count($source) == 1:
                     $typename = implode('', array_keys($source));
                     $outtype = array_search($typename, $this->ANYmap, true);
                     if ($outtype !== false) {
                         return $this->_encode_der($source[$typename], array('type' => $outtype) + $mapping, null, $special);
                     }
             }
             $filters = $this->filters;
             foreach ($loc as $part) {
                 if (!isset($filters[$part])) {
                     $filters = false;
                     break;
                 }
                 $filters = $filters[$part];
             }
             if ($filters === false) {
                 user_error('No filters defined for ' . implode('/', $loc));
                 return false;
             }
             return $this->_encode_der($source, $filters + $mapping, null, $special);
         case self::TYPE_NULL:
             $value = '';
             break;
         case self::TYPE_NUMERIC_STRING:
         case self::TYPE_TELETEX_STRING:
         case self::TYPE_PRINTABLE_STRING:
         case self::TYPE_UNIVERSAL_STRING:
         case self::TYPE_UTF8_STRING:
         case self::TYPE_BMP_STRING:
         case self::TYPE_IA5_STRING:
         case self::TYPE_VISIBLE_STRING:
         case self::TYPE_VIDEOTEX_STRING:
         case self::TYPE_GRAPHIC_STRING:
         case self::TYPE_GENERAL_STRING:
             $value = $source;
             break;
         case self::TYPE_BOOLEAN:
             $value = $source ? "ÿ" : "";
             break;
         default:
             user_error('Mapping provides no type definition for ' . implode('/', $this->location));
             return false;
     }
     if (isset($idx)) {
         array_pop($this->location);
     }
     if (isset($mapping['cast'])) {
         if (isset($mapping['explicit']) || $mapping['type'] == self::TYPE_CHOICE) {
             $value = chr($tag) . $this->_encodeLength(strlen($value)) . $value;
             $tag = $mapping['class'] << 6 | 0x20 | $mapping['cast'];
         } else {
             $tag = $mapping['class'] << 6 | ord($temp[0]) & 0x20 | $mapping['cast'];
         }
     }
     return chr($tag) . $this->_encodeLength(strlen($value)) . $value;
 }
コード例 #4
0
 /**
  * Logical Exclusive-Or
  *
  * @param \phpseclib\Math\BigInteger $x
  * @access public
  * @internal Implemented per a request by Lluis Pamies i Juarez <lluis _a_ pamies.cat>
  * @return \phpseclib\Math\BigInteger
  */
 function bitwise_xor($x)
 {
     switch (MATH_BIGINTEGER_MODE) {
         case self::MODE_GMP:
             $temp = new static();
             $temp->value = gmp_xor($this->value, $x->value);
             return $this->_normalize($temp);
         case self::MODE_BCMATH:
             $left = $this->toBytes();
             $right = $x->toBytes();
             $length = max(strlen($left), strlen($right));
             $left = str_pad($left, $length, chr(0), STR_PAD_LEFT);
             $right = str_pad($right, $length, chr(0), STR_PAD_LEFT);
             return $this->_normalize(new static($left ^ $right, 256));
     }
     $length = max(count($this->value), count($x->value));
     $result = $this->copy();
     $result->value = array_pad($result->value, $length, 0);
     $x->value = array_pad($x->value, $length, 0);
     for ($i = 0; $i < $length; ++$i) {
         $result->value[$i] ^= $x->value[$i];
     }
     return $this->_normalize($result);
 }
コード例 #5
0
ファイル: PuTTY.php プロジェクト: phpseclib/phpseclib
 /**
  * Convert a private key to the appropriate format.
  *
  * @access public
  * @param \phpseclib\Math\BigInteger $n
  * @param \phpseclib\Math\BigInteger $e
  * @param \phpseclib\Math\BigInteger $d
  * @param array $primes
  * @param array $exponents
  * @param array $coefficients
  * @param string $password optional
  * @return string
  */
 static function savePrivateKey(BigInteger $n, BigInteger $e, BigInteger $d, $primes, $exponents, $coefficients, $password = '')
 {
     if (count($primes) != 2) {
         return false;
     }
     $raw = array('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));
     $key = "PuTTY-User-Key-File-2: ssh-rsa\r\nEncryption: ";
     $encryption = !empty($password) || is_string($password) ? 'aes256-cbc' : 'none';
     $key .= $encryption;
     $key .= "\r\nComment: " . self::$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(self::$comment), self::$comment, strlen($public), $public);
     $public = Base64::encode($public);
     $key .= "Public-Lines: " . (strlen($public) + 63 >> 6) . "\r\n";
     $key .= chunk_split($public, 64);
     $private = pack('Na*Na*Na*Na*', strlen($raw['privateExponent']), $raw['privateExponent'], strlen($raw['prime1']), $raw['prime1'], strlen($raw['prime2']), $raw['prime2'], strlen($raw['coefficient']), $raw['coefficient']);
     if (empty($password) && !is_string($password)) {
         $source .= pack('Na*', strlen($private), $private);
         $hashkey = 'putty-private-key-file-mac-key';
     } else {
         $private .= Random::string(16 - (strlen($private) & 15));
         $source .= pack('Na*', strlen($private), $private);
         $crypto = new AES();
         $crypto->setKey(static::generateSymmetricKey($password, 32));
         $crypto->setIV(str_repeat("", $crypto->getBlockLength() >> 3));
         $crypto->disablePadding();
         $private = $crypto->encrypt($private);
         $hashkey = 'putty-private-key-file-mac-key' . $password;
     }
     $private = Base64::encode($private);
     $key .= 'Private-Lines: ' . (strlen($private) + 63 >> 6) . "\r\n";
     $key .= chunk_split($private, 64);
     $hash = new Hash('sha1');
     $hash->setKey(sha1($hashkey, true));
     $key .= 'Private-MAC: ' . Hex::encode($hash->hash($source)) . "\r\n";
     return $key;
 }
コード例 #6
0
ファイル: SSH1.php プロジェクト: zeus911/phpseclib
 /**
  * Connect to an SSHv1 server
  *
  * @return Boolean
  * @access private
  */
 function _connect()
 {
     $this->fsock = @fsockopen($this->host, $this->port, $errno, $errstr, $this->connectionTimeout);
     if (!$this->fsock) {
         user_error(rtrim("Cannot connect to {$this->host}:{$this->port}. Error {$errno}. {$errstr}"));
         return false;
     }
     $this->server_identification = $init_line = fgets($this->fsock, 255);
     if (defined('NET_SSH1_LOGGING')) {
         $this->_append_log('<-', $this->server_identification);
         $this->_append_log('->', $this->identifier . "\r\n");
     }
     if (!preg_match('#SSH-([0-9\\.]+)-(.+)#', $init_line, $parts)) {
         user_error('Can only connect to SSH servers');
         return false;
     }
     if ($parts[1][0] != 1) {
         user_error("Cannot connect to SSH {$parts['1']} servers");
         return false;
     }
     fputs($this->fsock, $this->identifier . "\r\n");
     $response = $this->_get_binary_packet();
     if ($response[self::RESPONSE_TYPE] != NET_SSH1_SMSG_PUBLIC_KEY) {
         user_error('Expected SSH_SMSG_PUBLIC_KEY');
         return false;
     }
     $anti_spoofing_cookie = $this->_string_shift($response[self::RESPONSE_DATA], 8);
     $this->_string_shift($response[self::RESPONSE_DATA], 4);
     $temp = unpack('nlen', $this->_string_shift($response[self::RESPONSE_DATA], 2));
     $server_key_public_exponent = new BigInteger($this->_string_shift($response[self::RESPONSE_DATA], ceil($temp['len'] / 8)), 256);
     $this->server_key_public_exponent = $server_key_public_exponent;
     $temp = unpack('nlen', $this->_string_shift($response[self::RESPONSE_DATA], 2));
     $server_key_public_modulus = new BigInteger($this->_string_shift($response[self::RESPONSE_DATA], ceil($temp['len'] / 8)), 256);
     $this->server_key_public_modulus = $server_key_public_modulus;
     $this->_string_shift($response[self::RESPONSE_DATA], 4);
     $temp = unpack('nlen', $this->_string_shift($response[self::RESPONSE_DATA], 2));
     $host_key_public_exponent = new BigInteger($this->_string_shift($response[self::RESPONSE_DATA], ceil($temp['len'] / 8)), 256);
     $this->host_key_public_exponent = $host_key_public_exponent;
     $temp = unpack('nlen', $this->_string_shift($response[self::RESPONSE_DATA], 2));
     $host_key_public_modulus = new BigInteger($this->_string_shift($response[self::RESPONSE_DATA], ceil($temp['len'] / 8)), 256);
     $this->host_key_public_modulus = $host_key_public_modulus;
     $this->_string_shift($response[self::RESPONSE_DATA], 4);
     // get a list of the supported ciphers
     extract(unpack('Nsupported_ciphers_mask', $this->_string_shift($response[self::RESPONSE_DATA], 4)));
     foreach ($this->supported_ciphers as $mask => $name) {
         if (($supported_ciphers_mask & 1 << $mask) == 0) {
             unset($this->supported_ciphers[$mask]);
         }
     }
     // get a list of the supported authentications
     extract(unpack('Nsupported_authentications_mask', $this->_string_shift($response[self::RESPONSE_DATA], 4)));
     foreach ($this->supported_authentications as $mask => $name) {
         if (($supported_authentications_mask & 1 << $mask) == 0) {
             unset($this->supported_authentications[$mask]);
         }
     }
     $session_id = pack('H*', md5($host_key_public_modulus->toBytes() . $server_key_public_modulus->toBytes() . $anti_spoofing_cookie));
     $session_key = Random::string(32);
     $double_encrypted_session_key = $session_key ^ str_pad($session_id, 32, chr(0));
     if ($server_key_public_modulus->compare($host_key_public_modulus) < 0) {
         $double_encrypted_session_key = $this->_rsa_crypt($double_encrypted_session_key, array($server_key_public_exponent, $server_key_public_modulus));
         $double_encrypted_session_key = $this->_rsa_crypt($double_encrypted_session_key, array($host_key_public_exponent, $host_key_public_modulus));
     } else {
         $double_encrypted_session_key = $this->_rsa_crypt($double_encrypted_session_key, array($host_key_public_exponent, $host_key_public_modulus));
         $double_encrypted_session_key = $this->_rsa_crypt($double_encrypted_session_key, array($server_key_public_exponent, $server_key_public_modulus));
     }
     $cipher = isset($this->supported_ciphers[$this->cipher]) ? $this->cipher : self::CIPHER_3DES;
     $data = pack('C2a*na*N', NET_SSH1_CMSG_SESSION_KEY, $cipher, $anti_spoofing_cookie, 8 * strlen($double_encrypted_session_key), $double_encrypted_session_key, 0);
     if (!$this->_send_binary_packet($data)) {
         user_error('Error sending SSH_CMSG_SESSION_KEY');
         return false;
     }
     switch ($cipher) {
         //case self::CIPHER_NONE:
         //    $this->crypto = new \phpseclib\Crypt\Null();
         //    break;
         case self::CIPHER_DES:
             $this->crypto = new DES();
             $this->crypto->disablePadding();
             $this->crypto->enableContinuousBuffer();
             $this->crypto->setKey(substr($session_key, 0, 8));
             break;
         case self::CIPHER_3DES:
             $this->crypto = new TripleDES(TripleDES::MODE_3CBC);
             $this->crypto->disablePadding();
             $this->crypto->enableContinuousBuffer();
             $this->crypto->setKey(substr($session_key, 0, 24));
             break;
             //case self::CIPHER_RC4:
             //    $this->crypto = new RC4();
             //    $this->crypto->enableContinuousBuffer();
             //    $this->crypto->setKey(substr($session_key, 0,  16));
             //    break;
     }
     $response = $this->_get_binary_packet();
     if ($response[self::RESPONSE_TYPE] != NET_SSH1_SMSG_SUCCESS) {
         user_error('Expected SSH_SMSG_SUCCESS');
         return false;
     }
     $this->bitmap = self::MASK_CONNECTED;
     return true;
 }
コード例 #7
0
ファイル: RSA.php プロジェクト: HerO-0110/EmailAuth
 /**
  * Loads a public or private key
  *
  * Returns true on success and false on failure (ie. an incorrect password was provided or the key was malformed)
  *
  * @access public
  * @param String $key        	
  * @param Integer $type
  *        	optional
  */
 function loadKey($key, $type = false)
 {
     if (is_object($key) && strtolower(get_class($key)) == 'crypt_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->encryptionMode = $key->encryptionMode;
         $this->signatureMode = $key->signatureMode;
         $this->password = $key->password;
         $this->configFile = $key->configFile;
         $this->comment = $key->comment;
         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 = $key->modulus->copy();
         }
         if (is_object($key->exponent)) {
             $this->exponent = $key->exponent->copy();
         }
         if (is_object($key->publicExponent)) {
             $this->publicExponent = $key->publicExponent->copy();
         }
         $this->primes = array();
         $this->exponents = array();
         $this->coefficients = array();
         foreach ($this->primes as $prime) {
             $this->primes[] = $prime->copy();
         }
         foreach ($this->exponents as $exponent) {
             $this->exponents[] = $exponent->copy();
         }
         foreach ($this->coefficients as $coefficient) {
             $this->coefficients[] = $coefficient->copy();
         }
         return true;
     }
     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;
 }
コード例 #8
0
ファイル: PKCS1.php プロジェクト: bengitiger/phpseclib
 /**
  * Convert a public key to the appropriate format
  *
  * @access public
  * @param \phpseclib\Math\BigInteger $n
  * @param \phpseclib\Math\BigInteger $e
  * @return string
  */
 static function savePublicKey(BigInteger $n, BigInteger $e)
 {
     $modulus = $n->toBytes(true);
     $publicExponent = $e->toBytes(true);
     // from <http://tools.ietf.org/html/rfc3447#appendix-A.1.1>:
     // RSAPublicKey ::= SEQUENCE {
     //     modulus           INTEGER,  -- n
     //     publicExponent    INTEGER   -- e
     // }
     $components = array('modulus' => pack('Ca*a*', self::ASN1_INTEGER, self::_encodeLength(strlen($modulus)), $modulus), 'publicExponent' => pack('Ca*a*', self::ASN1_INTEGER, self::_encodeLength(strlen($publicExponent)), $publicExponent));
     $RSAPublicKey = pack('Ca*a*a*', self::ASN1_SEQUENCE, self::_encodeLength(strlen($components['modulus']) + strlen($components['publicExponent'])), $components['modulus'], $components['publicExponent']);
     $RSAPublicKey = "-----BEGIN RSA PUBLIC KEY-----\r\n" . chunk_split(base64_encode($RSAPublicKey), 64) . '-----END RSA PUBLIC KEY-----';
     return $RSAPublicKey;
 }
コード例 #9
0
ファイル: MSBLOB.php プロジェクト: bengitiger/phpseclib
 /**
  * Convert a private key to the appropriate format.
  *
  * @access public
  * @param \phpseclib\Math\BigInteger $n
  * @param \phpseclib\Math\BigInteger $e
  * @param \phpseclib\Math\BigInteger $d
  * @param array $primes
  * @param array $exponents
  * @param array $coefficients
  * @param string $password optional
  * @return string
  */
 static function savePrivateKey(BigInteger $n, BigInteger $e, BigInteger $d, $primes, $exponents, $coefficients, $password = '')
 {
     $n = strrev($n->toBytes());
     $e = str_pad(strrev($e->toBytes()), 4, "");
     $key = pack('aavV', chr(self::PRIVATEKEYBLOB), chr(2), 0, self::CALG_RSA_KEYX);
     $key .= pack('VVa*', self::RSA2, 8 * strlen($n), $e);
     $key .= $n;
     $key .= strrev($primes[1]->toBytes());
     $key .= strrev($primes[2]->toBytes());
     $key .= strrev($exponents[1]->toBytes());
     $key .= strrev($exponents[2]->toBytes());
     $key .= strrev($coefficients[1]->toBytes());
     $key .= strrev($d->toBytes());
     return base64_encode($key);
 }
コード例 #10
0
ファイル: XML.php プロジェクト: paragonie-scott/phpseclib
 /**
  * Convert a public key to the appropriate format
  *
  * @access public
  * @param \phpseclib\Math\BigInteger $n
  * @param \phpseclib\Math\BigInteger $e
  * @return string
  */
 static function savePublicKey(BigInteger $n, BigInteger $e)
 {
     return "<RSAKeyValue>\r\n" . '  <Modulus>' . Base64::encode($n->toBytes()) . "</Modulus>\r\n" . '  <Exponent>' . Base64::encode($e->toBytes()) . "</Exponent>\r\n" . '</RSAKeyValue>';
 }
コード例 #11
0
ファイル: RSA.php プロジェクト: juggernautsei/openemr
    /**
     * Returns the public key's fingerprint
     *
     * The public key's fingerprint is returned, which is equivalent to running `ssh-keygen -lf rsa.pub`. If there is
     * no public key currently loaded, false is returned.
     * Example output (md5): "c1:b1:30:29:d7:b8:de:6c:97:77:10:d7:46:41:63:87" (as specified by RFC 4716)
     *
     * @access public
     * @param string $algorithm The hashing algorithm to be used. Valid options are 'md5' and 'sha256'. False is returned
     * for invalid values.
     * @return mixed
     */
    function getPublicKeyFingerprint($algorithm = 'md5')
    {
        if (empty($this->modulus) || empty($this->publicExponent)) {
            return false;
        }

        $modulus = $this->modulus->toBytes(true);
        $publicExponent = $this->publicExponent->toBytes(true);

        $RSAPublicKey = pack('Na*Na*Na*', strlen('ssh-rsa'), 'ssh-rsa', strlen($publicExponent), $publicExponent, strlen($modulus), $modulus);

        switch ($algorithm) {
            case 'sha256':
                $hash = new Hash('sha256');
                $base = base64_encode($hash->hash($RSAPublicKey));
                return substr($base, 0, strlen($base) - 1);
            case 'md5':
                return substr(chunk_split(md5($RSAPublicKey), 2, ':'), 0, -1);
            default:
                return false;
        }
    }
コード例 #12
0
ファイル: RSA.php プロジェクト: sksree/Jorani_new
 /**
  * Loads a public or private key
  *
  * Returns true on success and false on failure (ie. an incorrect password was provided or the key was malformed)
  *
  * @access public
  * @param String $key
  * @param Integer $type optional
  */
 function loadKey($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->encryptionMode = $key->encryptionMode;
         $this->signatureMode = $key->signatureMode;
         $this->password = $key->password;
         $this->configFile = $key->configFile;
         $this->comment = $key->comment;
         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 = $key->modulus->copy();
         }
         if (is_object($key->exponent)) {
             $this->exponent = $key->exponent->copy();
         }
         if (is_object($key->publicExponent)) {
             $this->publicExponent = $key->publicExponent->copy();
         }
         $this->primes = array();
         $this->exponents = array();
         $this->coefficients = array();
         foreach ($this->primes as $prime) {
             $this->primes[] = $prime->copy();
         }
         foreach ($this->exponents as $exponent) {
             $this->exponents[] = $exponent->copy();
         }
         foreach ($this->coefficients as $coefficient) {
             $this->coefficients[] = $coefficient->copy();
         }
         return true;
     }
     if ($type === false) {
         $types = array(self::PUBLIC_FORMAT_RAW, self::PRIVATE_FORMAT_PKCS1, self::PRIVATE_FORMAT_XML, self::PRIVATE_FORMAT_PUTTY, self::PUBLIC_FORMAT_OPENSSH);
         foreach ($types as $type) {
             $components = $this->_parseKey($key, $type);
             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;
     }
     switch ($type) {
         case self::PUBLIC_FORMAT_OPENSSH:
         case self::PUBLIC_FORMAT_RAW:
             $this->setPublicKey();
             break;
         case self::PRIVATE_FORMAT_PKCS1:
             switch (true) {
                 case strpos($key, '-BEGIN PUBLIC KEY-') !== false:
                 case strpos($key, '-BEGIN RSA PUBLIC KEY-') !== false:
                     $this->setPublicKey();
             }
     }
     return true;
 }
コード例 #13
0
ファイル: PKCS8.php プロジェクト: andreybolonin/phpseclib
 /**
  * Convert a public key to the appropriate format
  *
  * @access public
  * @param \phpseclib\Math\BigInteger $n
  * @param \phpseclib\Math\BigInteger $e
  * @return string
  */
 static function savePublicKey(BigInteger $n, BigInteger $e)
 {
     $modulus = $n->toBytes(true);
     $publicExponent = $e->toBytes(true);
     // from <http://tools.ietf.org/html/rfc3447#appendix-A.1.1>:
     // RSAPublicKey ::= SEQUENCE {
     //     modulus           INTEGER,  -- n
     //     publicExponent    INTEGER   -- e
     // }
     $components = array('modulus' => pack('Ca*a*', self::ASN1_INTEGER, ASN1::encodeLength(strlen($modulus)), $modulus), 'publicExponent' => pack('Ca*a*', self::ASN1_INTEGER, ASN1::encodeLength(strlen($publicExponent)), $publicExponent));
     $RSAPublicKey = pack('Ca*a*a*', self::ASN1_SEQUENCE, ASN1::encodeLength(strlen($components['modulus']) + strlen($components['publicExponent'])), $components['modulus'], $components['publicExponent']);
     // sequence(oid(1.2.840.113549.1.1.1), null)) = rsaEncryption.
     $rsaOID = "0\r\t*†H†÷\r";
     // hex version of MA0GCSqGSIb3DQEBAQUA
     $RSAPublicKey = chr(0) . $RSAPublicKey;
     $RSAPublicKey = chr(3) . ASN1::encodeLength(strlen($RSAPublicKey)) . $RSAPublicKey;
     $RSAPublicKey = pack('Ca*a*', self::ASN1_SEQUENCE, ASN1::encodeLength(strlen($rsaOID . $RSAPublicKey)), $rsaOID . $RSAPublicKey);
     $RSAPublicKey = "-----BEGIN PUBLIC KEY-----\r\n" . chunk_split(Base64::encode($RSAPublicKey), 64) . '-----END PUBLIC KEY-----';
     return $RSAPublicKey;
 }
コード例 #14
0
ファイル: OpenSSH.php プロジェクト: phpseclib/phpseclib
 /**
  * Convert a public key to the appropriate format
  *
  * @access public
  * @param \phpseclib\Math\BigInteger $n
  * @param \phpseclib\Math\BigInteger $e
  * @return string
  */
 static function savePublicKey(BigInteger $n, BigInteger $e)
 {
     $publicExponent = $e->toBytes(true);
     $modulus = $n->toBytes(true);
     // from <http://tools.ietf.org/html/rfc4253#page-15>:
     // string    "ssh-rsa"
     // mpint     e
     // mpint     n
     $RSAPublicKey = pack('Na*Na*Na*', strlen('ssh-rsa'), 'ssh-rsa', strlen($publicExponent), $publicExponent, strlen($modulus), $modulus);
     $RSAPublicKey = 'ssh-rsa ' . Base64::encode($RSAPublicKey) . ' ' . self::$comment;
     return $RSAPublicKey;
 }