Example #1
0
 function rsa_decrypt($ciphertext, $private_key, $password)
 {
     // 암호문을 base64로 디코딩한다.
     $ciphertext = @base64_decode($ciphertext, true);
     if ($ciphertext === false) {
         return false;
     }
     // 개인키를 사용하여 복호화한다.
     $privkey_decoded = @openssl_pkey_get_private($private_key, $password);
     if ($privkey_decoded === false) {
         return false;
     }
     $plaintext = false;
     $status = @openssl_private_decrypt($ciphertext, $plaintext, $privkey_decoded);
     @openssl_pkey_free($privkey_decoded);
     if (!$status || $plaintext === false) {
         return false;
     }
     // 압축을 해제하여 평문을 얻는다.
     $plaintext = @gzuncompress($plaintext);
     if ($plaintext === false) {
         return false;
     }
     // 이상이 없는 경우 평문을 반환한다.
     return $plaintext;
 }
Example #2
0
 /**
  * Test the plugin configuration form.
  *
  * @group key
  */
 public function testFileContentsKey()
 {
     $form = [];
     // Mock the translation manager translate method. This test does not assert
     // any other translation messages so the return value will always be the
     // same message on each consecutive call to t().
     $this->translationManager->expects($this->any())->method('translate')->withConsecutive(['File location'], ['The location of the file in which the key will be stored. The path may be absolute (e.g., %abs), relative to the Drupal directory (e.g., %rel), or defined using a stream wrapper (e.g., %str).'], ['File does not exist or is not readable.'])->willReturn('File does not exist or is not readable.');
     $form['key_settings'] = $this->plugin->buildConfigurationForm($form, $this->form_state);
     $this->assertNotNull($form['key_settings']['file_location']);
     // Test that the file is validated.
     $this->form_state->setValues(['file_location' => 'bogus']);
     $this->plugin->validateConfigurationForm($form, $this->form_state);
     $this->assertEquals('File does not exist or is not readable.', $this->form_state->getErrors()['file_location']);
     // Set the form state value, and simulate a form submission.
     $this->form_state->clearErrors();
     $this->form_state->setValues(['file_location' => $this->keyFile]);
     $this->plugin->validateConfigurationForm($form, $this->form_state);
     $this->assertEmpty($this->form_state->getErrors());
     // Submission.
     $this->plugin->submitConfigurationForm($form, $this->form_state);
     $this->assertEquals($this->keyFile, $this->plugin->getConfiguration()['file_location']);
     // Make sure that the file contents are valid.
     $resource = openssl_pkey_get_private($this->plugin->getKeyValue());
     $this->assertNotFalse($resource);
 }
 public function sign($data, $key, $passphrase = '')
 {
     $privateKey = openssl_pkey_get_private($key, $passphrase);
     openssl_sign($data, $signature, $privateKey);
     openssl_free_key($privateKey);
     return $signature;
 }
 public function getKey()
 {
     if (false === isset($this->key)) {
         $this->key = openssl_pkey_get_private(file_get_contents($this->getKeylocation()));
     }
     return $this->key;
 }
Example #5
0
File: secure.php Project: neel/bong
 public static function privateKey($uri, $ts)
 {
     if (self::privateExists($uri, $ts)) {
         return openssl_pkey_get_private(array('file://' . self::_basePath() . '/' . md5($uri . $ts) . '.pri', ''));
     }
     return false;
 }
Example #6
0
 /**
  * Returns a private key from file path or content
  *
  * @param string $key
  * @param string $passphrase
  *
  * @return resource
  *
  * @throws InvalidArgumentException
  */
 public function getPrivateKey($key, $passphrase = '')
 {
     if ($privateKey = openssl_pkey_get_private($key, $passphrase)) {
         return $privateKey;
     }
     throw new InvalidArgumentException('You should provid a valid private key (with its passphrase when used)');
 }
 protected function fetch_private_cert(&$request)
 {
     $file = Shindig_Config::get('private_key_file');
     if (!(file_exists($file) && is_readable($file))) {
         throw new Exception("Error loding private key");
     }
     $private_key = @file_get_contents($file);
     if (!$private_key) {
         throw new Exception("Error loding private key");
     }
     $phrase = Shindig_Config::get('private_key_phrase');
     if (strpos($private_key, '-----BEGIN') === false) {
         $tmp .= "-----BEGIN PRIVATE KEY-----\n";
         $chunks .= str_split($private_key, 64);
         foreach ($chunks as $chunk) {
             $tmp .= $chunk . "\n";
         }
         $tmp .= "-----END PRIVATE KEY-----";
         $private_key = $tmp;
     }
     if (!($rsa_private_key = @openssl_pkey_get_private($private_key, $phrase))) {
         throw new Exception("Could not create the key");
     }
     return $rsa_private_key;
 }
