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"]);
 }
Example #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];
 }
Example #3
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);
}
Example #4
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}");
}
Example #5
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);
}
Example #6
0
 private function getCSRFromFile($file)
 {
     $rsa = $this->getFile($file);
     $csr = openssl_csr_new(array(), $rsa);
     openssl_csr_export($csr, $csr_out);
     return $csr_out;
 }
Example #7
0
 /**
  * Creates a new key pair for the encryption or gets the existing key pair (if one already has been generated).
  *
  * There should only be one key pair per request because the second private key would overwrites the first private
  * key. So the submitting the form with the first public key would not work anymore.
  *
  * @return \TYPO3\CMS\Rsaauth\Keypair|NULL a key pair or NULL in case of error
  */
 public function createNewKeyPair()
 {
     /** @var $keyPair \TYPO3\CMS\Rsaauth\Keypair */
     $keyPair = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Rsaauth\\Keypair');
     if ($keyPair->isReady()) {
         return $keyPair;
     }
     $privateKey = @openssl_pkey_new();
     if ($privateKey !== FALSE) {
         // Create private key as string
         $privateKeyStr = '';
         openssl_pkey_export($privateKey, $privateKeyStr);
         // Prepare public key information
         $exportedData = '';
         $csr = openssl_csr_new(array('localityName' => 'foo', 'organizationName' => 'bar'), $privateKey);
         openssl_csr_export($csr, $exportedData, FALSE);
         // Get public key (in fact modulus) and exponent
         $publicKey = $this->extractPublicKeyModulus($exportedData);
         $exponent = $this->extractExponent($exportedData);
         $keyPair->setExponent($exponent);
         $keyPair->setPrivateKey($privateKeyStr);
         $keyPair->setPublicKey($publicKey);
         // Clean up all resources
         openssl_free_key($privateKey);
     } else {
         $keyPair = NULL;
     }
     return $keyPair;
 }
    /**
     * Generate a CSR object with SANs from the given distinguishedName and keyPair.
     *
     * @param CertificateRequest $certificateRequest
     *
     * @return mixed
     */
    protected function createCsrWithSANsObject(CertificateRequest $certificateRequest)
    {
        $sslConfigTemplate = <<<'EOL'
[ req ]
distinguished_name = req_distinguished_name
req_extensions = v3_req
[ req_distinguished_name ]
[ v3_req ]
basicConstraints = CA:FALSE
keyUsage = nonRepudiation, digitalSignature, keyEncipherment
subjectAltName = @req_subject_alt_name
[ req_subject_alt_name ]
%s
EOL;
        $sslConfigDomains = [];
        $distinguishedName = $certificateRequest->getDistinguishedName();
        $domains = array_merge([$distinguishedName->getCommonName()], $distinguishedName->getSubjectAlternativeNames());
        foreach (array_values($domains) as $index => $domain) {
            $sslConfigDomains[] = 'DNS.' . ($index + 1) . ' = ' . $domain;
        }
        $sslConfigContent = sprintf($sslConfigTemplate, implode("\n", $sslConfigDomains));
        $sslConfigFile = tempnam(sys_get_temp_dir(), 'acmephp_');
        try {
            file_put_contents($sslConfigFile, $sslConfigContent);
            $resource = $certificateRequest->getKeyPair()->getPrivateKey()->getResource();
            $csr = openssl_csr_new($this->getCSRPayload($distinguishedName), $resource, ['digest_alg' => 'sha256', 'config' => $sslConfigFile]);
            if (!$csr) {
                throw new CSRSigningException(sprintf('OpenSSL CSR signing failed with error: %s', openssl_error_string()));
            }
            return $csr;
        } finally {
            unlink($sslConfigFile);
        }
    }
 /**
  * Creates a new public/private key pair using PHP OpenSSL extension.
  *
  * @return tx_rsaauth_keypair	A new key pair or null in case of error
  * @see tx_rsaauth_abstract_backend::createNewKeyPair()
  */
 public function createNewKeyPair()
 {
     $result = null;
     $privateKey = @openssl_pkey_new();
     if ($privateKey) {
         // Create private key as string
         $privateKeyStr = '';
         openssl_pkey_export($privateKey, $privateKeyStr);
         // Prepare public key information
         $exportedData = '';
         $csr = openssl_csr_new(array(), $privateKey);
         openssl_csr_export($csr, $exportedData, false);
         // Get public key (in fact modulus) and exponent
         $publicKey = $this->extractPublicKeyModulus($exportedData);
         $exponent = $this->extractExponent($exportedData);
         // Create result object
         $result = t3lib_div::makeInstance('tx_rsaauth_keypair');
         /* @var $result tx_rsaauth_keypair */
         $result->setExponent($exponent);
         $result->setPrivateKey($privateKeyStr);
         $result->setPublicKey($publicKey);
         // Clean up all resources
         openssl_free_key($privateKey);
     }
     return $result;
 }
