Beispiel #1
2
 /**
  * @param string $pkcs12
  * @param string $password
  *
  * @throws Exception
  */
 public function load($pkcs12, string $password = NULL)
 {
     if (is_null($pkcs12)) {
         return;
     }
     if ($pkcs12 instanceof File) {
         $pkcs12 = $pkcs12->getContent();
     }
     if ($pkcs12 instanceof SplFileInfo) {
         $pkcs12 = file_get_contents($pkcs12);
     }
     if (!openssl_pkcs12_read($pkcs12, $result, $password)) {
         throw new RuntimeException(OpenSSL::getLastError());
     }
     if (array_key_exists('cert', $result)) {
         $certificate = new Certificate($result['cert']);
         $this->setCertificate($certificate);
     }
     if (array_key_exists('pkey', $result)) {
         $privateKey = new PrivateKey($result['pkey']);
         $this->setPrivateKey($privateKey);
     }
     if (array_key_exists('extracerts', $result)) {
         $this->setChain($result['extracerts']);
     }
 }
 /**
  * @param   Entity\CloudCredentials $entity
  * @param   Entity\CloudCredentials $prevConfig
  *
  * @throws  ApiErrorException
  */
 public function validateEntity($entity, $prevConfig = null)
 {
     parent::validateEntity($entity, $prevConfig);
     $ccProps = $entity->properties;
     $prevCcProps = isset($prevConfig) ? $prevConfig->properties : null;
     if ($this->needValidation($ccProps, $prevCcProps)) {
         $ccProps[Entity\CloudCredentialsProperty::GCE_ACCESS_TOKEN] = "";
         try {
             $client = new \Google_Client();
             $client->setApplicationName("Scalr GCE");
             $client->setScopes(['https://www.googleapis.com/auth/compute']);
             $key = base64_decode($ccProps[Entity\CloudCredentialsProperty::GCE_KEY]);
             // If it's not a json key we need to convert PKCS12 to PEM
             if (!$ccProps[Entity\CloudCredentialsProperty::GCE_JSON_KEY]) {
                 @openssl_pkcs12_read($key, $certs, 'notasecret');
                 $key = $certs['pkey'];
             }
             $client->setAuthConfig(['type' => 'service_account', 'project_id' => $ccProps[Entity\CloudCredentialsProperty::GCE_PROJECT_ID], 'private_key' => $key, 'client_email' => $ccProps[Entity\CloudCredentialsProperty::GCE_SERVICE_ACCOUNT_NAME], 'client_id' => $ccProps[Entity\CloudCredentialsProperty::GCE_CLIENT_ID]]);
             $client->setClientId($ccProps[Entity\CloudCredentialsProperty::GCE_CLIENT_ID]);
             $gce = new \Google_Service_Compute($client);
             $gce->zones->listZones($ccProps[Entity\CloudCredentialsProperty::GCE_PROJECT_ID]);
         } catch (Exception $e) {
             throw new ApiErrorException(400, ErrorMessage::ERR_INVALID_VALUE, "Provided GCE credentials are incorrect: ({$e->getMessage()})");
         }
         $entity->status = Entity\CloudCredentials::STATUS_ENABLED;
     }
 }
Beispiel #3
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");
     }
 }
Beispiel #4
0
 /**
  * @param $p12buf
  * @param $p12cert
  * @param $password
  * @return array
  * @throws \Exception
  */
 private static function pkcs12Read($p12buf, array $p12cert, $password)
 {
     if (!openssl_pkcs12_read($p12buf, $p12cert, $password)) {
         throw new \RuntimeException("Invalid cert format or password.");
     }
     return $p12cert;
 }
