Exemplo n.º 1
0
 /**
  * Generates a new key pair with the given length in bits.
  *
  * @api
  * @param int $bits length of the key
  * @return KeyPair generated key pair
  */
 public function generate($bits = 2048)
 {
     if (!is_int($bits)) {
         throw new \InvalidArgumentException(sprintf("\$bits must be of type int, %s given", gettype($bits)));
     }
     if ($bits < 2048) {
         throw new \InvalidArgumentException("Keys with fewer than 2048 bits are not allowed!");
     }
     $configFile = $defaultConfigFile = __DIR__ . "/../res/openssl.cnf";
     if (class_exists("Phar") && !empty(Phar::running(true))) {
         $configContent = file_get_contents($configFile);
         $configFile = tempnam(sys_get_temp_dir(), "acme_openssl_");
         file_put_contents($configFile, $configContent);
         register_shutdown_function(function () use($configFile) {
             @unlink($configFile);
         });
     }
     $res = openssl_pkey_new(["private_key_type" => OPENSSL_KEYTYPE_RSA, "private_key_bits" => $bits, "config" => $configFile]);
     $success = openssl_pkey_export($res, $privateKey, null, ["config" => $configFile]);
     if ($configFile !== $defaultConfigFile) {
         @unlink($configFile);
     }
     if (!$success) {
         openssl_pkey_free($res);
         throw new \RuntimeException("Key export failed!");
     }
     $publicKey = openssl_pkey_get_details($res)["key"];
     openssl_pkey_free($res);
     // clear error buffer, because of minimalistic openssl.cnf
     while (openssl_error_string() !== false) {
     }
     return new KeyPair($privateKey, $publicKey);
 }
Exemplo n.º 2
0
 /**
  * Generate public and private key
  * @param array $options
  */
 public function generateKeys(array $options = self::DEFAULT_PUBLIC_KEY_OPTIONS)
 {
     $keys = openssl_pkey_new($options);
     $this->publicKey = openssl_pkey_get_details($keys)["key"];
     openssl_pkey_export($keys, $this->privateKey);
     openssl_pkey_free($keys);
 }
Exemplo n.º 3
0
 /**
  * Frees the resource associated with this private key.
  * This is automatically done on destruct.
  */
 private function free()
 {
     if ($this->keyResource) {
         openssl_pkey_free($this->keyResource);
     }
     $this->keyResource = null;
 }
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']);
}
Exemplo n.º 5
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;
 }
Exemplo n.º 6
0
Arquivo: Key.php Projeto: blar/openssl
 public function __destruct()
 {
     if (!is_resource($this->handle)) {
         return;
     }
     openssl_pkey_free($this->handle);
 }
Exemplo n.º 7
0
 public function removeAll()
 {
     foreach ($this->resources as $resource) {
         openssl_pkey_free($resource);
     }
     $this->keys = array();
     $this->resources = array();
 }
Exemplo n.º 8
0
 /**
  * Generate a key pair (public / private key) with optional passphrase
  * that protects the private key.
  *
  * @param string $passphrase
  * @return KeyPair
  */
 public function generateKeyPair($passphrase = null)
 {
     $privateKey = null;
     $encrypted = $passphrase !== null;
     $keyPair = openssl_pkey_new();
     openssl_pkey_export($keyPair, $privateKey, $passphrase);
     $keyDetails = openssl_pkey_get_details($keyPair);
     $publicKey = $keyDetails['key'];
     openssl_pkey_free($keyPair);
     return new KeyPair($privateKey, $publicKey, $encrypted);
 }
 /**
  * Generate a key pair (public / private key) with optional passphrase
  * that protects the private key.
  *
  * @param string $passphrase
  * @return \TYPO3\Deploy\Encryption\KeyPair
  * @author Christopher Hlubek <*****@*****.**>
  */
 public function generateKeyPair($passphrase = NULL)
 {
     $privateKey = NULL;
     $encrypted = $passphrase !== NULL;
     $keyPair = openssl_pkey_new();
     openssl_pkey_export($keyPair, $privateKey, $passphrase);
     $keyDetails = openssl_pkey_get_details($keyPair);
     $publicKey = $keyDetails['key'];
     openssl_pkey_free($keyPair);
     return new \TYPO3\Deploy\Encryption\KeyPair($privateKey, $publicKey, $encrypted);
 }