Example #8
0
 /**
  * Converts a string representation of a key into an OpenSSL resource
  *
  * @param string|resource $key
  * @param string          $password
  * @return resource OpenSSL key resource
  */
 protected function getKeyResource($key, $password = null)
 {
     if (is_resource($key)) {
         return $key;
     }
     return openssl_pkey_get_public($key) ?: openssl_pkey_get_private($key, $password);
 }
 public function __construct()
 {
     $strCoreKey = "";
     $strPackageKey = "";
     //==================================================================
     $objPackages = $this->db->query("SELECT * FROM __repo_packages WHERE category");
     if ($objPackages) {
         while ($row = $objPackages->fetchAssoc()) {
             if (intval($row['category']) == 8) {
                 $privateKey = $strCoreKey;
             } else {
                 $privateKey = $strPackageKey;
             }
             if ($row['filehash'] != "") {
                 $strHash = $row['filehash'];
                 // fetch private key from file and ready it
                 $strKey = "file://" . $privateKey;
                 $pkeyid = openssl_pkey_get_private($strKey);
                 // compute signature
                 openssl_sign($strHash, $signature, $pkeyid, "sha1WithRSAEncryption");
                 // free the key from memory
                 openssl_free_key($pkeyid);
                 $signature = base64_encode($signature);
                 echo "UPDATE eqdkp20_repo_packages SET signature = '" . $signature . "' WHERE id=" . $row['id'] . "; ";
             }
         }
     }
 }
Example #10
0
function decryptPrivate($path, $cText)
{
    $fcontents = file_get_contents($path);
    $privateKey = openssl_pkey_get_private($fcontents, "symelosh");
    openssl_private_decrypt($cText, $decrypted, $privateKey);
    return $decrypted;
}
Example #11
0
 /**
  * {@inheritdoc}
  */
 public function decrypt($data, $key, $passphrase = '')
 {
     $privateKey = openssl_pkey_get_private($key, $passphrase);
     openssl_private_decrypt($data, $messageDecrypted, $privateKey);
     openssl_free_key($privateKey);
     return $messageDecrypted;
 }
