Ejemplo n.º 1
0
function createNewcertificate()
{
    global $gbl, $login, $ghtml;
    $cerpath = "server.crt";
    $keypath = "server.key";
    $requestpath = "a.csr";
    $ltemp["countryName"] = "IN";
    $ltemp["stateOrProvinceName"] = "Bn";
    $ltemp["localityName"] = "Bn";
    $ltemp["organizationName"] = "LxCenter";
    $ltemp["organizationalUnitName"] = "Kloxo";
    $ltemp["commonName"] = "Kloxo";
    $ltemp["emailAddress"] = "*****@*****.**";
    $privkey = openssl_pkey_new();
    openssl_pkey_export_to_file($privkey, $keypath);
    $csr = openssl_csr_new($ltemp, $privkey);
    openssl_csr_export_to_file($csr, $requestpath);
    $sscert = openssl_csr_sign($csr, null, $privkey, 365);
    openssl_x509_export_to_file($sscert, $cerpath);
    $src = getcwd();
    $dest = '/usr/local/lxlabs/kloxo/ext/lxhttpd/conf';
    root_execsys("lxfilesys_mkdir", $dest . "/ssl.crt/");
    root_execsys("lxfilesys_mkdir", $dest . "/ssl.key/");
    root_execsys("lxfilesys_mv", "{$src}/{$cerpath}", $dest . "/ssl.crt/" . $cerpath);
    root_execsys("lxfilesys_mv", "{$src}/{$keypath}", $dest . "/ssl.key/" . $cerpath);
    root_execsys("lxfilesys_mv", "{$src}/{$requestpath}", "{$dest}/{$requestpath}");
}
Ejemplo n.º 2
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];
 }
Ejemplo n.º 3
0
 public function makeKeys($distinguishedName, $passphrase = NULL, $certCA = NULL, $keyCA)
 {
     // keep track of the distinguished name
     $this->dn = $distinguishedName;
     // generate the pem-encoded private key
     $config = array('digest_alg' => 'sha1', 'private_key_bits' => 1024, 'encrypt_key' => TRUE);
     $key = openssl_pkey_new($config);
     // generate the certificate signing request...
     $csr = openssl_csr_new($this->dn, $key, $config);
     // and use it to make a self-signed certificate
     $this->serialNumber = rand();
     $cert = openssl_csr_sign($csr, NULL, $key, 365, $config, time());
     // make openssl forget the key
     openssl_free_key($keyCA);
     // export private and public keys
     openssl_pkey_export($key, $this->privatekey, $passphrase, $config);
     //openssl_pkey_export_to_file ( $this->privatekey , "server.key", $passphrase, $config )
     openssl_x509_export($cert, $this->certificate);
     // parse certificate
     $this->x509 = openssl_x509_parse($cert);
     if (isset($this->serialNumber)) {
         $outfilename = '/var/www/html/' . $this->serialNumber;
         // Gets an exportable representation of a key into a file
         openssl_pkey_export_to_file($key, $outfilename . '.pem', $passphrase, $config);
     }
     openssl_x509_export_to_file($this->certificate, $outfilename . '.crt', TRUE);
     return TRUE;
     // end of makeKeys() method
 }