Exemplo n.º 10
0
 /**
  * @param Signature $signature
  *
  * @return boolean Whether the signature has been signed by this certificate
  */
 public function hasSigned(Signature $signature)
 {
     $key = openssl_pkey_get_public($this->x509Cert);
     try {
         $hasSigned = $signature->isSignedByKey($key);
     } catch (\Excetpion $e) {
         openssl_pkey_free($key);
         throw $e;
     }
     openssl_pkey_free($key);
     return $hasSigned;
 }
Exemplo n.º 11
0
 /**
  * Sign a string using the configured private key
  *
  * @param string $str  The string to calculate a signature for
  */
 private function base64_signature($str)
 {
     $key = openssl_pkey_get_private($this->private_key);
     if ($key === false) {
         throw new SimpleSAML_Error_Exception("Unable to load private key: " . openssl_error_string());
     }
     if (!openssl_sign($str, $sig, $key)) {
         throw new SimpleSAML_Error_Exception("Unable to create signature: " . openssl_error_string());
     }
     openssl_pkey_free($key);
     return base64_encode($sig);
 }
Exemplo n.º 12
0
 protected function load()
 {
     if (false == is_file($this->filename)) {
         throw new \RuntimeException(sprintf("Specified private key file '%s' does not exist", $this->filename));
     }
     $this->loadedContent = file_get_contents($this->filename);
     $resource = openssl_pkey_get_private($this->loadedContent);
     if (false == $resource) {
         $this->loadedContent = null;
         throw new \RuntimeException(sprintf("Specified private key '%s' is invalid", $this->filename));
     }
     openssl_pkey_free($resource);
 }
 /**
  * Function to generate a new RSA keypair. This is not
  * used for point derivation or for generating signatures.
  * Only used for assymetric data encryption, as needed.
  *
  * @param int
  * @param string
  * @return array|boolean array of keys on success, boolean false on failure
  */
 public final function generateKeypair($keybits = 512, $digest_alg = 'sha512')
 {
     try {
         /* see: http://www.php.net/manual/en/function.openssl-pkey-new.php */
         if (function_exists('openssl_pkey_new')) {
             $keypair = array();
             /* openssl keysize can't be smaller than 384 bits */
             if ((int) $keybits < 384) {
                 $keybits = 384;
             }
             if (!isset($digest_alg) || trim($digest_alg) == '') {
                 $digest_alg = 'sha512';
             }
             /*
              * RSA is the only supported key type at this time
              * http://www.php.net/manual/en/function.openssl-csr-new.php
              */
             $config = array('digest_alg' => $digest_alg, 'private_key_bits' => (int) $keybits, 'private_key_type' => OPENSSL_KEYTYPE_RSA);
             $resource = openssl_pkey_new($config);
             if (!$resource) {
                 throw new \Exception('Error in generateOpenSSLKeypair: Could not create new OpenSSL resource.');
                 /* with the openssl extension, you also have it's own errors returned */
                 while ($msg = openssl_error_string()) {
                     throw new \Exception('Error in generateOpenSSLKeypair: OpenSSL reported error: ' . $msg);
                 }
                 return false;
             }
             if (openssl_pkey_export($resource, $keypair['pri'])) {
                 $publickey = openssl_pkey_get_details($resource);
                 $keypair['pub'] = $publickey['key'];
             } else {
                 throw new \Exception('Error in generateOpenSSLKeypair: Private key could not be determined from OpenSSL key resource.');
                 while ($msg = openssl_error_string()) {
                     throw new \Exception('Error in generateOpenSSLKeypair: OpenSSL reported error: ' . $msg);
                 }
                 return false;
             }
             openssl_pkey_free($resource);
             return $keypair;
         } else {
             throw new \Exception('Error in generateOpenSSLKeypair: OpenSSL PHP extension missing. Cannot continue.');
             return false;
         }
     } catch (Exception $e) {
         while ($msg = openssl_error_string()) {
             throw new \Exception('Error in generateOpenSSLKeypair: OpenSSL reported error: ' . $msg);
         }
         throw $e;
         return false;
     }
 }