function gal_service_account_upgrade(&$option, $gal_option_name, &$existing_sa_options, $gal_sa_option_name)
{
    /* Convert ga_serviceemail ga_keyfilepath
     * into new separate sa options:
     * ga_sakey, ga_serviceemail, ga_pkey_print
     */
    if (count($existing_sa_options)) {
        return;
    }
    $existing_sa_options = array('ga_serviceemail' => isset($option['ga_serviceemail']) ? $option['ga_serviceemail'] : '', 'ga_sakey' => '', 'ga_pkey_print' => '<unspecified>');
    try {
        if (version_compare(PHP_VERSION, '5.3.0') >= 0 && function_exists('openssl_x509_read')) {
            if (isset($option['ga_keyfilepath']) && $option['ga_keyfilepath'] != '' && file_exists($option['ga_keyfilepath'])) {
                $p12key = @file_get_contents($option['ga_keyfilepath']);
                $certs = array();
                if (openssl_pkcs12_read($p12key, $certs, 'notasecret')) {
                    if (array_key_exists("pkey", $certs) && $certs["pkey"]) {
                        $privateKey = openssl_pkey_get_private($certs['pkey']);
                        $pemString = '';
                        if (openssl_pkey_export($privateKey, $pemString)) {
                            $existing_sa_options['ga_sakey'] = $pemString;
                        }
                        openssl_pkey_free($privateKey);
                        @unlink($options['ga_keyfilepath']);
                    }
                }
            }
        }
    } catch (Exception $e) {
        // Never mind
    }
    // Remove redundant parts of regular options
    unset($option['ga_serviceemail']);
    unset($option['ga_keyfilepath']);
}
 function __construct($clientcrt, $clientkey, $clientpw = NULL, $logging = false)
 {
     if (is_bool($logging)) {
         $this->logging = $logging;
     }
     if (!openssl_pkey_get_private(is_file($clientkey) ? "file://" . $clientkey : $clientkey, $clientpw)) {
         $this->log("Invalid client private key.", true);
     }
     if (!openssl_pkey_get_public(is_file($clientcrt) ? "file://" . $clientcrt : $clientcrt)) {
         $this->log("Invalid client public key.", true);
     }
     $this->log("Certificate / key looks valid.");
     $handle = curl_init();
     curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
     curl_setopt($handle, CURLOPT_HEADER, true);
     curl_setopt($handle, CURLOPT_USERAGENT, sprintf("StartSSL-PHP-API/%s", self::VERSION));
     curl_setopt($handle, CURLOPT_URL, $this->authUrl);
     curl_setopt($handle, CURLOPT_SSLCERT, $clientcrt);
     curl_setopt($handle, CURLOPT_SSLKEY, $clientkey);
     if (!is_null($clientpw)) {
         curl_setopt($handle, CURLOPT_SSLKEYPASSWD, $clientpw);
     }
     $this->log("Authenticating...");
     $result = curl_exec($handle);
     preg_match('/^Set-Cookie: (MyStartSSLCookie=.*)$/m', $result, $matches);
     if (isset($matches[1])) {
         $this->cookie = $matches[1];
         $this->log("User authenticated.");
     } else {
         $this->log("Unable to authenticate. Check certificate/key.", true);
     }
 }
 private function setPrivateKey($key, $passPhrase)
 {
     $this->privateKey = @openssl_pkey_get_private($key, $passPhrase);
     if (!$this->validateOpenSslKey($this->privateKey)) {
         throw new InvalidArgumentException('Unable to create private key' . ' from provided key. Key must be a PEM encoded private key or' . ' a path to a file containing a PEM encoded private key.');
     }
 }
Example #15
0
 /**
  * getSignMsg 计算前面
  *
  * @param array $pay_params
  *        	计算前面数据
  * @param string $sign_type
  *        	签名类型
  * @return string $signMsg 返回密文
  */
 function getSignMsg($pay_params = array(), $sign_type)
 {
     $params_str = "";
     $signMsg = "";
     $sina_config = \System\Entrance::config('SINA_FUND_MANAGED');
     foreach ($pay_params as $key => $val) {
         if ($key != "sign" && $key != "sign_type" && $key != "sign_version" && isset($val) && @$val != "") {
             $params_str .= $key . "=" . $val . "&";
         }
     }
     $params_str = substr($params_str, 0, -1);
     switch (@$sign_type) {
         case 'RSA':
             //签名私钥
             $private_key = $sina_config['private_key'];
             $priv_key = file_get_contents($private_key);
             $pkeyid = openssl_pkey_get_private($priv_key);
             openssl_sign($params_str, $signMsg, $pkeyid, OPENSSL_ALGO_SHA1);
             openssl_free_key($pkeyid);
             $signMsg = base64_encode($signMsg);
             break;
         case 'MD5':
         default:
             $params_str = $params_str . $sina_config['md5_key'];
             $signMsg = strtolower(md5($params_str));
             break;
     }
     return $signMsg;
 }
Example #16
0
 /**
  * @param SigningDetails $dn
  * @param null $privateKey
  * @param null $privkeypass
  * @param int $numberofdays
  * @return array
  * @throws \Exception
  */
 function generate(SigningDetails $dn, $privateKey = null, $privkeypass = null, $numberofdays = 365)
 {
     if ($privateKey === null) {
         $privkey = $this->generatePrivateKey();
     } elseif (is_string($privateKey)) {
         $privkey = openssl_pkey_get_private($privateKey);
     } else {
         throw new \Exception('Invalid format for private key');
     }
     if (!$privkey) {
         throw new \Exception('Invalid private key');
     }
     $csr = @openssl_csr_new($dn->toArray(), $privkey);
     if (!$csr) {
         throw new \Exception('Failed create signing request. Input likely invalid.');
     }
     $sscert = openssl_csr_sign($csr, null, $privkey, $numberofdays);
     if (!$sscert) {
         throw new \Exception('Failed create signing request. Input likely invalid.');
     }
     openssl_x509_export($sscert, $publickey);
     $privatekey = null;
     if (!openssl_pkey_export($privkey, $privatekey, $privkeypass)) {
         throw new \Exception('Private key generatio failed');
     }
     /*$csrStr = null;
     		if(!openssl_csr_export($csr, $csrStr)){
     			throw new \Exception('CSR generation failed');
     		}*/
     return [$publickey, $privatekey];
 }