Ejemplo n.º 4
0
function generateSslKeypair($commonName, $mail, $keyLength)
{
    $key = openssl_pkey_new(array("private_key_bits" => $keyLength));
    $certConf = parse_ini_file("cert.conf", true);
    $dn = $certConf["dn"];
    $dn["commonName"] = $commonName;
    $dn["emailAddress"] = $mail;
    $cert = openssl_csr_new($dn, $key);
    // Creating a new X509 Certificate Signing Request
    if ($e = error_get_last()) {
        // Issues found in parsing the arguments will get a warning. A CSR is created, nonetheless
        throw new Exception("Error occured:" . $e["message"]);
    }
    $signed = openssl_csr_sign($cert, null, $key, $certConf["csr"]["validity_in_days"], array("config" => "../core/cert.conf", "config_section_name" => "csr", "x509_extensions" => "clientx509_ext"));
    // Self-signed X509 certificate with SHA256 digest and extensions specified in local openssl.conf
    if (!$signed) {
        throw new Exception("Error occured while signing certificate");
    }
    openssl_pkey_export($key, $privateKey);
    // Export private-key to $privateKey
    openssl_x509_export($signed, $clientCert, FALSE);
    // Export signed-certificate to $clientCert
    openssl_x509_export($signed, $publicKey);
    // Export public-key from the signed-certificate to $publicKey
    return array($clientCert, $publicKey, $privateKey);
}
Ejemplo n.º 5
0
function generateSslKeypair($commonName, $keyLength)
{
    $key = openssl_pkey_new(array("private_key_bits" => $keyLength));
    $default = getDefaultConfPath();
    if (file_exists($default . "/cert-overrides.ini")) {
        $confFile = $default . "/cert-overrides.ini";
    } else {
        $confFile = $_SERVER["DOCUMENT_ROOT"] . "/conf/cert.ini";
    }
    $certConf = parse_ini_file($confFile, true);
    $dn = $certConf["dn"];
    $dn["commonName"] = $commonName;
    $cert = openssl_csr_new($dn, $key);
    // Creating a new X509 Certificate Signing Request
    if ($e = error_get_last()) {
        // Issues found in parsing the arguments will get a warning. A CSR is created, nonetheless
        throw new Exception("Error occured:" . $e["message"]);
    }
    $signed = openssl_csr_sign($cert, null, $key, $certConf["csr"]["validity_in_days"], array("config" => $confFile, "config_section_name" => "csr", "x509_extensions" => "clientx509_ext"));
    // Self-signed X509 certificate with SHA256 digest and extensions specified in local openssl.conf
    if (!$signed) {
        throw new Exception("Error occured while signing certificate");
    }
    openssl_pkey_export($key, $privateKey);
    // Export private-key to $privateKey
    openssl_x509_export($signed, $clientCert);
    // Export signed-certificate to $clientCert without Extra Details
    return array($clientCert, $privateKey);
}
Ejemplo n.º 6
0
 static public function get_keys($login,$full_name) {
   $CA_CERT = base_url()."data/key/CA_DOC.csr";
   $CA_KEY  = base_url()."data/key/CA_DOC_priv.key";
   $config = array(
     "private_key_type"=>OPENSSL_KEYTYPE_RSA,
     "private_key_bits"=>512
   );
   $res = openssl_pkey_new($config);
   $privKey = '';
   openssl_pkey_export($res,$privKey);
   $arr = array(
     "organizationName" => "Фізична особа",
     "organizationalUnitName" => "Фізична особа",
     "commonName" => $full_name,
     "UID" => $login,
     "countryName" => "UA"
   );
   $csr = openssl_csr_new($arr,$privKey);
   $cert = openssl_csr_sign($csr,file_get_contents($CA_CERT),file_get_contents($CA_KEY),730);
   openssl_x509_export($cert,$str_cert);
   $public_key = openssl_pkey_get_public($str_cert);
   $public_key_details = openssl_pkey_get_details($public_key);
   $public_key_string = $public_key_details['key'];
   return array('private'=>$privKey,'cert'=>$str_cert,'public'=>$public_key_string);
 }