Exemplo n.º 14
0
 /**
  * Returns a usable private and public key from a PEM encoded string.
  *
  * @param string $key  The private key.
  * @param string $pass The private key passphrase.
  *
  * @return array The private ([0]) and public ([1]) key.
  *
  * @throws InvalidArgumentException If a passphrase is required.
  * @throws RuntimeException         If the file could not be parsed.
  */
 public function parsePem($key, $pass = null)
 {
     $this->clearErrors();
     if (false === ($resource = openssl_pkey_get_private($key, $pass))) {
         $error = openssl_error_string();
         if (preg_match('/(bad password|bad decrypt)/', $error)) {
             throw new InvalidArgumentException('The private key passphrase is invalid.');
         }
         throw new RuntimeException("The private key could not be parsed: {$error}");
     }
     openssl_pkey_export($resource, $private);
     $details = openssl_pkey_get_details($resource);
     openssl_pkey_free($resource);
     return array($private, $details['key']);
 }
Exemplo n.º 15
0
 public function onPasswordChange(FormEvent $event)
 {
     // Get new password
     /** @var User $user */
     $user = $event->getForm()->getData();
     $password = $user->getPlainPassword();
     // Get pkey from session
     $privKey = $event->getRequest()->getSession()->get('pkey');
     // Secure pkey with new password
     $res = openssl_pkey_get_private($privKey);
     openssl_pkey_export($res, $privKey, $password);
     // Store pkey in user
     $user->setPrivateKey($privKey);
     unset($password);
     openssl_pkey_free($res);
     unset($privKey);
 }
Exemplo n.º 16
0
/**
 * Check if signature is correct
 * @param string SSH formatted public key
 * @param string
 * @param string
 * @return bool
 */
function verify($key, $data, $signature)
{
    if (($pkeyid = @openssl_pkey_get_public(ssh2pem($key))) === FALSE) {
        throw new Error('Cannot get public key.');
    }
    $details = openssl_pkey_get_details($pkeyid);
    list($keytype, $blob) = parse('ss', $signature);
    if ($details['type'] === OPENSSL_KEYTYPE_DSA && $keytype !== 'ssh-dss' || $details['type'] === OPENSSL_KEYTYPE_RSA && $keytype !== 'ssh-rsa') {
        throw new Error('Key/signature type mismatch.');
    }
    if ($keytype !== 'ssh-rsa') {
        throw new Error('FIXME: currently only ssh-rsa implemented');
    }
    $verified = @openssl_verify($data, $blob, $pkeyid);
    openssl_pkey_free($pkeyid);
    return $verified === 1;
}
/**
 * Post install hook implementation for the quizaccess_offlinemode plugin.
 */
function xmldb_quizaccess_offlinemode_install()
{
    global $OUTPUT;
    // If OpenSSL is available, generate a public/private key pair.
    if (function_exists('openssl_pkey_new')) {
        $privatekey = openssl_pkey_new(array('digest_alg' => 'sha512', 'private_key_bits' => 1024, 'private_key_type' => OPENSSL_KEYTYPE_RSA));
        if ($privatekey) {
            openssl_pkey_export($privatekey, $privatekeystring);
            $publickeydata = openssl_pkey_get_details($privatekey);
            openssl_pkey_free($privatekey);
            set_config('privatekey', $privatekeystring, 'quizaccess_offlinemode');
            set_config('publickey', $publickeydata['key'], 'quizaccess_offlinemode');
        } else {
            echo $OUTPUT->notification('Failed to generate an public/private key pair.');
            while ($message = openssl_error_string()) {
                echo $OUTPUT->notification($message);
            }
        }
    }
}
Exemplo n.º 18
0
 public function testKeyGen()
 {
     $fileName = 'testfile_ssl_id_rsa_' . date('Ymd_His') . '_' . uniqid('', true);
     $sslConfig = array('digest_alg' => 'sha512', 'private_key_bits' => 4096, 'private_key_type' => OPENSSL_KEYTYPE_RSA);
     $ssl = openssl_pkey_new($sslConfig);
     $this->assertTrue($ssl ? true : false);
     openssl_pkey_export_to_file($ssl, 'test_data/' . $fileName . '.prv');
     #fwrite(STDOUT, 'SSL ERROR: '.openssl_error_string()."\n");
     openssl_pkey_export_to_file($ssl, 'test_data/' . $fileName . '_pass.prv', 'my_password');
     #fwrite(STDOUT, 'SSL ERROR: '.openssl_error_string()."\n");
     $keyPub = openssl_pkey_get_details($ssl);
     #ve($keyPub);
     $keyPub = $keyPub['key'];
     file_put_contents('test_data/' . $fileName . '.pub', $keyPub);
     openssl_public_encrypt('test my keys', $encrypted, $keyPub);
     #fwrite(STDOUT, 'SSL ERROR: '.openssl_error_string()."\n");
     openssl_private_decrypt($encrypted, $decrypted, $ssl);
     #fwrite(STDOUT, 'SSL ERROR: '.openssl_error_string()."\n");
     $this->assertEquals('test my keys', $decrypted);
     openssl_pkey_free($ssl);
 }