Example #17
0
 /**
  * return PublicKey
  */
 public function getPublicKey()
 {
     $res = \openssl_pkey_get_private($this->keyMaterial);
     $pubkey = \openssl_pkey_get_details($res);
     $public = \rtrim(\str_replace("\n", "\r\n", $pubkey['key']), "\r\n");
     return new PublicKey($public);
 }
Example #18
0
function getSign($sMessage)
{
    $sPrivateKey = file_get_contents('private.pem');
    $rPrivateKey = openssl_pkey_get_private($sPrivateKey);
    openssl_sign($sMessage, $sSign, $rPrivateKey, OPENSSL_ALGO_SHA1);
    return bin2hex($sSign);
}
Example #19
0
function decryptPassword($input)
{
    $config = $GLOBALS['config'];
    if ($config['rsa_modulus'] != '' && $config['rsa_exponent'] != '' && $config['rsa_key'] != '' && isset($_SESSION['crypt_key'])) {
        if (substr($input, 0, 5) == "enc: ") {
            $input = substr($input, 5);
            $res = openssl_pkey_get_private($config['rsa_key'], $config['rsa_passphrase']);
            openssl_private_decrypt(hex2bin($input), $plaintext, $res);
            $plaintext = utf8_encode($plaintext);
            //loop through current session login keys and try all of them that haven't expired
            foreach ($_SESSION['crypt_key'] as $arrayKey => $key_array) {
                //key_array is array(time key was generated, hexadecimal key)
                if (time() - $key_array[0] > 5 * 60) {
                    //delete keys older than 5 minutes
                    //shouldn't take that long to login anyway!
                    unset($_SESSION['crypt_key'][$arrayKey]);
                } else {
                    $crypt_key = $key_array[1];
                    //first part of plaintext should be equal to crypt key
                    if (substr($plaintext, 0, strlen($crypt_key)) == $crypt_key) {
                        return substr($plaintext, strlen($crypt_key));
                    }
                }
            }
            //none of the keys above worked, either forgery or expired form
            return "";
        } else {
            return $input;
        }
    } else {
        return $input;
    }
}
 public function __construct($accessKey, $secretKey, $encryptionMaterials, $endpoint = NULL)
 {
     parent::__construct($accessKey, $secretKey, $endpoint);
     if (is_array($encryptionMaterials)) {
         if (count($encryptionMaterials) == 2) {
             $pk = openssl_pkey_get_public($encryptionMaterials[0]);
             $sk = openssl_pkey_get_private($encryptionMaterials[1]);
             if (!$pk) {
                 throw new Ks3ClientException("invalid RSA public key,you can generate key use openssl");
             }
             if (!$sk) {
                 throw new Ks3ClientException("invalid RSA private key,you can generate key use openssl");
             }
             $encryptionMaterials = array($pk, $sk);
         } else {
             throw new Ks3ClientException("encryptionMaterials should be string or an array of size 2");
         }
     }
     $ks3client = new Ks3Client($accessKey, $secretKey, $endpoint);
     $this->encryptionMaterials = $encryptionMaterials;
     if (ENCRYPTPTION_MODE == "EO") {
         $this->encryptionHandler = new EncryptionEO($ks3client, $encryptionMaterials);
     } elseif (ENCRYPTPTION_MODE == "AE") {
         throw new Ks3ClientException("Authenticated encryption will be supported in the futher");
     } else {
         throw new Ks3ClientException("unsupported encryption mode :" . ENCRYPTPTION_MODE);
     }
     if (ENCRYPTPTION_STORAGE_MODE != "ObjectMetadata" && ENCRYPTPTION_STORAGE_MODE != "InstructionFile") {
         throw new Ks3ClientException("unsupported encryption storage mode :" . ENCRYPTPTION_STORAGE_MODE);
     }
 }
 /**
  * {@inheritdoc}
  */
 protected function authorizeUser(App $app, $email, $password)
 {
     if (isset($app['db'])) {
         $db = $app['db'];
     } else {
         if (isset($app['orm.em'])) {
             $db = $app['orm.em']->getConnection();
         } else {
             throw new Exception("DB connection not found");
         }
     }
     // User array
     $userArray = Users::getInstance($db)->getByEmail($email);
     // User for encode password
     $user = new User($email, $password, array('ROLE_USER'), true, true, true, true);
     // Encoded password
     $encodedPasswd = $app['security.encoder.digest']->encodePassword($password, $user->getSalt());
     if ($userArray['password'] !== $encodedPasswd) {
         $token = false;
     } else {
         // Datetime tomorrow
         $date = new \DateTime('tomorrow');
         // Json Web Token
         $jws = new SimpleJWS(array('alg' => 'RS256'));
         $jws->setPayload(array('uid' => $userArray['id'], 'exp' => $date->format('U')));
         $privateKey = openssl_pkey_get_private('file://' . $app->getAppDir() . '/private.key', '123456789');
         $jws->sign($privateKey);
         $token = $jws->getTokenString();
     }
     return $token;
 }