Ejemplo n.º 7
0
 public function run()
 {
     if (strrev($this->input['folder']) !== DIRECTORY_SEPARATOR) {
         $this->input['folder'] .= DIRECTORY_SEPARATOR;
     }
     $files = [];
     foreach (['pub', 'key', 'crt', 'csr'] as $extension) {
         $files[$extension] = sprintf('%s%s%s.%s', $this->input['folder'], $this->input['prefix'], $this->input['hostname'], $extension);
     }
     foreach ($files as $file) {
         if (file_exists($file)) {
             throw new RuntimeException(sprintf('File exist: %s', $file));
         }
     }
     $dn = array("countryName" => $this->input['country'], "stateOrProvinceName" => $this->input['state-or-province-name'], "localityName" => $this->input['locality-name'], "organizationName" => $this->input['organization-name'], "organizationalUnitName" => $this->input['organizational-unit-name'], "commonName" => $this->input['common-name'], "emailAddress" => $this->input['email-address']);
     // Create the private and public key
     $res = openssl_pkey_new(['digest_alg' => $this->input['alg'], 'private_key_bits' => $this->input['bits'], 'private_key_type' => OPENSSL_KEYTYPE_RSA]);
     // Generate a certificate signing request
     $csr = openssl_csr_new(array_filter($dn), $res);
     // Creates a self-signed cert
     $sscert = openssl_csr_sign($csr, null, $res, $this->input['days']);
     openssl_csr_export($csr, $out);
     file_put_contents($files['csr'], $out);
     // Export certfile
     openssl_x509_export($sscert, $out);
     file_put_contents($files['crt'], $out);
     // Extract the private key from $res to $privKey
     openssl_pkey_export($res, $out);
     file_put_contents($files['key'], $out);
     // Extract the public key from $res to $pubKey
     $out = openssl_pkey_get_details($res);
     file_put_contents($files['pub'], $out["key"]);
 }
 public static function setUpBeforeClass()
 {
     self::$pKey = openssl_pkey_new();
     $csr = openssl_csr_new([], self::$pKey);
     $x509 = openssl_csr_sign($csr, null, self::$pKey, 1);
     openssl_x509_export($x509, self::$certificate);
     openssl_x509_free($x509);
 }
Ejemplo n.º 9
0
 /**
  * Sign this CSR
  *
  * @param   security.KeyPair keypair
  * @param   int days default 365
  * @param   var cacert default NULL
  * @return  security.cert.X509Certificate
  */
 public function sign($keypair, $days = 365, $cacert = NULL)
 {
     if (FALSE === ($x509 = openssl_csr_sign($this->_res, $cacert, $keypair->_res, $days))) {
         trigger_error(implode("\n  @", OpenSslUtil::getErrors()), E_USER_NOTICE);
         throw new CertificateException('Cannot sign certificate');
     }
     if (FALSE === openssl_x509_export($x509, $str)) {
         trigger_error(implode("\n  @", OpenSslUtil::getErrors()), E_USER_NOTICE);
         throw new CertificateException('Cannot export certificate');
     }
     return X509Certificate::fromString($str);
 }
Ejemplo n.º 10
0
function create_ssl_cert($pem_file, $pem_passphrase, $pem_dn)
{
    $privkey = openssl_pkey_new();
    $cert = openssl_csr_new($pem_dn, $privkey);
    $cert = openssl_csr_sign($cert, null, $privkey, 365);
    $pem = array();
    openssl_x509_export($cert, $pem[0]);
    openssl_pkey_export($privkey, $pem[1], $pem_passphrase);
    $pem = implode($pem);
    file_put_contents($pem_file, $pem);
    chmod($pem_file, 0600);
}
Ejemplo n.º 11
0
 /**
  * @param array $dn
  * @param null  $passPhrase
  *
  * @return string
  */
 public function create(array $dn, $passPhrase = null)
 {
     $config = $this->getConfig();
     $key = openssl_pkey_new($config);
     $crt = openssl_csr_new($dn, $key, $config);
     $crt = openssl_csr_sign($crt, null, $key, 365, $config);
     $x509 = null;
     $pKey = null;
     openssl_x509_export($crt, $x509);
     openssl_pkey_export($key, $pKey, $passPhrase, $config);
     return $x509 . $pKey;
 }