Exemplo n.º 19
0
/**
 * Generate public/private keys and store in the config table
 *
 * Use the distinguished name provided to create a CSR, and then sign that CSR
 * with the same credentials. Store the keypair you create in the config table.
 * If a distinguished name is not provided, create one using the fullname of
 * 'the course with ID 1' as your organization name, and your hostname (as
 * detailed in $CFG->wwwroot).
 *
 * @param   array  $dn  The distinguished name of the server
 * @return  string      The signature over that text
 */
function mnet_generate_keypair($dn = null, $days = 28)
{
    global $CFG, $USER;
    // check if lifetime has been overriden
    if (!empty($CFG->mnetkeylifetime)) {
        $days = $CFG->mnetkeylifetime;
    }
    $host = strtolower($CFG->wwwroot);
    $host = ereg_replace("^http(s)?://", '', $host);
    $break = strpos($host . '/', '/');
    $host = substr($host, 0, $break);
    if ($result = get_record_select('course', " id ='" . SITEID . "' ")) {
        $organization = $result->fullname;
    } else {
        $organization = 'None';
    }
    $keypair = array();
    $country = 'NZ';
    $province = 'Wellington';
    $locality = 'Wellington';
    $email = $CFG->noreplyaddress;
    if (!empty($USER->country)) {
        $country = $USER->country;
    }
    if (!empty($USER->city)) {
        $province = $USER->city;
        $locality = $USER->city;
    }
    if (!empty($USER->email)) {
        $email = $USER->email;
    }
    if (is_null($dn)) {
        $dn = array("countryName" => $country, "stateOrProvinceName" => $province, "localityName" => $locality, "organizationName" => $organization, "organizationalUnitName" => 'Moodle', "commonName" => $CFG->wwwroot, "emailAddress" => $email);
    }
    $dnlimits = array('countryName' => 2, 'stateOrProvinceName' => 128, 'localityName' => 128, 'organizationName' => 64, 'organizationalUnitName' => 64, 'commonName' => 64, 'emailAddress' => 128);
    foreach ($dnlimits as $key => $length) {
        $dn[$key] = substr($dn[$key], 0, $length);
    }
    // ensure we remove trailing slashes
    $dn["commonName"] = preg_replace(':/$:', '', $dn["commonName"]);
    if (!empty($CFG->opensslcnf)) {
        //allow specification of openssl.cnf especially for Windows installs
        $new_key = openssl_pkey_new(array("config" => $CFG->opensslcnf));
        $csr_rsc = openssl_csr_new($dn, $new_key, array("config" => $CFG->opensslcnf));
        $selfSignedCert = openssl_csr_sign($csr_rsc, null, $new_key, $days, array("config" => $CFG->opensslcnf));
    } else {
        $new_key = openssl_pkey_new();
        $csr_rsc = openssl_csr_new($dn, $new_key, array('private_key_bits', 2048));
        $selfSignedCert = openssl_csr_sign($csr_rsc, null, $new_key, $days);
    }
    unset($csr_rsc);
    // Free up the resource
    // We export our self-signed certificate to a string.
    openssl_x509_export($selfSignedCert, $keypair['certificate']);
    openssl_x509_free($selfSignedCert);
    // Export your public/private key pair as a PEM encoded string. You
    // can protect it with an optional passphrase if you wish.
    if (!empty($CFG->opensslcnf)) {
        //allow specification of openssl.cnf especially for Windows installs
        $export = openssl_pkey_export($new_key, $keypair['keypair_PEM'], null, array("config" => $CFG->opensslcnf));
    } else {
        $export = openssl_pkey_export($new_key, $keypair['keypair_PEM']);
    }
    openssl_pkey_free($new_key);
    unset($new_key);
    // Free up the resource
    return $keypair;
}
Exemplo n.º 20
0
 /**
  * Generate a DKIM signature.
  * @access public
  * @param string $signHeader
  * @throws phpmailerException
  * @return string The DKIM signature value
  */
 public function DKIM_Sign($signHeader)
 {
     if (!defined('PKCS7_TEXT')) {
         if ($this->exceptions) {
             throw new phpmailerException($this->lang('extension_missing') . 'openssl');
         }
         return '';
     }
     $privKeyStr = file_get_contents($this->DKIM_private);
     if ('' != $this->DKIM_passphrase) {
         $privKey = openssl_pkey_get_private($privKeyStr, $this->DKIM_passphrase);
     } else {
         $privKey = openssl_pkey_get_private($privKeyStr);
     }
     //Workaround for missing digest algorithms in old PHP & OpenSSL versions
     //@link http://stackoverflow.com/a/11117338/333340
     if (version_compare(PHP_VERSION, '5.3.0') >= 0 and in_array('sha256WithRSAEncryption', openssl_get_md_methods(true))) {
         if (openssl_sign($signHeader, $signature, $privKey, 'sha256WithRSAEncryption')) {
             openssl_pkey_free($privKey);
             return base64_encode($signature);
         }
     } else {
         $pinfo = openssl_pkey_get_details($privKey);
         $hash = hash('sha256', $signHeader);
         //'Magic' constant for SHA256 from RFC3447
         //@link https://tools.ietf.org/html/rfc3447#page-43
         $t = '3031300d060960864801650304020105000420' . $hash;
         $pslen = $pinfo['bits'] / 8 - (strlen($t) / 2 + 3);
         $eb = pack('H*', '0001' . str_repeat('FF', $pslen) . '00' . $t);
         if (openssl_private_encrypt($eb, $signature, $privKey, OPENSSL_NO_PADDING)) {
             openssl_pkey_free($privKey);
             return base64_encode($signature);
         }
     }
     openssl_pkey_free($privKey);
     return '';
 }