Beispiel #5
0
/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KdyF0RY+djo
b3cR9I7+hurpqhJmQ7yuvAWe2xWc+YNTQ48FDJTogXlB
-----END RSA PRIVATE KEY-----
"
  ["extracerts"]=>
  array(0) {
  }
}
*/
function cfcasign_pkcs12($plainText)
{
    $p12cert = array();
    //①读取公匙文件内容:二进制数据
    $file = 'ceshi/test.pfx';
    //二进制文件
    $fd = fopen($file, 'r');
    //只读模式打开文件
    $p12buf = fread($fd, filesize($file));
    //读取文件
    fclose($fd);
    /**
     * bool openssl_pkcs12_read ( string $pkcs12 , array &$certs , string $pass  )
     * 把以公匙加密标准证书存放区($pkcs12)转为数组存储($certs)
     * $pass:解开公匙加密标准证书存放区加密的密码
     */
    //②转为数组
    openssl_pkcs12_read($p12buf, $p12cert, 'cfca1234');
    $pkeyid = $p12cert["pkey"];
    $binary_signature = "";
    /**
     * bool openssl_sign ( string $data , string &$signature , mixed $priv_key_id [, int $signature_alg = OPENSSL_ALGO_SHA1 ] )
     * 生成签名
     * $data:特殊数据
     * $signature:如果成功,生成的签名(二进制数)
     * $priv_key_id:用于加密sha散列法生成的数据
     * 注意:$data没被加密过
     */
    openssl_sign($plainText, $binary_signature, $pkeyid, OPENSSL_ALGO_SHA1);
    return bin2hex($binary_signature);
    //将二进制数据转换成十六进制表示
}
Beispiel #6
0
 /**
  * @param \Scalr_Environment $environment             Scalr Environment object
  * @param array              $config        optional  Config array
  * @return \Google_Service_Compute
  */
 public function getClient(\Scalr_Environment $environment = null, array $config = [])
 {
     $ccProps = null;
     if (empty($config)) {
         $ccProps = $environment->keychain(\SERVER_PLATFORMS::GCE)->properties;
         $config = $ccProps;
     }
     $client = new \Google_Client();
     $client->setApplicationName("Scalr GCE");
     $client->setScopes(array('https://www.googleapis.com/auth/compute'));
     $key = base64_decode($config[Entity\CloudCredentialsProperty::GCE_KEY]);
     // If it's not a json key we need to convert PKCS12 to PEM
     if (!$config[Entity\CloudCredentialsProperty::GCE_JSON_KEY]) {
         @openssl_pkcs12_read($key, $certs, 'notasecret');
         $key = $certs['pkey'];
     }
     $client->setAuthConfig(['type' => 'service_account', 'project_id' => $config[Entity\CloudCredentialsProperty::GCE_PROJECT_ID], 'private_key' => $key, 'client_email' => $config[Entity\CloudCredentialsProperty::GCE_SERVICE_ACCOUNT_NAME], 'client_id' => $config[Entity\CloudCredentialsProperty::GCE_CLIENT_ID]]);
     $client->setClientId($config[Entity\CloudCredentialsProperty::GCE_CLIENT_ID]);
     $gce = new \Google_Service_Compute($client);
     //**** Store access token ****//
     $jsonAccessToken = $config[Entity\CloudCredentialsProperty::GCE_ACCESS_TOKEN];
     $accessToken = @json_decode($jsonAccessToken);
     if ($accessToken && $accessToken->created + $accessToken->expires_in > time()) {
         $client->setAccessToken($jsonAccessToken);
     } else {
         $gce->zones->listZones($config[Entity\CloudCredentialsProperty::GCE_PROJECT_ID]);
         if ($ccProps) {
             $token = $client->getAccessToken();
             $ccProps[Entity\CloudCredentialsProperty::GCE_ACCESS_TOKEN] = $token;
             $ccProps->save();
         }
     }
     return $gce;
 }
 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;
 }
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']);
}
 /**
  * @return string A plaintext private key in PEM format
  *
  * @throws \Exception When the pkcs12 string cannot be decrypted
  */
 private function decryptPKCS12string()
 {
     $keystore = [];
     if (!@openssl_pkcs12_read($this->pkcs12string, $keystore, $this->passphrase)) {
         throw new \Exception('PKCS#12 cannot be decrypted');
     }
     return $keystore['pkey'];
 }
 public function read()
 {
     $data = array();
     if (!openssl_pkcs12_read($this->content, $data, $this->password)) {
         throw new \Exception('O certificado não pode ser lido, senha ou arquivo inválido');
     }
     $this->certificate->setPubKey($data['cert']);
     $this->certificate->setPrivKey($data['pkey']);
 }
 /**
  * Method to retrieve the private key from the p12 file
  *
  * @return Private key string
  */
 private function getPrivateKey($masterPassData)
 {
     $thispath = dirname(__DIR__) . "/" . $masterPassData->keystorePath;
     $path = realpath($thispath);
     $keystore = array();
     $pkcs12 = file_get_contents($path);
     trim(openssl_pkcs12_read($pkcs12, $keystore, $masterPassData->keystorePassword));
     return $keystore['pkey'];
 }
 /**
  * Abre um certificado enviado com a senha informada
  * @param  string $password A senha necessária para abrir o certificado
  * @return array  Com os dados extraidos do certificado
  * @throws CannotOpenCertificate Caso a senha do certificado for inválida
  * @since  1.0.0
  */
 public function open($password)
 {
     $key = file_get_contents($this->filePath);
     $dataCertificate = array();
     if (!openssl_pkcs12_read($key, $dataCertificate, $password)) {
         throw new CannotOpenCertificate($this->filePath);
     }
     return $dataCertificate;
 }