Ejemplo n.º 12
0
 private function createSSLCert()
 {
     $privKey = openssl_pkey_new();
     $cert = openssl_csr_new(self::$pemDN, $privKey);
     $cert = openssl_csr_sign($cert, null, $privKey, 365);
     $pem = [];
     openssl_x509_export($cert, $pem[0]);
     openssl_pkey_export($privKey, $pem[1], self::PEM_PASSPHRASE);
     $pem = implode($pem);
     file_put_contents($this->pemFile, $pem);
     chmod($this->pemFile, 0600);
 }
Ejemplo n.º 13
0
 function generateKeys($passphrase)
 {
     $identity = Zend_Auth::getInstance()->getIdentity();
     $dn = array("countryName" => $this->_config->countryName, "stateOrProvinceName" => $this->_config->stateOrProvinceName, "localityName" => $this->_config->localityName, "organizationName" => $this->_config->organizationName, "organizationalUnitName" => $this->_config->organizationUnitName, "commonName" => $identity->firstName . " " . $identity->lastName . "(" . $identity->username . ")", "emailAddress" => $this->_config->emailAddress);
     $privkey = openssl_pkey_new();
     $csr = openssl_csr_new($dn, $privkey);
     $sscert = openssl_csr_sign($csr, null, $privkey, $this->_config->numberOfDays);
     openssl_x509_export($sscert, $publickey);
     openssl_pkey_export($privkey, $privatekey);
     openssl_csr_export($csr, $csrStr);
     $this->publicKey = $publickey;
     $this->privateKey = $this->_encryptPrivateKey($privatekey, $passphrase);
 }
Ejemplo n.º 14
0
 /**
  * Generates a new PEM File given the informations
  *
  * @param string $pem_file                 the path of the PEM file to create
  * @param string $pem_passphrase           the passphrase to protect the PEM
  *                                             file or if you don't want to
  *                                             use a passphrase
  * @param string $country_name             the country code of the new PEM file. e.g.: EN
  * @param string $state_or_province_name   the state or province name of the new PEM file
  * @param string $locality_name            the name of the locality
  * @param string $organization_name        the name of the organisation. e.g.: MyCompany
  * @param string $organizational_unit_name the organisation unit name
  * @param string $common_name               the common name
  * @param string $email_address            the email address
  */
 public static function generatePemFile($pem_file, $pem_passphrase, $country_name, $state_or_province_name, $locality_name, $organization_name, $organizational_unit_name, $common_name, $email_address)
 {
     // Generate PEM file
     $dn = array('countryName' => $country_name, 'stateOrProvinceName' => $state_or_province_name, 'localityName' => $locality_name, 'organizationName' => $organization_name, 'organizationalUnitName' => $organizational_unit_name, 'commonName' => $common_name, 'emailAddress' => $email_address);
     $privkey = openssl_pkey_new();
     $cert = openssl_csr_new($dn, $privkey);
     $cert = openssl_csr_sign($cert, null, $privkey, 365);
     $pem = array();
     openssl_x509_export($cert, $pem[0]);
     openssl_pkey_export($privkey, $pem[1], $pem_passphrase);
     $pem = implode($pem);
     file_put_contents($pem_file, $pem);
 }