Exemplo n.º 21
0
 /**
  * Verifies the signature of the document and that the signing certificate
  * stems from a trusted root CA.
  * 
  * Returns the CN of the signing certificate if valid.
  *
  * @param str $xml XML doc to verify
  * @param str $signature_value Base64 encoded signature to verify against.
  * @returns str
  */
 function verify($xml, $signature_value)
 {
     $doc = $this->parse_doc($xml);
     $xp = $this->get_xpath($doc);
     $certs = $this->parse_certificates($xp);
     if ($signature_value == null && empty($certs)) {
         // Doc unsigned and no signature expected
         return null;
     }
     $valid = $this->validate_xml($xp);
     $cert = openssl_x509_read($certs[0]);
     $parsed_certificate = openssl_x509_parse($cert);
     if ($pubkey = openssl_pkey_get_public($cert)) {
         $valid = openssl_verify($xml, base64_decode($signature_value), $pubkey);
         openssl_pkey_free($pubkey);
         openssl_x509_free($cert);
         $cert = null;
         $signed_by = null;
         if (!$valid) {
             throw new GApps_Discovery_Exception("Signature verification failed.");
         }
     } else {
         error_log('/lib/openid/Auth/OpenID/google_discovery.php: error getting certificate public key.');
     }
     $trusted = $this->validate_chain($certs);
     if (!empty($cert)) {
         openssl_x509_free($cert);
     }
     if (!$trusted) {
         throw new GApps_Discovery_Exception("Can not verify trust chain.");
     }
     $subject = $parsed_certificate["subject"];
     $signed_by = strtolower($subject["CN"]);
     return $signed_by;
 }