Example #22
0
 /**
  * @return bool|resource
  */
 protected function getPrivateKey()
 {
     if (is_null($this->privateKey)) {
         throw new ParameterNotFoundException("'privateKey' in JWTEncoder");
     }
     return openssl_pkey_get_private('file://' . $this->privateKey, $this->passPhrase);
 }
Example #23
0
    /**
     * {@inheritdoc}
     */
    public function generate(KeyPair $keyPair, array $domains)
    {
        if (!($privateKey = openssl_pkey_get_private($keyPair->getPrivate()))) {
            // TODO: Improve error message
            throw new AcmeException("Couldn't use private key.");
        }
        $san = implode(",", array_map(function ($dns) {
            return "DNS:{$dns}";
        }, $domains));
        // http://www.heise.de/netze/rfc/rfcs/rfc7633.shtml
        // http://www.heise.de/netze/rfc/rfcs/rfc6066.shtml
        $mustStaple = $this->mustStaple ? "tlsfeature = status_request" : "";
        $tempFile = tempnam(sys_get_temp_dir(), "acme-openssl-config-");
        $tempConf = <<<EOL
[ req ]
distinguished_name = req_distinguished_name
req_extensions = v3_req
{$mustStaple}

[ req_distinguished_name ]

[ v3_req ]
basicConstraints = CA:FALSE
keyUsage = digitalSignature, nonRepudiation
subjectAltName = {$san}
EOL;
        (yield \Amp\File\put($tempFile, $tempConf));
        $csr = openssl_csr_new(["CN" => reset($domains)], $privateKey, ["digest_alg" => "sha256", "config" => $tempFile]);
        (yield \Amp\File\unlink($tempFile));
        if (!$csr) {
            // TODO: Improve error message
            throw new AcmeException("CSR could not be generated.");
        }
        (yield new CoroutineResult(openssl_csr_export($csr, $csr)));
    }
Example #24
0
File: user.php Project: pedra/limp
 function checkUser()
 {
     $rec = $this->_decodePostData();
     $private = file_get_contents(CONFIG_PATH . 'keys/private.key');
     $key = base64_decode($rec['data']->key);
     if (!openssl_private_decrypt($key, $key, openssl_pkey_get_private($private))) {
         exit;
     } else {
         $key = json_decode($key);
         $this->key = $key->asskey;
         // global key access in this controller
         //login in parent app
         $sys = new Model\Sysuser();
         $user = $sys->getLogin($key->login, $key->password);
         if ($user === false) {
             exit(json_encode(['ret' => 'no']));
         }
         //create new user (delete if exists)
         $this->model->createUser($user->ID, $user->NAME, $this->key);
         //user x group status
         $ugs = $this->model->getUserGroupStatus($user->ID);
         $user = array_merge(['ID' => $user->ID, 'NAME' => $user->NAME], $ugs);
         //send
         $this->_sendEncriptedData($user);
     }
 }