Ejemplo n.º 15
0
 public function signCertificate($cacert = null, $days = 365)
 {
     \debug("OpenSSL CSR: Signing certificate (cacert=%s, days=%d)", $cacert ? 'yes' : 'no', $days);
     $this->csr = openssl_csr_new($this->dn, $this->pkey);
     // Default serial to 0
     if ($this->serial) {
         $serial = $this->serial;
     } else {
         $serial = 0;
     }
     $this->signed = openssl_csr_sign($this->csr, $cacert, $this->pkey, $days, [], $serial);
     // Return true on success
     return true;
 }
 /**
  * Generate a pkcs12 file and private key to use with remote desktoping.
  *
  * @param string $password
  * @return RemoteDesktopCertificate
  */
 public static function generate()
 {
     if (!extension_loaded('openssl')) {
         throw new \RuntimeException("Can only generate a remote desktop certificate when OpenSSL PHP extension is installed.");
     }
     // Generate a new private (and public) key pair
     $config = array('config' => __DIR__ . '/../Resources/config/openssl.cnf');
     $privkey = openssl_pkey_new($config);
     // Generate a certificate signing request
     $dn = array("commonName" => "AzureDistributionBundle for Symfony Tools");
     $csr = openssl_csr_new($dn, $privkey, $config);
     $sscert = openssl_csr_sign($csr, null, $privkey, 365, $config);
     return new self($privkey, $sscert);
 }
 protected function execute($arguments = array(), $options = array())
 {
     if (!extension_loaded('openssl')) {
         throw Exception('this task requires the openssl php extension, see http://www.php.net/openssl');
     }
     $days = null;
     while (!is_numeric($days)) {
         $days = $this->ask('The Days of Validity (default:365)');
         if (!$days) {
             $days = 365;
         }
     }
     while (!($phrase = $this->ask('Private Key Phrase'))) {
     }
     $country = null;
     while (!($country = strtoupper($this->ask('Country Name (2 letter code)'))) || strlen($country) != 2) {
         $this->logBlock('invalid format.', 'ERROR');
     }
     while (!($state = $this->ask('State or Province Name (full name)'))) {
     }
     while (!($locality = $this->ask('Locality Name (eg,city)'))) {
     }
     while (!($org = $this->ask('Organization Name(eg,company)'))) {
     }
     while (!($orgUnit = $this->ask('Organization Unit Name(eg,section)'))) {
     }
     while (!($common = $this->ask('Common Name(eg,Your name)'))) {
     }
     while (!($email = $this->ask('Email Address'))) {
     }
     $dn = array('countryName' => $country, 'stateOrProvinceName' => $state, 'localityName' => $locality, 'organizationName' => $org, 'organizationalUnitName' => $orgUnit, 'commonName' => $common, 'emailAddress' => $email);
     $dirname = sfConfig::get('sf_plugins_dir') . '/opOpenSocialPlugin/certs';
     $filesystem = new sfFilesystem($this->dispatcher, $this->formatter);
     $filesystem->mkdirs($dirname);
     $privatekey = openssl_pkey_new();
     $csr = openssl_csr_new($dn, $privatekey);
     $sscert = openssl_csr_sign($csr, null, $privatekey, $days);
     openssl_x509_export($sscert, $certout);
     openssl_pkey_export($privatekey, $pkeyout, $phrase);
     $cert_filename = $dirname . '/public.crt';
     file_put_contents($cert_filename, $certout);
     $this->logSection('file+', $cert_filename);
     $pkey_filename = $dirname . '/private.key';
     file_put_contents($pkey_filename, $pkeyout);
     $this->logSection('file+', $pkey_filename);
     $databaseManager = new sfDatabaseManager($this->configuration);
     Doctrine::getTable('SnsConfig')->set('shindig_private_key_phrase', $phrase);
 }
Ejemplo n.º 18
0
 public function createUserCert($filename)
 {
     $dn = (array) $this;
     $privateKeyPass = $this->generate_password();
     //$filename = dirname(__FILE__) . '/certificate.pfx';
     $numberOfDays = 365 * 3;
     $privateKey = openssl_pkey_new();
     $csr = openssl_csr_new($dn, $privateKey);
     $sscert = openssl_csr_sign($csr, null, $privateKey, $numberOfDays);
     //create a csr file, change null to a filename to save it if you need to
     $key = openssl_pkey_get_private($privateKey, $privateKeyPass);
     //parses the $privateKey and prepares it for use by openssl_pkcs12_export_to_file.
     openssl_pkcs12_export_to_file($sscert, $filename, $key, $privateKeyPass);
     //Save the pfx file to $filename
     return $privateKeyPass;
 }