Exemplo n.º 22
0
function test_openssl_pkey_free()
{
    $fkey = file_get_contents(__DIR__ . "/test_public.pem");
    $k = openssl_pkey_get_public($fkey);
    VERIFY($k != false);
    VERIFY($k != null);
    openssl_pkey_free($k);
}
Exemplo n.º 23
0
 /**
  * Generate a DKIM signature.
  * @access public
  * @param string $signHeader
  * @throws phpmailerException
  * @return string
  */
 public function DKIM_Sign($signHeader)
 {
     if (!defined('PKCS7_TEXT')) {
         if ($this->exceptions) {
             throw new phpmailerException($this->lang('extension_missing') . 'openssl');
         }
         return '';
     }
     $privKeyStr = file_get_contents($this->DKIM_private);
     if ($this->DKIM_passphrase != '') {
         $privKey = openssl_pkey_get_private($privKeyStr, $this->DKIM_passphrase);
     } else {
         $privKey = openssl_pkey_get_private($privKeyStr);
     }
     if (openssl_sign($signHeader, $signature, $privKey, 'sha256WithRSAEncryption')) {
         //sha1WithRSAEncryption
         openssl_pkey_free($privKey);
         return base64_encode($signature);
     }
     openssl_pkey_free($privKey);
     return '';
 }
Exemplo n.º 24
0
 /**
  * Takes the body of the message and processes it with S/MIME
  * 
  * @param  string $to       The recipients being sent to
  * @param  string $subject  The subject of the email
  * @param  string $headers  The headers for the message
  * @param  string $body     The message body
  * @return array  `0` => The message headers, `1` => The message body
  */
 private function createSMIMEBody($to, $subject, $headers, $body)
 {
     if (!$this->smime_encrypt && !$this->smime_sign) {
         return array($headers, $body);
     }
     $plaintext_file = tempnam('', '__fEmail_');
     $ciphertext_file = tempnam('', '__fEmail_');
     $headers_array = array('To' => $to, 'Subject' => $subject);
     preg_match_all('#^([\\w\\-]+):\\s+([^\\n]+\\n( [^\\n]+\\n)*)#im', $headers, $header_matches, PREG_SET_ORDER);
     foreach ($header_matches as $header_match) {
         $headers_array[$header_match[1]] = trim($header_match[2]);
     }
     $body_headers = "";
     if (isset($headers_array['Content-Type'])) {
         $body_headers .= 'Content-Type: ' . $headers_array['Content-Type'] . "\r\n";
     }
     if (isset($headers_array['Content-Transfer-Encoding'])) {
         $body_headers .= 'Content-Transfer-Encoding: ' . $headers_array['Content-Transfer-Encoding'] . "\r\n";
     }
     if ($body_headers) {
         $body = $body_headers . "\r\n" . $body;
     }
     file_put_contents($plaintext_file, $body);
     file_put_contents($ciphertext_file, '');
     // Set up the neccessary S/MIME resources
     if ($this->smime_sign) {
         $senders_smime_cert = file_get_contents($this->senders_smime_cert_file);
         $senders_private_key = openssl_pkey_get_private(file_get_contents($this->senders_smime_pk_file), $this->senders_smime_pk_password);
         if ($senders_private_key === FALSE) {
             throw new fValidationException("The sender's S/MIME private key password specified does not appear to be valid for the private key");
         }
     }
     if ($this->smime_encrypt) {
         $recipients_smime_cert = file_get_contents($this->recipients_smime_cert_file);
     }
     // If we are going to sign and encrypt, the best way is to sign, encrypt and then sign again
     if ($this->smime_encrypt && $this->smime_sign) {
         openssl_pkcs7_sign($plaintext_file, $ciphertext_file, $senders_smime_cert, $senders_private_key, array());
         openssl_pkcs7_encrypt($ciphertext_file, $plaintext_file, $recipients_smime_cert, array(), NULL, OPENSSL_CIPHER_RC2_128);
         openssl_pkcs7_sign($plaintext_file, $ciphertext_file, $senders_smime_cert, $senders_private_key, $headers_array);
     } elseif ($this->smime_sign) {
         openssl_pkcs7_sign($plaintext_file, $ciphertext_file, $senders_smime_cert, $senders_private_key, $headers_array);
     } elseif ($this->smime_encrypt) {
         openssl_pkcs7_encrypt($plaintext_file, $ciphertext_file, $recipients_smime_cert, $headers_array, NULL, OPENSSL_CIPHER_RC2_128);
     }
     // It seems that the contents of the ciphertext is not always \r\n line breaks
     $message = file_get_contents($ciphertext_file);
     $message = str_replace("\r\n", "\n", $message);
     $message = str_replace("\r", "\n", $message);
     $message = str_replace("\n", "\r\n", $message);
     list($new_headers, $new_body) = explode("\r\n\r\n", $message, 2);
     $new_headers = preg_replace('#^To:[^\\n]+\\n( [^\\n]+\\n)*#mi', '', $new_headers);
     $new_headers = preg_replace('#^Subject:[^\\n]+\\n( [^\\n]+\\n)*#mi', '', $new_headers);
     $new_headers = preg_replace("#^MIME-Version: 1.0\r?\n#mi", '', $new_headers, 1);
     $new_headers = preg_replace('#^Content-Type:\\s+' . preg_quote($headers_array['Content-Type'], '#') . "\r?\n#mi", '', $new_headers);
     $new_headers = preg_replace('#^Content-Transfer-Encoding:\\s+' . preg_quote($headers_array['Content-Transfer-Encoding'], '#') . "\r?\n#mi", '', $new_headers);
     unlink($plaintext_file);
     unlink($ciphertext_file);
     if ($this->smime_sign) {
         openssl_pkey_free($senders_private_key);
     }
     return array($new_headers, $new_body);
 }