Example #25
0
 /**
  * Sign some data with a private key.
  *
  * @param  string      $data
  * @param  string      $privateKey
  * @param  string|null $passphrase
  * @return string
  */
 protected function signData($data, $privateKey, $passphrase = null)
 {
     $privateKey = openssl_pkey_get_private($privateKey, $passphrase);
     openssl_sign($data, $signature, $privateKey);
     openssl_free_key($privateKey);
     return $signature;
 }
 protected function validateSslOptions()
 {
     // Get the contents.
     $sslCertFile = file_exists($this->certPath) ? trim(file_get_contents($this->certPath)) : '';
     $sslKeyFile = file_exists($this->keyPath) ? trim(file_get_contents($this->keyPath)) : '';
     $sslChainFiles = $this->assembleChainFiles($this->chainPaths);
     // Do a bit of validation.
     // @todo: Cert first.
     $certResource = openssl_x509_read($sslCertFile);
     if (!$certResource) {
         throw new \Exception("The provided certificate is either not a valid X509 certificate or could not be read.");
     }
     // Then the key. Does it match?
     $keyResource = openssl_pkey_get_private($sslKeyFile);
     if (!$keyResource) {
         throw new \Exception("The provided private key is either not a valid RSA private key or could not be read.");
     }
     $keyMatch = openssl_x509_check_private_key($certResource, $keyResource);
     if (!$keyMatch) {
         throw new \Exception("The provided certificate does not match the provided private key.");
     }
     // Each chain needs to be a valid cert.
     foreach ($sslChainFiles as $chainFile) {
         $chainResource = openssl_x509_read($chainFile);
         if (!$chainResource) {
             throw new \Exception("One of the provided certificates in the chain is not a valid X509 certificate.");
         } else {
             openssl_x509_free($chainResource);
         }
     }
     // Yay we win.
     $this->sslOptions = array('certificate' => $sslCertFile, 'key' => $sslKeyFile, 'chain' => $sslChainFiles);
     return true;
 }
Example #27
0
 /**
  * Decrypts RSA encrypted data using the given private key
  *
  * @throws Zend_InfoCard_Cipher_Exception
  * @param string $encryptedData The encrypted data in binary format
  * @param string $privateKey The private key in binary format
  * @param string $password The private key passphrase
  * @param integer $padding The padding to use during decryption (of not provided object value will be used)
  * @return string The decrypted data
  */
 public function decrypt($encryptedData, $privateKey, $password = null, $padding = null)
 {
     $private_key = openssl_pkey_get_private(array($privateKey, $password));
     if (!$private_key) {
         throw new Zend_InfoCard_Cipher_Exception("Failed to load private key");
     }
     if (!is_null($padding)) {
         try {
             $this->setPadding($padding);
         } catch (Exception $e) {
             openssl_free_key($private_key);
             throw $e;
         }
     }
     switch ($this->getPadding()) {
         case self::NO_PADDING:
             $openssl_padding = OPENSSL_NO_PADDING;
             break;
         case self::OAEP_PADDING:
             $openssl_padding = OPENSSL_PKCS1_OAEP_PADDING;
             break;
     }
     $result = openssl_private_decrypt($encryptedData, $decryptedData, $private_key, $openssl_padding);
     openssl_free_key($private_key);
     if (!$result) {
         throw new Zend_InfoCard_Cipher_Exception("Unable to Decrypt Value using provided private key");
     }
     if ($this->getPadding() == self::NO_PADDING) {
         $decryptedData = substr($decryptedData, 2);
         $start = strpos($decryptedData, 0) + 1;
         $decryptedData = substr($decryptedData, $start);
     }
     return $decryptedData;
 }
 protected function generateSignedJWT()
 {
     if (!file_exists($this->privateKey) || !is_file($this->privateKey)) {
         throw new Exception('Private key does not exist');
     }
     $header = array('alg' => 'RS256', 'typ' => 'JWT');
     $t = time();
     $params = array('iss' => $this->email, 'scope' => Oauth::SCOPE_URL, 'aud' => Oauth::TOKEN_URL, 'exp' => $t + self::MAX_LIFETIME_SECONDS, 'iat' => $t);
     $encodings = array(base64_encode(json_encode($header)), base64_encode(json_encode($params)));
     $input = implode('.', $encodings);
     $certs = array();
     $pkcs12 = file_get_contents($this->privateKey);
     if (!openssl_pkcs12_read($pkcs12, $certs, $this->password)) {
         throw new Exception('Could not parse .p12 file');
     }
     if (!isset($certs['pkey'])) {
         throw new Exception('Could not find private key in .p12 file');
     }
     $keyId = openssl_pkey_get_private($certs['pkey']);
     if (!openssl_sign($input, $sig, $keyId, 'sha256')) {
         throw new Exception('Could not sign data');
     }
     $encodings[] = base64_encode($sig);
     $jwt = implode('.', $encodings);
     return $jwt;
 }