Ejemplo n.º 19
0
 function gen_new_keypair($expired = false)
 {
     $config = array('private_key_bits' => 384, 'digest_alg' => 'sha1', 'private_key_type' => OPENSSL_KEYTYPE_RSA);
     $privkey = openssl_pkey_new($config);
     $pw = "c0nfusa";
     $dn = array("countryName" => 'NO', "localityName" => 'Drammen', "organizationName" => 'Austad IT', "commonName" => 'austad.us', "emailAddress" => '*****@*****.**');
     $csr = openssl_csr_new($dn, $privkey);
     if ($expired) {
         $cert = openssl_csr_sign($csr, null, $privkey, -1);
     } else {
         $cert = openssl_csr_sign($csr, null, $privkey, 14);
     }
     openssl_pkey_export($privkey, $privkeystr, $pw);
     openssl_x509_export($cert, $certstr);
     openssl_csr_export($csr, $csrstr);
     return array('key' => $privkeystr, 'cert' => $certstr, 'csr' => $csrstr, 'pw' => $pw);
 }
Ejemplo n.º 20
0
 public function generateCertificate($certData)
 {
     $configParams = array("digest_alg" => "sha512", "private_key_bits" => 4096, "private_key_type" => OPENSSL_KEYTYPE_RSA);
     $privkey = openssl_pkey_new($configParams);
     //Now, using the private key, we can create the certificate. First we define the certificate parameters:
     //And then we can create the certificate:
     $csr = openssl_csr_new($certData, $privkey, $configParams);
     //Now we sign the certificate using the private key:
     $duration = 2 * 365;
     $sscert = openssl_csr_sign($csr, null, $privkey, $duration, $configParams);
     //Finally we can export the certificate and the private key:
     openssl_x509_export($sscert, $certout);
     $password = NULL;
     openssl_pkey_export($privkey, $pkout, $password, $configParams);
     //Note that a password is needed to export the private key. If a password is not needed, you must set $password
     //to NULL (don't set it to empty string as the private key password will be an empty string).
     return array('privateKey' => $pkout, 'certificate' => $certout);
 }
Ejemplo n.º 21
0
 public function createCertificateFile($v47826cacc65c665212b821e6ff80b9b0)
 {
     if ($this->getPrivateKeyFilePath()) {
         $v328008858471c657239879e93eab77e2 = $this->getPrivateKey();
         $v1f8c50db95e9ead5645e32f8df5baa7b = openssl_csr_new($this->dn, $v328008858471c657239879e93eab77e2);
         $v0d2faad4cfcceb5381d65e733cab0635 = openssl_csr_sign($v1f8c50db95e9ead5645e32f8df5baa7b, null, $v328008858471c657239879e93eab77e2, 100);
         if (openssl_x509_export($v0d2faad4cfcceb5381d65e733cab0635, $vb6ba9fa6ea18201bf39ea635ecca9f13)) {
             file_put_contents($v47826cacc65c665212b821e6ff80b9b0, $vb6ba9fa6ea18201bf39ea635ecca9f13);
             $this->setCertificateFilePath($v47826cacc65c665212b821e6ff80b9b0);
             return true;
         } else {
             throw new coreException("Can't export x509 certificate");
             return false;
         }
     } else {
         throw new coreException("Private key requred");
         return false;
     }
 }
Ejemplo n.º 22
0
 public function testGenerateSignedLink()
 {
     if (!extension_loaded('openssl')) {
         $this->markTestSkipped('OpenSSL is required for this test.');
     }
     $pemFile = sys_get_temp_dir() . '/aws-sdk-php-zf2-cloudfront-test.pem';
     if (!file_exists($pemFile)) {
         // Generate a new Certificate Signing Request and public/private keypair
         $csr = openssl_csr_new(array(), $keypair);
         // Create a self-signed certificate
         $x509 = openssl_csr_sign($csr, null, $keypair, 1);
         openssl_x509_export($x509, $certificate);
         // Create and save a private key
         $privateKey = openssl_get_privatekey($keypair);
         openssl_pkey_export_to_file($privateKey, $pemFile);
     }
     $this->viewHelper->setHostname('example.com');
     $link = $this->viewHelper->__invoke('my-object', '123abc', time() + 600, 'kpid', $pemFile);
     $this->assertRegExp('#^https\\:\\/\\/123abc\\.example\\.com\\/my-object\\?Expires\\=(.*)\\&Signature\\=(.*)\\&Key-Pair-Id\\=kpid$#', $link);
 }