Exemplo n.º 25
0
 public function __destruct()
 {
     if ($this->privateKey) {
         openssl_pkey_free($this->privateKey);
     }
 }
 public static function tearDownAfterClass()
 {
     openssl_pkey_free(self::$pKey);
 }
Exemplo n.º 27
0
 /**
  * Generates the JWT signature according to the private key file and the JWT content.
  *
  * @param string $jsonWebToken The JWT content.
  *
  * @throws \Widop\GoogleAnalytics\Exception\GoogleAnalyticsException If an error occured when generating the signature.
  *
  * @return string The JWT signature.
  */
 protected function generateSignature($jsonWebToken)
 {
     if (!function_exists('openssl_x509_read')) {
         throw GoogleAnalyticsException::invalidOpenSslExtension();
     }
     $certificate = file_get_contents($this->privateKeyFile);
     $certificates = array();
     if (!openssl_pkcs12_read($certificate, $certificates, 'notasecret')) {
         throw GoogleAnalyticsException::invalidPKCS12File();
     }
     if (!isset($certificates['pkey']) || !$certificates['pkey']) {
         throw GoogleAnalyticsException::invalidPKCS12Format();
     }
     $ressource = openssl_pkey_get_private($certificates['pkey']);
     if (!$ressource) {
         throw GoogleAnalyticsException::invalidPKCS12PKey();
     }
     $signature = null;
     if (!openssl_sign($jsonWebToken, $signature, $ressource, 'sha256')) {
         throw GoogleAnalyticsException::invalidPKCS12Signature();
     }
     openssl_pkey_free($ressource);
     return $signature;
 }