Example #29
0
 public function __construct($p12, $password)
 {
     if (!function_exists('openssl_x509_read')) {
         throw new Google_Exception('The Google PHP API library needs the openssl PHP extension');
     }
     // If the private key is provided directly, then this isn't in the p12
     // format. Different versions of openssl support different p12 formats
     // and the key from google wasn't being accepted by the version available
     // at the time.
     if (!$password && strpos($p12, "-----BEGIN RSA PRIVATE KEY-----") !== false) {
         $this->privateKey = openssl_pkey_get_private($p12);
     } elseif ($password === 'notasecret' && strpos($p12, "-----BEGIN PRIVATE KEY-----") !== false) {
         $this->privateKey = openssl_pkey_get_private($p12);
     } else {
         // This throws on error
         $certs = array();
         if (!openssl_pkcs12_read($p12, $certs, $password)) {
             throw new Google_Auth_Exception("Unable to parse the p12 file.  " . "Is this a .p12 file?  Is the password correct?  OpenSSL error: " . openssl_error_string());
         }
         // TODO(beaton): is this part of the contract for the openssl_pkcs12_read
         // method?  What happens if there are multiple private keys?  Do we care?
         if (!array_key_exists("pkey", $certs) || !$certs["pkey"]) {
             throw new Google_Auth_Exception("No private key found in p12 file.");
         }
         $this->privateKey = openssl_pkey_get_private($certs['pkey']);
     }
     if (!$this->privateKey) {
         throw new Google_Auth_Exception("Unable to load private key");
     }
 }
    /**
     * Prepares the environment before running a test.
     */
    protected function setUp()
    {
        parent::setUp();
        $private_key = <<<EOD
-----BEGIN RSA PRIVATE KEY-----
Proc-Type: 4,ENCRYPTED
DEK-Info: DES-EDE3-CBC,2BB1348F45867303

9+e/kJCKUTnJLrNYY1iSjX+e6IVPo31dN20ab3O1BknT5c28PLjJbQkJz479VCX8
zJen/OyugesHXiQe5skPaG6+xwWGnztIxjHCLT5WtRE755UT3K83IeDde1zsK9xy
Iy8aRZbfBKCkgriIRNgD496gaVgEOGljEhCCIBLWERNZntcGmaBmN6CUdg75uuTI
HMX+2cA68yzRx31cU6EYdzB2vN93aLNuPI1u2ebFe7kuNYhW3d9Bc5MJh7iQdOfO
Yf94Xuic+2vIvwxi30Htz0wTBmTdEolDsSWzuyj7pjtUa0zZqaawCwLMYJFtz8lm
M2c5PXv8VvLBFIsTXWdy5+qDWMeROl1PaSDQ7HfAq8BtwNqV2yMKLE6cwHIWbYr/
lyIcBEhAZ8jfM81AWCgyAyeGSi4xGoCljxptExEwVzBJGjH93Ly6M7tjLBLmEQJM
nGmcY/3lmSMQIbxHV4ktXukPMrYYaTu5DW9jE+sNUHj+iUN/jJMTdOGh8zUtOQTs
qGuZBJbmjxdfSogCBL3f+JqOtRYUIIsZWEgb/AC10PC4pBit+9Cs9Z1LDMynFjKH
kGX/qgro2rPLiqR8o2dI/wCIa5sJhUT5vFC5N+Jn0jyhROK+eom4yEF0xX3DxSZY
iiclKgIOL/iB7FYEYFO17kUjFj8g53QWKh4tML/UG4GTIetNjD2u8wbobE7SxzZf
HHJXc4OblK/6GVpLn7yxZ5/EG7vtX/R4aPA70VFSkJYUd0xHWjUihss+9/TSIj/K
Cgpm3sdinamuC5b40tVhFhrfZyfUlqmssjU1nOsbnS+EqFgQJimbDg==
-----END RSA PRIVATE KEY-----
EOD;
        $rsa_private_key = @openssl_pkey_get_private($private_key, 'shindig');
        $basicFetcher = $this->getMock('RemoteContentFetcher');
        $this->signingFetcher = SigningFetcher::makeFromOpenSslPrivateKey($basicFetcher, 'http://shindig/public.cer', $rsa_private_key);
    }