Beispiel #13
0
 public function GetPrivate_Public_KeyFromPfxFile($filePath, $Passphase)
 {
     $p12cert = array();
     $fp = fopen($filePath, "r");
     $p12buf = fread($fp, filesize($filePath));
     fclose($fp);
     openssl_pkcs12_read($p12buf, $p12cert, $Passphase);
     $this->RsaPrivateKey = $p12cert['pkey'];
     $this->RsaPublicKey = $p12cert['cert'];
 }
Beispiel #14
0
 /**
  * Represents a PKCS12 keystore.
  * @param string $contents The contents of the PKCS12 keystore.
  */
 public function __construct($contents, $passphrase)
 {
     if (!extension_loaded('openssl')) {
         throw new OpenSSLExtensionNotLoadedException('The openssl module is not loaded.');
     }
     if (!openssl_pkcs12_read($contents, $keystore, $passphrase)) {
         throw new KeyStoreDecryptionFailedException('Could not decrypt the certificate, the passphrase is incorrect, ' . 'its contents are mangled or it is not a valid PKCS #12 keystore.');
     }
     $this->X509Certificate = new X509Certificate($keystore['cert']);
     $this->privateKey = new PrivateKey($keystore['pkey']);
 }
 /**
  * @param string $certificate
  * @param null|string $pass
  * @return bool
  * @throws Exception If could not open/parse certificate
  */
 public function loadString($certificate, $pass = null)
 {
     //unset cached certData
     //TODO: think Maybe disable loading of different certificate with some magic
     $this->certData = null;
     openssl_pkcs12_read($certificate, $this->raw_cert, $pass);
     if (!$this->raw_cert) {
         throw new Exception('Could not open certificate!');
     }
     return true;
 }
Beispiel #16
0
 function cfcasign_pkcs12($plainText)
 {
     $p12cert = array();
     $file = $this->CICC_REAL['PFX_PATH'];
     $fd = fopen($file, 'r');
     $p12buf = fread($fd, filesize($file));
     fclose($fd);
     openssl_pkcs12_read($p12buf, $p12cert, $this->CICC_REAL['PFX_PASS']);
     $pkeyid = $p12cert["pkey"];
     $binary_signature = "";
     openssl_sign($plainText, $binary_signature, $pkeyid, OPENSSL_ALGO_SHA1);
     return bin2hex($binary_signature);
 }
Beispiel #17
0
 public function Certificate($path, $cert_password = '')
 {
     $this->path = $path;
     $this->cert_password = $cert_password;
     if (file_exists($this->path) == false) {
         return $this;
     }
     $pkcs12 = file_get_contents($this->path);
     if (openssl_pkcs12_read($pkcs12, $this->certs, $cert_password) == true) {
         $this->cert_data = openssl_x509_read($this->certs['cert']);
         $this->cert_info = openssl_x509_parse($this->cert_data);
     }
 }