Ejemplo n.º 23
0
 private function applySSLContext()
 {
     $pem_file = './server.pem';
     $pem_passphrase = 'shinywss';
     // Generate PEM file
     if (!file_exists($pem_file)) {
         $dn = array("countryName" => "DE", "stateOrProvinceName" => "none", "localityName" => "none", "organizationName" => "none", "organizationalUnitName" => "none", "commonName" => "foo.lh", "emailAddress" => "*****@*****.**");
         $privkey = openssl_pkey_new();
         $cert = openssl_csr_new($dn, $privkey);
         $cert = openssl_csr_sign($cert, null, $privkey, 365);
         $pem = array();
         openssl_x509_export($cert, $pem[0]);
         openssl_pkey_export($privkey, $pem[1], $pem_passphrase);
         $pem = implode($pem);
         file_put_contents($pem_file, $pem);
     }
     // apply ssl context:
     stream_context_set_option($this->context, 'ssl', 'local_cert', $pem_file);
     stream_context_set_option($this->context, 'ssl', 'passphrase', $pem_passphrase);
     stream_context_set_option($this->context, 'ssl', 'allow_self_signed', true);
     stream_context_set_option($this->context, 'ssl', 'verify_peer', false);
 }
Ejemplo n.º 24
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;
}
 /**
  * S/MIME Signing tests
  */
 public function testSigning()
 {
     $this->Mail->Subject .= ': S/MIME signing';
     $this->Mail->Body = 'This message is S/MIME signed.';
     $this->buildBody();
     $dn = array('countryName' => 'UK', 'stateOrProvinceName' => 'Here', 'localityName' => 'There', 'organizationName' => 'PHP', 'organizationalUnitName' => 'PHPMailer', 'commonName' => 'PHPMailer Test', 'emailAddress' => '*****@*****.**');
     $password = '******';
     $certfile = 'certfile.txt';
     $keyfile = 'keyfile.txt';
     //Make a new key pair
     $pk = openssl_pkey_new();
     //Create a certificate signing request
     $csr = openssl_csr_new($dn, $pk);
     //Create a self-signed cert
     $cert = openssl_csr_sign($csr, null, $pk, 1);
     //Save the cert
     openssl_x509_export($cert, $certout);
     file_put_contents($certfile, $certout);
     //Save the key
     openssl_pkey_export($pk, $pkeyout, $password);
     file_put_contents($keyfile, $pkeyout);
     $this->Mail->sign($certfile, $keyfile, $password);
     $this->assertTrue($this->Mail->send(), 'S/MIME signing failed');
     unlink($certfile);
     unlink($keyfile);
 }
Ejemplo n.º 26
0
function test_openssl_x509_check_private_key()
{
    $privkey = openssl_pkey_new();
    VERIFY($privkey != null);
    $csr = openssl_csr_new(null, $privkey);
    VERIFY($csr != null);
    $scert = openssl_csr_sign($csr, null, $privkey, 365);
    VERIFY(openssl_x509_check_private_key($scert, $privkey));
}
Ejemplo n.º 27
0
 /**
  * Generates self signed certificate and returns it.
  * 
  * @param array      $dn      Certificate information
  * @param int        $days    Days until certificate expires
  * @param string     $cacert  Encrypted issuer certifcate
  * @param string     $cakey   Encrypted issuer private key
  * @param array|null $options Options for creating certificate
  * @param int        $serial  Serial number by default is 0
  * @return resource of certificate.
  */
 public function genSignedCert($dn, $days, $cacert, $cakey, $options = null, $serial = 0)
 {
     $this->_cert = openssl_csr_sign($this->genCertificate($dn, $options), $cacert, $cakey, $days, $options, $serial);
     return $this->_cert;
 }