Exemplo n.º 28
0
for ($i = 1, $c = $pkey_pair_num; $i <= $c; $i++) {
   $cert->create_private();
   $pub_key = $cert->get_pubkey();
   $priv_key = $cert->get_privkey();
   printf("+Ok, Set up %d key pair succ!\r", $i);
}
echo "\n";
echo microtime(true)-$t;
echo "\n";
*/
$t = 0;
for ($i = 1, $c = $pkey_pair_num; $i <= $c; $i++) {
    $t1 = microtime(true);
    $cert->create_private();
    $cert->free();
    $t2 = microtime(true);
    $t += $t2 - $t1;
    printf("%d\r", $i);
}
echo $t / $pkey_pair_num . "\n";
$config = em_config::get2('openssl_config');
$t = 0;
for ($i = 1, $c = $pkey_pair_num; $i <= $c; $i++) {
    $t1 = microtime(true);
    $res = openssl_pkey_new($config);
    openssl_pkey_free($res);
    $t2 = microtime(true);
    $t += $t2 - $t1;
    printf("%d\r", $i);
}
echo $t / $pkey_pair_num . "\n";
Exemplo n.º 29
0
 /**
  * Verifies the signature of the document and that the signing certificate
  * stems from a trusted root CA.
  * 
  * Returns the CN of the signing certificate if valid.
  *
  * @param str $xml XML doc to verify
  * @param str $signature_value Base64 encoded signature to verify against.
  * @returns str
  */
 function verify($xml, $signature_value)
 {
     $doc = $this->parse_doc($xml);
     $xp = $this->get_xpath($doc);
     $valid = $this->validate_xml($xp);
     $certs = $this->parse_certificates($xp);
     $cert = openssl_x509_read($certs[0]);
     $parsed_certificate = openssl_x509_parse($cert);
     $pubkey = openssl_pkey_get_public($cert);
     $valid = openssl_verify($xml, base64_decode($signature_value), $pubkey);
     openssl_pkey_free($pubkey);
     openssl_x509_free($cert);
     $signed_by = null;
     if (!$valid) {
         throw new GApps_Discovery_Exception("Signature verification failed.");
     }
     $trusted = $this->validate_chain($certs);
     if (!$trusted) {
         throw new GApps_Discovery_Exception("Can not verify trust chain.");
     }
     $subject = $parsed_certificate["subject"];
     $signed_by = strtolower($subject["CN"]);
     return $signed_by;
 }
Exemplo n.º 30
-1
/**
 * WebSite-PHP file utils_openssl.inc.php
 *
 * WebSite-PHP : PHP Framework 100% object (http://www.website-php.com)
 * Copyright (c) 2009-2015 WebSite-PHP.com
 * PHP versions >= 5.2
 *
 * Licensed under The MIT License
 * Redistributions of files must retain the above copyright notice.
 * 
 * @author      Emilien MOREL <*****@*****.**>
 * @link        http://www.website-php.com
 * @copyright   WebSite-PHP.com 12/05/2015
 * @version     1.2.13
 * @access      public
 * @since       1.0.67
 */
function createKeys($passphrase = 'passphrase', $private_key_bits = 1024, $private_key_type = OPENSSL_KEYTYPE_RSA, $encrypte_key = true)
{
    if (!extension_loaded('openssl')) {
        throw new NewException("Please activate openssl php lib, to use encryption.", 0, getDebugBacktrace(1));
    } else {
        $openssl_conf_file = str_replace("\\", "/", dirname(__FILE__)) . '/../config/openssl.cnf';
        if (!file_exists($openssl_conf_file)) {
            throw new NewException("openssl.cnf doesn't exists (" . $openssl_conf_file . ").", 0, getDebugBacktrace(1));
        }
        // Create the keypair
        $config_key = array("config" => $openssl_conf_file, "digest_alg" => "sha1", "x509_extensions" => "v3_ca", "req_extensions" => "v3_req", "private_key_bits" => $private_key_bits, "private_key_type" => $private_key_type, "encrypte_key" => $encrypte_key);
        $res = openssl_pkey_new($config_key);
        if ($res != false) {
            // Get private key. A pass phrase is required for proper encryption/decryption.
            openssl_pkey_export($res, $privkey, $passphrase, $config_key);
            // Get public key
            $pubkey = openssl_pkey_get_details($res);
            $pubkey = $pubkey['key'];
            $keys = array();
            $keys['private'] = $privkey;
            $keys['public'] = $pubkey;
            openssl_pkey_free($res);
            return $keys;
        } else {
            $error = "";
            while ($msg = openssl_error_string()) {
                $error .= $msg . "<br />\n";
            }
            $error = "Error generation private key" . ($error != "" ? " : " . $error : "");
            throw new NewException($error, 0, getDebugBacktrace(1));
        }
    }
    return null;
}