Beispiel #18
0
 /**
  * Archive creator for phar, tar, tgz and zip archives.
  *
  * @param string path to primary archive
  * @param string|false stub or false to use default stub of phar archives
  * @param int one of Phar::TAR, Phar::PHAR, or Phar::ZIP
  * @param int if the archive can be compressed (phar and tar), one of Phar::GZ, Phar::BZ2 or Phar::NONE
  *            for no compression
  * @param array an array of arrays containing information on additional archives to create.  The indices are:
  *
  *               0. extension (tar/tgz/zip)
  *               1. format (Phar::TAR, Phar::ZIP, Phar::PHAR)
  *               2. compression (Phar::GZ, Phar::BZ2, Phar::NONE)
  * @param string PKCS12 certificate to be used to sign the archive.  This must be a certificate issued
  *               by a certificate authority, self-signed certs will not be accepted by Pyrus
  * @param string passphrase, if any, for the PKCS12 certificate.
  */
 function __construct($path, $stub = false, $fileformat = \Phar::TAR, $compression = \Phar::GZ, array $others = null, $releaser = null, \PEAR2\Pyrus\Package $new = null, $pkcs12 = null, $passphrase = '')
 {
     if (!class_exists('Phar')) {
         throw new \PEAR2\Pyrus\Developer\Creator\Exception('Phar extension is not available');
     }
     if (!\Phar::canWrite() || !\Phar::isValidPharFilename($path, true)) {
         $this->_classname = 'PharData';
     }
     $this->path = $path;
     $this->compression = $compression;
     $this->format = $fileformat;
     $this->others = $others;
     $this->stub = $stub;
     if ($pkcs12 && !extension_loaded('openssl')) {
         throw new \PEAR2\Pyrus\Developer\Creator\Exception('Unable to use ' . 'OpenSSL signing of phars, enable the openssl PHP extension');
     }
     $this->pkcs12 = $pkcs12;
     $this->passphrase = $passphrase;
     if (null !== $this->pkcs12) {
         $cert = array();
         $pkcs = openssl_pkcs12_read(file_get_contents($this->pkcs12), $cert, $this->passphrase);
         if (!$pkcs) {
             throw new \PEAR2\Pyrus\Developer\Creator\Exception('Unable to process openssl key');
         }
         $private = openssl_pkey_get_private($cert['pkey']);
         if (!$private) {
             throw new \PEAR2\Pyrus\Developer\Creator\Exception('Unable to extract private openssl key');
         }
         $pub = openssl_pkey_get_public($cert['cert']);
         $info = openssl_x509_parse($cert['cert']);
         $details = openssl_pkey_get_details($pub);
         if (true !== openssl_x509_checkpurpose($cert['cert'], X509_PURPOSE_SSL_SERVER, \PEAR2\Pyrus\Channel\RemotePackage::authorities())) {
             throw new \PEAR2\Pyrus\Developer\Creator\Exception('releasing maintainer\'s certificate is invalid');
         }
         // now verify that this cert is in fact the releasing maintainer's certificate
         // by verifying that alternate name is the releaser's email address
         if (!isset($info['subject']) || !isset($info['subject']['emailAddress'])) {
             throw new \PEAR2\Pyrus\Developer\Creator\Exception('releasing maintainer\'s certificate does not contain' . ' an alternate name corresponding to the releaser\'s email address');
         }
         if ($info['subject']['emailAddress'] != $new->maintainer[$releaser]->email) {
             throw new \PEAR2\Pyrus\Developer\Creator\Exception('releasing maintainer\'s certificate ' . 'alternate name does not match the releaser\'s email address ' . $new->maintainer[$releaser]->email);
         }
         $pkey = '';
         openssl_pkey_export($private, $pkey);
         $this->x509cert = $cert['cert'];
         $this->publickey = $details['key'];
         $this->privatekey = $pkey;
     }
 }
 /**
  * Construct
  *
  * @param String $certificate P12 file
  * @param String $passphrase  Passphrase for the certificate
  * @param bool   $path        The certificate variable is a path
  */
 function __construct($certificate, $passphrase = null, $path = true)
 {
     if ($path) {
         $this->certificate_path = $certificate;
         $certificate = file_get_contents($certificate);
         //Il est important que le certificat soit en p12
         openssl_pkcs12_read($certificate, $array_cert, $passphrase);
         $this->certificate = $array_cert["cert"];
         $this->pivate_key = $array_cert["pkey"];
         $this->chain = $array_cert["extracerts"];
     } else {
         $this->certificate = $certificate;
     }
     $this->passphrase = $passphrase;
 }
/**
 * 
 * [rsa_sign description]
 * @param  [string] $pfx  [pfx 证书]
 * @param  [string] $pwd  [pfx 密码]
 * @param  [string] $data [要加密的内容]
 * @return [string]       [description]
 */