Ejemplo n.º 28
0
 /**
  * Create a new public certificate.
  * 
  * @param string $csr The CSR to create a public key off of.
  * 
  * @return string The new public key.
  */
 public function create($csr)
 {
     $cert = openssl_csr_sign($csr, Config::get('ssl:certificate'), Config::get('ssl:key'), 365, Config::get('sslConf'), $this->getSerial());
     openssl_x509_export($cert, $output);
     return $output;
 }
Ejemplo n.º 29
-1
 public function generateKeyPair($keyPath, $keySize)
 {
     // Fill in data for the distinguished name to be used in the cert
     // You must change the values of these keys to match your name and
     // company, or more precisely, the name and company of the person/site
     // that you are generating the certificate for.
     // For SSL certificates, the commonName is usually the domain name of
     // that will be using the certificate, but for S/MIME certificates,
     // the commonName will be the name of the individual who will use the
     // certificate.
     $dn = array("countryName" => "UK", "stateOrProvinceName" => "Somerset", "localityName" => "Glastonbury", "organizationName" => "The Brain Room Limited", "organizationalUnitName" => "PHP Documentation Team", "commonName" => "Wez Furlong", "emailAddress" => "*****@*****.**");
     // Generate a new private (and public) key pair
     $privkey = openssl_pkey_new(array('private_key_bits' => $keySize, 'private_key_type' => OPENSSL_KEYTYPE_RSA));
     // Generate a certificate signing request
     $csr = openssl_csr_new($dn, $privkey);
     // You will usually want to create a self-signed certificate at this
     // point until your CA fulfills your request.
     $sscert = openssl_csr_sign($csr, null, $privkey, 365000);
     // Now you will want to preserve your private key, CSR and self-signed
     // cert so that they can be installed into your web server, mail server
     // or mail client (depending on the intended use of the certificate).
     // This example shows how to get those things into variables, but you
     // can also store them directly into files.
     // Typically, you will send the CSR on to your CA who will then issue
     // you with the "real" certificate.
     // openssl_csr_export($csr, $csrout);
     // echo $csrout . "\n";
     openssl_x509_export($sscert, $certout);
     file_put_contents($keyPath . '/public.crt', $certout);
     openssl_pkey_export($privkey, $pkeyout, "mypassword");
     file_put_contents($keyPath . '/private.key', $pkeyout);
 }
Ejemplo n.º 30
-1
function create_cert()
{
    global $file_pkcs12, $file_x509, $file_ca_x509, $file_ca_pkey;
    global $pass, $config, $dn, $expire_time;
    $ca_x509 = file_get_contents($file_ca_x509);
    $ca_pkey = file_get_contents($file_ca_pkey);
    $req_key = openssl_pkey_new($config);
    $req_csr = openssl_csr_new($dn, $req_key);
    // CA sign
    $req_cert = openssl_csr_sign($req_csr, $ca_x509, [$ca_pkey, $pass], $expire_time);
    // SELF sign
    // 自签证书不能验证有效期
    //$req_cert = openssl_csr_sign($req_csr, null, $req_key, $expire_time);
    $ret = openssl_x509_export_to_file($req_cert, $file_x509);
    if (!$ret) {
        while ($msg = openssl_error_string()) {
            echo $msg . "<br />\n";
        }
        echo "-Err, create x509 fail!(" . __LINE__ . ")\n";
        exit(1);
    }
    $ret = openssl_pkcs12_export_to_file($req_cert, $file_pkcs12, $req_key, $pass);
    if (!$ret) {
        while ($msg = openssl_error_string()) {
            echo $msg . "<br />\n";
        }
        echo "-Err, create pkcs12 fail!(" . __LINE__ . ")\n";
        exit(1);
    }
    echo "+Ok, create keys succ!\n";
}