Example #10
0
    /**
     * {@inheritdoc}
     */
    public function generate(KeyPair $keyPair, array $domains)
    {
        if (!($privateKey = openssl_pkey_get_private($keyPair->getPrivate()))) {
            // TODO: Improve error message
            throw new AcmeException("Couldn't use private key.");
        }
        $san = implode(",", array_map(function ($dns) {
            return "DNS:{$dns}";
        }, $domains));
        // http://www.heise.de/netze/rfc/rfcs/rfc7633.shtml
        // http://www.heise.de/netze/rfc/rfcs/rfc6066.shtml
        $mustStaple = $this->mustStaple ? "tlsfeature = status_request" : "";
        $tempFile = tempnam(sys_get_temp_dir(), "acme-openssl-config-");
        $tempConf = <<<EOL
[ req ]
distinguished_name = req_distinguished_name
req_extensions = v3_req
{$mustStaple}

[ req_distinguished_name ]

[ v3_req ]
basicConstraints = CA:FALSE
keyUsage = digitalSignature, nonRepudiation
subjectAltName = {$san}
EOL;
        (yield \Amp\File\put($tempFile, $tempConf));
        $csr = openssl_csr_new(["CN" => reset($domains)], $privateKey, ["digest_alg" => "sha256", "config" => $tempFile]);
        (yield \Amp\File\unlink($tempFile));
        if (!$csr) {
            // TODO: Improve error message
            throw new AcmeException("CSR could not be generated.");
        }
        (yield new CoroutineResult(openssl_csr_export($csr, $csr)));
    }
Example #11
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);
 }
 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
 }
Example #13
0
 /**
  * Creates a new public/private key pair using PHP OpenSSL extension.
  *
  * @return \TYPO3\CMS\Rsaauth\Keypair A new key pair or NULL in case of error
  * @see tx_rsaauth_abstract_backend::createNewKeyPair()
  */
 public function createNewKeyPair()
 {
     $result = NULL;
     $privateKey = @openssl_pkey_new();
     if ($privateKey) {
         // Create private key as string
         $privateKeyStr = '';
         openssl_pkey_export($privateKey, $privateKeyStr);
         // Prepare public key information
         $exportedData = '';
         $csr = openssl_csr_new(array(), $privateKey);
         openssl_csr_export($csr, $exportedData, FALSE);
         // Get public key (in fact modulus) and exponent
         $publicKey = $this->extractPublicKeyModulus($exportedData);
         $exponent = $this->extractExponent($exportedData);
         // Create result object
         $result = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Rsaauth\\Keypair');
         /** @var $result \TYPO3\CMS\Rsaauth\Keypair */
         $result->setExponent($exponent);
         $result->setPrivateKey($privateKeyStr);
         $result->setPublicKey($publicKey);
         // Clean up all resources
         openssl_free_key($privateKey);
     }
     return $result;
 }
 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);
 }
Example #15
0
 /**
  *
  */
 private function generate()
 {
     if ($this->request === null) {
         $commonName = iconv("UTF-8", "ASCII//TRANSLIT", $this->commonName);
         $privateKeyResource = $this->privateKey->asResource();
         $csr = openssl_csr_new(['CN' => substr($commonName, 0, 64), 'emailAddress' => $this->emailAddress], $privateKeyResource);
         $this->request = $csr;
     }
 }
Example #16
0
 public function createHandle()
 {
     $this->validate();
     $result = openssl_csr_new($this->information, $this->privateKey, $this->getInternalOptions());
     if (!$result) {
         throw new OpenSslException("Failed to create CSR handle");
     }
     return $result;
 }
Example #17
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);
 }
Example #18
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;
 }
Example #19
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);
}
Example #20
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);
 }
Example #21
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);
 }
Example #22
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);
 }
 /**
  * Generates a new key pair and returns it as an array, which has
  * 0 => Public Key
  * 1 => Exponent
  * 3 => Private Key
  *
  * @return array
  */
 public function createKeys()
 {
     // Initialize
     $keyResource = openssl_pkey_new();
     $csr = openssl_csr_new(array(), $keyResource);
     // Export the private key
     openssl_pkey_export($keyResource, $privateKey);
     // Export the public key
     openssl_csr_export($csr, $data, FALSE);
     preg_match('/Modulus:\\n?(?P<publicKey>[a-f0-9:\\s]+)\\s*Exponent:\\s*(?P<exponent>[0-9]+)/', $data, $matches);
     $publicKey = trim(strtoupper(substr(preg_replace('/[\\s\\n\\r:]+/', '', $matches['publicKey']), 2)));
     $exponent = (int) $matches['exponent'];
     openssl_free_key($keyResource);
     return array($publicKey, $exponent, $privateKey);
 }
 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);
 }
Example #26
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;
 }
Example #27
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);
 }
Example #28
-1
 /**
  * Gera um no certificado
  * @param  string $file Local do Arquivo.
  * @return object.
  */
 public function generatePassword($file = 'certificate.crt')
 {
     $dn = [];
     if ($this->getStateOrProvinceName() !== false) {
         $dn['stateOrProvinceName'] = $this->getStateOrProvinceName();
     }
     if ($this->getLocalityName() !== false) {
         $dn['localityName'] = $this->getLocalityName();
     }
     if ($this->getOrganizationName() !== false) {
         $dn['organizationName'] = $this->getOrganizationName();
     }
     if ($this->getCountryName() !== false) {
         $dn['countryName'] = $this->getCountryName();
     }
     if ($this->getOrganizationalUnitName() !== false) {
         $dn['organizationalUnitName'] = $this->getOrganizationalUnitName();
     }
     if ($this->getCommonName() !== false) {
         $dn['commonName'] = $this->getCommonName();
     }
     if ($this->getEmailAddress() !== false) {
         $dn['emailAddress'] = $this->getEmailAddress();
     }
     $private_key = openssl_pkey_new();
     $csr = openssl_csr_new($dn, $private_key);
     openssl_csr_export_to_file($csr, DIR_ROOT . $file, true);
     openssl_csr_export_to_file($csr, DIR_ROOT . preg_replace('/(\\..*)$/', '-details$1', $file), false);
     openssl_csr_export($csr, $password);
     $this->password = $password;
     return $this;
 }
Example #29
-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";
}
 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);
 }