function rsa_sign1($pfx, $pwd, $data)
{
    //1、使用密码读取证书
    openssl_pkcs12_read(file_get_contents($pfx), $cert_arr, $pwd);
    //2、验证证书是否在有效期内
    $cer = openssl_x509_parse($cert_arr['cert']);
    //3、取得密钥
    $pkey = openssl_get_privatekey($cert_arr['pkey']);
    $signature = '';
    $data = strval($data);
    if (!openssl_sign($data, $signature, $pkey, OPENSSL_ALGO_SHA1)) {
        return null;
    }
    $signature = base64_encode($signature);
    return $signature;
}
Beispiel #21
0
 public function getPrivateKey()
 {
     $keystorePath = "";
     $keystorePassword = "";
     if ($this->environment == Environment::PRODUCTION) {
         $keystorePath = self::PRODUCTION_KEYSTORE_PATH;
         $keystorePassword = self::PRODUCTION_KEYSTORE_PASSWORD;
     } else {
         $keystorePath = self::SANDBOX_KEYSTORE_PATH;
         $keystorePassword = self::SANDBOX_KEYSTORE_PASSWORD;
     }
     $path = realpath($keystorePath);
     $keystore = array();
     $pkcs12 = file_get_contents($path);
     trim(openssl_pkcs12_read($pkcs12, $keystore, $keystorePassword));
     return $keystore['pkey'];
 }
Beispiel #22
0
 /**
  * Fetch the private CERT key for the signature
  * 
  * @param OAuthRequest request
  * @return string private key
  */
 protected function fetch_private_cert(&$request)
 {
     $passphrase = 'replace-this-withp12-cert-password';
     $pkcs12 = file_get_contents("replace-this-with-pl2-filename");
     $certs = array();
     if (!openssl_pkcs12_read($pkcs12, $certs, $passphrase)) {
         throw new OAuthException("Unable to parse the p12 file.  " . "Is this a .p12 file?  Is the password correct?  OpenSSL error: " . openssl_error_string());
     }
     if (!array_key_exists("pkey", $certs) || !$certs["pkey"]) {
         throw new OAuthException("No private key found in p12 file.");
     }
     $privateKey = openssl_pkey_get_private($certs["pkey"]);
     if (!$privateKey) {
         throw new OAuthException("Unable to load private key in ");
     }
     return $privateKey;
 }
Beispiel #23
0
 /**
  * Constructor para la clase: crea configuración y carga certificado digital
  *
  * Si se desea pasar una configuración específica para la firma electrónica
  * se debe hacer a través de un arreglo con los índices file y pass, donde
  * file es la ruta hacia el archivo .p12 que contiene tanto la clave privada
  * como la pública y pass es la contraseña para abrir dicho archivo.
  * Ejemplo:
  *
  * \code{.php}
  *   $firma_config = ['file'=>'/ruta/al/certificado.p12', 'pass'=>'contraseña'];
  *   $firma = new \sasco\LibreDTE\FirmaElectronica($firma_config);
  * \endcode
  *
  * @param config Configuración para la cllase, si no se especifica se trarará de determinar
  * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
  * @version 2014-12-08
  */
 public function __construct($config = [])
 {
     // crear configuración
     if (!$config and class_exists('\\sowerphp\\core\\Configure')) {
         $config = (array) \sowerphp\core\Configure::read('firma_electronica.default');
     }
     $this->config = array_merge(['file' => (defined('DIR_PROJECT') ? DIR_PROJECT . '/data/firma_electronica/' : '') . 'default.p12', 'pass' => '', 'wordwrap' => 64], $config);
     // cargar certificado digital
     if (file_exists($this->config['file'])) {
         $pkcs12 = file_get_contents($this->config['file']);
         if (openssl_pkcs12_read($pkcs12, $this->certs, $this->config['pass']) === false) {
             $this->error('Contraseña incorrecta para la firma electrónica ' . basename($this->config['file']));
         }
     } else {
         $this->error('Archivo de la firma electrónica ' . basename($this->config['file']) . ' no existe');
     }
 }
 /**
  * Builds and returns a JWT (JSON Web Signature) to submit to Google's
  * OAuth2 endpoint. See https://developers.google.com/accounts/docs/OAuth2ServiceAccount
  * for documentation on the contents of this signature.
  *
  * @return string
  */
 private function _getJWT()
 {
     $header = array('alg' => 'RS256', 'typ' => 'JWT');
     $requestTime = time();
     $claimSet = array('iss' => $this->_user, 'scope' => $this->_scope, 'aud' => $this->_authTarget, 'exp' => $requestTime + 3600, 'iat' => $requestTime);
     if ($this->_onBehalfOfUser !== null) {
         $claimSet['sub'] = $this->_onBehalfOfUser;
     }
     $payload = base64_encode(json_encode($header)) . '.' . base64_encode(json_encode($claimSet));
     $cert = array();
     if (!openssl_pkcs12_read(file_get_contents($this->_keyFile), $cert, 'notasecret')) {
         throw new RuntimeException('Unable to load private key from file.');
     }
     $signature = '';
     if (!openssl_sign($payload, $signature, $cert['pkey'], 'sha256')) {
         throw new RuntimeException('Unable to generate signature.');
     }
     return $payload . '.' . base64_encode($signature);
 }
 function __construct($p12, $password)
 {
     if (!function_exists('openssl_x509_read')) {
         throw new Exception('The Google PHP API library needs the openssl PHP extension');
     }
     // This throws on error
     $certs = array();
     if (!openssl_pkcs12_read($p12, $certs, $password)) {
         throw new Google_AuthException("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_AuthException("No private key found in p12 file.");
     }
     $this->privateKey = openssl_pkey_get_private($certs["pkey"]);
     if (!$this->privateKey) {
         throw new Google_AuthException("Unable to load private key in ");
     }
 }
function create_signature($package_dir, $cert_path, $cert_password)
{
    // Load the push notification certificate
    $pkcs12 = file_get_contents($cert_path);
    $certs = array();
    if (!openssl_pkcs12_read($pkcs12, $certs, $cert_password)) {
        return;
    }
    $signature_path = "{$package_dir}/signature";
    // Sign the manifest.json file with the private key from the certificate
    $cert_data = openssl_x509_read($certs['cert']);
    $private_key = openssl_pkey_get_private($certs['pkey'], $cert_password);
    openssl_pkcs7_sign("{$package_dir}/manifest.json", $signature_path, $cert_data, $private_key, array(), PKCS7_BINARY | PKCS7_DETACHED);
    // Convert the signature from PEM to DER
    $signature_pem = file_get_contents($signature_path);
    $matches = array();
    if (!preg_match('~Content-Disposition:[^\\n]+\\s*?([A-Za-z0-9+=/\\r\\n]+)\\s*?-----~', $signature_pem, $matches)) {
        return;
    }
    $signature_der = base64_decode($matches[1]);
    file_put_contents($signature_path, $signature_der);
}
Beispiel #27
0
 public function testGetPKCS12SelfSigned()
 {
     $countryName = "US";
     $stateOrProvinceName = "Georgia";
     $localityName = "Roswell";
     $organizationName = "Werx Limited";
     $organizationalUnitName = "";
     $commonName = "Wes Widner";
     $emailAddress = "*****@*****.**";
     $pks12 = $this->object->getPKCS12SelfSigned($countryName, $stateOrProvinceName, $localityName, $organizationName, $organizationalUnitName, $commonName, $emailAddress);
     $this->assertNotNull($pks12, "PKCS12 cert not generated properly");
     openssl_pkcs12_read($pks12, $data, null);
     $this->assertNotNull($data, "PKCS12 Data not read properly");
     $this->assertNotNull($data['cert'], "PKCS12 Cert data does not exist");
     $certdata = openssl_x509_parse($data['cert']);
     $this->assertEquals($certdata['subject']['C'], $countryName, "PKCS12 Country does not match");
     $this->assertEquals($certdata['subject']['ST'], $stateOrProvinceName, "PKCS12 State does not match");
     $this->assertEquals($certdata['subject']['L'], $localityName, "PKCS12 Locality does not match");
     $this->assertEquals($certdata['subject']['O'], $organizationName, "PKCS12 Orginization name does not match");
     $this->assertEquals($certdata['subject']['OU'], $organizationalUnitName, "PKCS12 Orginization unit name does not match");
     $this->assertEquals($certdata['subject']['CN'], $commonName, "PKCS12 Common name does not match");
     $this->assertEquals($certdata['subject']['emailAddress'], $emailAddress, "PKCS12 Email address does not match");
 }
 /**
  * @param string              $merchantName name of the merchant
  * @param string|\SplFileInfo $pkcs12       filename or content of the certificate file
  * @param string              $password     certificate password
  * @param string              $uuid         uuid
  *
  * @throws \Exception
  */
 public function __construct($merchantName, $pkcs12, $password, $uuid)
 {
     $this->merchantName = $merchantName;
     $this->certificatePassword = $password;
     $this->uuid = $uuid;
     if (!$merchantName || !$password) {
         throw new \RuntimeException('Invalid QPay Api credentials');
     }
     if ($pkcs12 instanceof \SplFileInfo) {
         $pkcs12 = $pkcs12->getRealPath();
     }
     if (file_exists($pkcs12)) {
         $pkcs12 = file_get_contents($pkcs12);
     } else {
         $fileInfo = new \SplFileInfo($pkcs12);
         $message = sprintf('The certificate file called "%s" could not be found.', $fileInfo->getPathname());
         throw new FileNotFoundException($message);
     }
     $certs = [];
     if (openssl_pkcs12_read($pkcs12, $certs, $password)) {
         if (isset($certs['cert'])) {
             $this->setClientCertificate($certs['cert']);
         }
         if (isset($certs['pkey'])) {
             $this->setCertificateKey($certs['pkey']);
         }
         if (isset($certs['extracerts'])) {
             $content = '';
             foreach ($certs['extracerts'] as $caCert) {
                 $content .= $caCert;
             }
             $this->setAuthorityCertificate($content);
         }
     } else {
         throw new \Exception(openssl_error_string());
     }
 }
Beispiel #29
0
 private function loadCert()
 {
     $x509CertData = array();
     if (!openssl_pkcs12_read(file_get_contents($this->pkcs12), $x509CertData, $this->passphrase)) {
         error_log(__METHOD__ . ': Certificate cannot be read. File is corrupted or invalid format.');
         return false;
     }
     $this->X509Certificate = preg_replace("/[\n]/", '', preg_replace('/\\-\\-\\-\\-\\-[A-Z]+ CERTIFICATE\\-\\-\\-\\-\\-/', '', $x509CertData['cert']));
     if (!self::validateCert($x509CertData['cert'])) {
         return false;
     }
     if (!is_dir($this->certDir)) {
         if (!mkdir($this->certDir, 0777)) {
             error_log(__METHOD__ . ': Cannot create folder ' . $this->certDir);
             return false;
         }
     }
     if (!file_exists($this->privateKey)) {
         if (!file_put_contents($this->privateKey, $x509CertData['pkey'])) {
             error_log(__METHOD__ . ': Cannot create file ' . $this->privateKey);
             return false;
         }
     }
     if (!file_exists($this->publicKey)) {
         if (!file_put_contents($this->publicKey, $x509CertData['cert'])) {
             error_log(__METHOD__ . ': Cannot create file ' . $this->publicKey);
             return false;
         }
     }
     if (!file_exists($this->key)) {
         if (!file_put_contents($this->key, $x509CertData['cert'] . $x509CertData['pkey'])) {
             error_log(__METHOD__ . ': Cannot create file ' . $this->key);
             return false;
         }
     }
     return true;
 }
Beispiel #30
0
 private function loadCert()
 {
     $x509CertData = array();
     if (!openssl_pkcs12_read(file_get_contents($this->pkcs12), $x509CertData, $this->passphrase)) {
         error_log(__METHOD__ . ': Certificado não pode ser lido. O arquivo esta corrompido ou em formato invalido.');
         return false;
     }
     $this->X509Certificate = preg_replace("/[\n]/", '', preg_replace('/\\-\\-\\-\\-\\-[A-Z]+ CERTIFICATE\\-\\-\\-\\-\\-/', '', $x509CertData['cert']));
     if (!self::validateCert($x509CertData['cert'])) {
         return false;
     }
     if (!is_dir($this->certDir)) {
         if (!mkdir($this->certDir, 0777)) {
             error_log(__METHOD__ . ': Falha ao criar o diretorio ' . $this->certDir);
             return false;
         }
     }
     if (!file_exists($this->privateKey)) {
         if (!file_put_contents($this->privateKey, $x509CertData['pkey'])) {
             error_log(__METHOD__ . ': Falha ao criar o arquivo ' . $this->privateKey);
             return false;
         }
     }
     if (!file_exists($this->publicKey)) {
         if (!file_put_contents($this->publicKey, $x509CertData['cert'])) {
             error_log(__METHOD__ . ': Falha ao criar o arquivo ' . $this->publicKey);
             return false;
         }
     }
     if (!file_exists($this->key)) {
         if (!file_put_contents($this->key, $x509CertData['cert'] . $x509CertData['pkey'])) {
             error_log(__METHOD__ . ': Falha ao criar o arquivo ' . $this->key);
             return false;
         }
     }
     return true;
 }