/** * @return string */ public function __toString() { $this->generate(); $output = ''; openssl_csr_export($this->request, $output); return $output; }
/** * {@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))); }
/** * 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; }
/** * 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; }
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"]); }
/** * 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; }
private function getCSRFromFile($file) { $rsa = $this->getFile($file); $csr = openssl_csr_new(array(), $rsa); openssl_csr_export($csr, $csr_out); return $csr_out; }
/** * Export this CSR * * @return string CSR */ public function export() { if (FALSE === openssl_csr_export($this->_res, $out)) { trigger_error(implode("\n @", OpenSslUtil::getErrors()), E_USER_NOTICE); throw new XPException('Could not export CSR'); } return $out; }
/** * Generate a CSR from the given distinguishedName and keyPair. * * @param CertificateRequest $certificateRequest * * @return string */ public function signCertificateRequest(CertificateRequest $certificateRequest) { $csrObject = $this->createCsrWithSANsObject($certificateRequest); if (!$csrObject || !openssl_csr_export($csrObject, $csrExport)) { throw new CSRSigningException(sprintf('OpenSSL CSR signing failed with error: %s', openssl_error_string())); } return $csrExport; }
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); }
/** * 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); }
/** * A method for exporting the certificate. * * @param mixed $password * @return string */ public function export($type = 'x509', $password = null) { if ($this->signed === false) { openssl_csr_export($this->csr, $out); return $out; } else { switch ($type) { case 'x509': openssl_x509_export($this->csr, $out); break; case 'pkcs12': openssl_pkcs12_export($this->csr, $out, $this->keyPair->privateKey, $password); break; } return $out; } }
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); }
function test_openssl_csr_sign() { $dn = array("countryName", "stateOrProvinceName", "localityName", "organizationName", "organizationalUnitName", "commonName", "emailAddress"); $privkeypass = "******"; $numberofdays = 365; $privkey = openssl_pkey_new(); VERIFY($privkey != null); $csr = openssl_csr_new($dn, $privkey); VERIFY($csr != null); $scert = openssl_csr_sign($csr, null, $privkey, $numberofdays); openssl_x509_export($scert, $publickey); openssl_pkey_export($privkey, $privatekey, $privkeypass); openssl_csr_export($csr, $csrStr); VERIFY(strlen($privatekey) > 500); VERIFY(strlen($publickey) > 800); VERIFY(strlen($csrStr) > 500); }
public function gen_CSR_PKey($dn, &$privKey, &$csr_export) { $config = array("digest_alg" => "sha1", "private_key_bits" => 2048, "private_key_type" => OPENSSL_KEYTYPE_RSA); $dn_full = array_merge(array("countryName" => "RU", "stateOrProvinceName" => "Russia", "localityName" => ".", "organizationalUnitName" => "."), $dn); $res = openssl_pkey_new($config); $csr_origin = openssl_csr_new($dn_full, $res); $csr_full = ""; openssl_pkey_export($res, $privKey); openssl_csr_export($csr_origin, $csr_export); openssl_csr_export($csr_origin, $csr_full, false); preg_match('"Signature Algorithm\\: (.*)-----BEGIN"ims', $csr_full, $sign); $sign = str_replace("\t", "", $sign); if ($sign) { $sign = $sign[1]; $a = explode("\n", $sign); unset($a[0]); $sign = str_replace(" ", "", trim(join("\n", $a))); } return $sign; }
function csr_generate(&$cert, $keylen, $dn, $digest_alg = "sha256") { $args = array("x509_extensions" => "v3_req", "digest_alg" => $digest_alg, "private_key_bits" => (int) $keylen, "private_key_type" => OPENSSL_KEYTYPE_RSA, "encrypt_key" => false); // generate a new key pair $res_key = openssl_pkey_new($args); if (!$res_key) { return false; } // generate a certificate signing request $res_csr = openssl_csr_new($dn, $res_key, $args); if (!$res_csr) { return false; } // export our request data if (!openssl_pkey_export($res_key, $str_key) || !openssl_csr_export($res_csr, $str_csr)) { return false; } // return our request information $cert['csr'] = base64_encode($str_csr); $cert['prv'] = base64_encode($str_key); return true; }
function csr_generate(&$cert, $keylen, $dn, $digest_alg = 'sha256') { $args = array('config' => '/usr/local/etc/ssl/opnsense.cnf', 'private_key_type' => OPENSSL_KEYTYPE_RSA, 'private_key_bits' => (int) $keylen, 'x509_extensions' => 'v3_req', 'digest_alg' => $digest_alg, 'encrypt_key' => false); // generate a new key pair $res_key = openssl_pkey_new($args); if (!$res_key) { return false; } // generate a certificate signing request $res_csr = openssl_csr_new($dn, $res_key, $args); if (!$res_csr) { return false; } // export our request data if (!openssl_pkey_export($res_key, $str_key) || !openssl_csr_export($res_csr, $str_csr)) { return false; } // return our request information $cert['csr'] = base64_encode($str_csr); $cert['prv'] = base64_encode($str_key); return true; }
private function doRequestCertificate(KeyPair $keyPair, array $domains) : Generator { if (!($privateKey = openssl_pkey_get_private($keyPair->getPrivate()))) { throw new AcmeException("Couldn't use private key"); } $san = implode(",", array_map(function ($dns) { return "DNS:" . $dns; }, $domains)); $csr = openssl_csr_new(["CN" => reset($domains), "ST" => "Germany", "C" => "DE", "O" => "Unknown", "subjectAltName" => $san, "basicConstraints" => "CA:FALSE", "extendedKeyUsage" => "serverAuth"], $privateKey, ["digest_alg" => "sha256", "req_extensions" => "v3_req"]); if (!$csr) { throw new AcmeException("CSR couldn't be generated!"); } openssl_csr_export($csr, $csr); $begin = "REQUEST-----"; $end = "----END"; $csr = substr($csr, strpos($csr, $begin) + strlen($begin)); $csr = substr($csr, 0, strpos($csr, $end)); $enc = new Base64UrlSafeEncoder(); /** @var Response $response */ $response = (yield $this->acmeClient->post(AcmeResource::NEW_CERTIFICATE, ["csr" => $enc->encode(base64_decode($csr))])); if ($response->getStatus() === 201) { if (!$response->hasHeader("location")) { throw new AcmeException("Protocol Violation: No Location Header"); } return current($response->getHeader("location")); } throw new AcmeException("Invalid response code: " . $response->getStatus() . "\n" . $response->getBody()); }
function createPublicPrivate() { global $gbl, $sgbl, $login, $ghtml; $data["commonName"] = "lxcenter.org"; $data["countryName"] = "IN"; $data["stateOrProvinceName"] = "in"; $data["localityName"] = "in"; $data["organizationName"] = "lx"; $data["organizationalUnitName"] = "soft"; $data["emailAddress"] = "*****@*****.**"; foreach ($data as $key => $value) { $ltemp[$key] = $value; } $privkey = openssl_pkey_new(); openssl_pkey_export($privkey, $text_key_content); $csr = openssl_csr_new($ltemp, $privkey); openssl_csr_export($csr, $text_csr_content); $sscert = openssl_csr_sign($csr, null, $privkey, 365); openssl_x509_export($sscert, $text_crt_content); $this->text_private_key = $text_key_content; $this->text_public_key = $text_crt_content; }
public function paypal_encrypt_wizard_step2() { access::verify_csrf(); $form = self::keyGenerationForm(); if (!$form->validate()) { self::paypal_encrypt_wizard_step1(); return; } $ssldir = str_replace('\\', '/', VARPATH . 'certificate'); $ssldir = rtrim($ssldir, '/') . '/'; if (!is_dir($ssldir)) { // Create the upload directory mkdir($ssldir, 0777, TRUE); } $prkeyfile = $ssldir . "myprvkey.pem"; $pubcertfile = $ssldir . "mypubcert.pem"; $certreqfile = $ssldir . "mycertreq.pem"; $dn = array("countryName" => $form->encrypt->countryName->value, "stateOrProvinceName" => $form->encrypt->stateOrProvinceName->value, "localityName" => $form->encrypt->localityName->value, "organizationName" => $form->encrypt->organizationName->value, "organizationalUnitName" => $form->encrypt->organizationalUnitName->value, "commonName" => $form->encrypt->commonName->value, "emailAddress" => $form->encrypt->emailAddress->value); $privkeypass = $form->encrypt->privKeyPass->value; $numberofdays = 365; $config = array("private_key_bits" => 1024); $privkey = openssl_pkey_new($config); $csr = openssl_csr_new($dn, $privkey); $sscert = openssl_csr_sign($csr, null, $privkey, $numberofdays); openssl_x509_export($sscert, $publickey); openssl_pkey_export($privkey, $privatekey, $privkeypass); openssl_csr_export($csr, $csrStr); openssl_x509_export_to_file($sscert, $pubcertfile); openssl_pkey_export_to_file($privkey, $prkeyfile, $privkeypass); openssl_csr_export_to_file($csr, $certreqfile); //echo "Your Public Certificate has been saved to " . $pubcertfile . "<br><br>"; //echo "Your Private Key has been saved to " . $prkeyfile . "<br><br>"; //echo "Your Certificate Request has been saved to " . $certreqfile . "<br><br>"; //echo $privatekey; // Will hold the exported PriKey //echo $publickey; // Will hold the exported PubKey //echo $csrStr; // Will hold the exported Certificate }
/** * Generates a CSR for one or more domains. * * @since 1.0.0 * @access public * * @param resource $key_resource The private key resource for the CSR. * @param array $domains Array of domains the CSR should be created for. * @param array $dn Array of CSR settings. It should have the array keys * 'ST' (for country), 'C' (for two-letter country code) * and 'O' (for organization name). * @return string|WP_Error The generated CSR if successful or an error object otherwise. */ public function generate_csr($key_resource, $domains, $dn = array()) { $filesystem = Util::get_filesystem(); $status = Util::maybe_create_letsencrypt_certificates_dir(); if (is_wp_error($status)) { return $status; } $san = implode(',', array_map(array($this, 'dnsify'), $domains)); $output = 'HOME = . RANDFILE = $ENV::HOME/.rnd [ req ] default_bits = 2048 default_keyfile = privkey.pem distinguished_name = req_distinguished_name req_extensions = v3_req [ req_distinguished_name ] countryName = Country Name (2 letter code) [ v3_req ] basicConstraints = CA:FALSE subjectAltName = ' . $san . ' keyUsage = nonRepudiation, digitalSignature, keyEncipherment'; $tmp_config_path = tempnam(sys_get_temp_dir(), 'wpenc'); if (false === $filesystem->put_contents($tmp_config_path, $output)) { return new WP_Error('csr_cannot_write_tmp_file', __('Could not write CSR configuration to temporary file. Please check your filesystem permissions.', 'wp-encrypt')); } $dn = wp_parse_args($dn, array('CN' => $this->domain, 'ST' => 'United States of America', 'C' => 'US', 'O' => 'Unknown')); $dn = apply_filters('wp_encrypt_csr_dn', $dn, $this->domain); $csr = openssl_csr_new($dn, $key_resource, array('config' => $tmp_config_path, 'digest_alg' => 'sha256')); if (false === $csr) { $filesystem->delete($tmp_config_path); return new WP_Error('csr_cannot_generate', sprintf(__('Could not generate CSR. Original error message: %s', 'wp-encrypt'), openssl_error_string())); } if (false === openssl_csr_export($csr, $csr)) { $filesystem->delete($tmp_config_path); return new WP_Error('csr_cannot_export', sprintf(__('Could not export CSR. Original error message: %s', 'wp-encrypt'), openssl_error_string())); } $filesystem->delete($tmp_config_path); if (false === $filesystem->put_contents($this->path . '/last.csr', $csr)) { return new WP_Error('csr_cannot_write', sprintf(__('Could not write CSR into file <code>%s</code>. Please check your filesystem permissions.', 'wp-encrypt'), $this->path . '/last.csr')); } preg_match('#REQUEST-----(.*)-----END#s', $csr, $matches); return trim($matches[1]); }
function updategenerate_csr($param) { $s = new sslcert(null, null, null); dprintr($param); $dn = array("countryName" => $param['ssl_data_b_s_countryName_r'], "stateOrProvinceName" => $param['ssl_data_b_s_stateOrProvinceName_r'], "localityName" => $param['ssl_data_b_s_localityName_r'], "organizationName" => $param['ssl_data_b_s_organizationName_r'], "organizationalUnitName" => $param['ssl_data_b_s_organizationalUnitName_r'], "commonName" => $param['ssl_data_b_s_commonName_r'], "emailAddress" => $param['ssl_data_b_s_emailAddress_r']); //$fp=@fopen("/home/root/nag.txt","w"); $privkey = openssl_pkey_new(); $csr = openssl_csr_new($dn, $privkey); $sscert = openssl_csr_sign($csr, null, $privkey, 365); openssl_csr_export($csr, $csrout); mail($this->contactemail, "Kloxo CSR", $csrout); openssl_x509_export($sscert, $certout); mail($this->contactemail, "cert", $certout); openssl_pkey_export($privkey, $pkeyout, null); mail($this->contactemail, "public-key", $pkeyout); throw new lxException("csr_sent_to_email", ''); }
/** * Add a server certificate request from POST data * Post variable possibilities: CommonName, OrgName, * OrgUnitName, EmailAddress, LocalityName, StateName, CountryName, * PassPhrase, ExportPassPhrase * @return void */ public function actionServerCsrAdd() { $this->moduleRequired('ca'); // Normalize/validate variables $CommonName = isset($_POST['CommonName']) ? stripslashes(trim($_POST['CommonName'])) : false; $OrgName = isset($_POST['OrgName']) ? stripslashes(trim($_POST['OrgName'])) : false; $OrgUnitName = isset($_POST['OrgUnitName']) ? stripslashes(trim($_POST['OrgUnitName'])) : false; $EmailAddress = isset($_POST['EmailAddress']) ? stripslashes(trim($_POST['EmailAddress'])) : false; $LocalityName = isset($_POST['LocalityName']) ? stripslashes(trim($_POST['LocalityName'])) : false; $StateName = isset($_POST['StateName']) ? stripslashes(trim($_POST['StateName'])) : false; $CountryName = isset($_POST['CountryName']) ? stripslashes(trim($_POST['CountryName'])) : false; $PassPhrase = isset($_POST['PassPhrase']) ? stripslashes(trim($_POST['PassPhrase'])) : false; $ExportPassPhrase = isset($_POST['ExportPassPhrase']) ? stripslashes(trim($_POST['ExportPassPhrase'])) : false; if (!is_string($PassPhrase) or strlen($PassPhrase) < 1) { $PassPhrase = null; } if (!is_string($ExportPassPhrase) or strlen($ExportPassPhrase) < 1) { $ExportPassPhrase = null; } // Validate required if (!is_string($CommonName)) { return 'Must specify a valid Host name.'; } if (!is_string($OrgName)) { return 'Must specify a valid Organization name.'; } if (!is_string($OrgUnitName)) { return 'Must specify a valid Organizational Unit name.'; } if (!is_string($EmailAddress)) { return 'Must specify a valid Email Address.'; } if (!is_string($LocalityName)) { return 'Must specify a valid City name.'; } if (!is_string($StateName)) { return 'Must specify a valid State name.'; } if (!is_string($CountryName) or strlen($CountryName) !== 2) { return 'Must specify a valid Country name.'; } // Create dn args $dnargs = array(); $dnargs['commonName'] = $CommonName; $dnargs['emailAddress'] = $EmailAddress; $dnargs['countryName'] = $CountryName; $dnargs['organizationName'] = $OrgName; $dnargs['organizationalUnitName'] = $OrgUnitName; $dnargs['localityName'] = $LocalityName; $dnargs['stateOrProvinceName'] = $StateName; $cfgargs = array(); $cfgargs['config'] = OPENSSL_CONF; $cfgargs['x509_extensions'] = 'v3_server'; // Generate private key $privkey = openssl_pkey_new($cfgargs); if ($privkey === false) { return 'Failed to generate private key: ' . openssl_error_string(); } // Issue CSR with newly generated key. If an export passphrase was // requested, add it. if (!empty($ExportPassPhrase)) { $cfgargs['encrypt_key'] = $ExportPassPhrase; } $csr = openssl_csr_new($dnargs, $privkey, $cfgargs); if ($csr === false) { return 'Failed to generate CSR: ' . openssl_error_string(); } // Export the private key $rc = openssl_pkey_export($privkey, $privkeyPem, $PassPhrase, $cfgargs); if ($rc === false) { $errors = openssl_error_string(); return 'Failed to export the private key: ' . $errors; } // Export the public key $junk = openssl_pkey_get_details(openssl_csr_get_public_key($csr)); if (!is_array($junk) or !isset($junk['key'])) { return 'Failed to extract public key.'; } $pubkeyPem = $junk['key']; // Export the csr $rc = openssl_csr_export($csr, $csrPem); if ($rc === false) { $errors = openssl_error_string(); return 'Failed to export the csr: ' . $errors; } // // Do the insert // $this->moduleRequired('csrserver'); $this->csrserver->resetProperties(); $this->csrserver->setProperty('CommonName', $CommonName); $this->csrserver->setProperty('CountryName', $CountryName); $this->csrserver->setProperty('CreateDate', 'now()'); $this->csrserver->setProperty('CSR', $csrPem); // $this->csrserver->setProperty('Description', ); $this->csrserver->setProperty('EmailAddress', $EmailAddress); $this->csrserver->setProperty('LocalityName', $LocalityName); $this->csrserver->setProperty('OrgName', $OrgName); $this->csrserver->setProperty('OrgUnitName', $OrgUnitName); $this->csrserver->setProperty('PrivateKey', $privkeyPem); $this->csrserver->setProperty('PublicKey', $pubkeyPem); $this->csrserver->setProperty('StateName', $StateName); $this->csrserver->populated = true; $rc = $this->csrserver->add(); if (!($rc === true)) { return 'Insert Failed: ' . $rc; } return true; }
// OpenSSL X.509 CSR $ca_cert = openssl_csr_sign($ca_csr, null, $ca_priv, 365); // OpenSSL X.509 $ca_pubout = openssl_pkey_get_details($ca_priv)['key']; //var_dump($ca_pubout); openssl_pkey_export($ca_priv, $ca_privout, $password, $config); // && var_dump('CA Private', $ca_privout); openssl_x509_export($ca_cert, $ca_certout); // and var_dump('CA cert', $ca_certout); $path = __DIR__ . '/ca'; file_put_contents($path . '/ca_cert.cer', $ca_certout); file_put_contents($path . '/ca_priv.pem', $ca_privout); // SELF $priv = openssl_pkey_new($config); $csr = openssl_csr_new($dn, $priv, $config); openssl_csr_export($csr, $csrout); // ********** 签署证书 ********** // 自签证书 $cert_self = openssl_csr_sign($csrout, null, $priv, 365); openssl_x509_export($cert_self, $certout_self); // CA 签证书 $cert_ca = openssl_csr_sign($csr, $ca_certout, [$ca_privout, $password], 365); openssl_x509_export($cert_ca, $certout_ca); $cert_other_file = __DIR__ . '/keys/cert-x509.crt'; $certout_other = file_get_contents($cert_other_file); // 验证公私钥是否成对 function check_pair($cert, $priv) { $msg = openssl_x509_check_private_key($cert, $priv) ? '+Ok, Match' : '-Err, Not Match'; echo $msg . "\n\n"; }
public function exportCsr($file) { $out = null; openssl_csr_export($this->csr, $out); file_put_contents($file, $out); }
private function generateCSR($privateKey, array $domains) { $domain = reset($domains); $san = implode(",", array_map(function ($dns) { return "DNS:" . $dns; }, $domains)); $tmpConf = tmpfile(); $tmpConfMeta = stream_get_meta_data($tmpConf); $tmpConfPath = $tmpConfMeta["uri"]; // workaround to get SAN working fwrite($tmpConf, 'HOME = . RANDFILE = $ENV::HOME/.rnd [ req ] default_bits = 2048 default_keyfile = privkey.pem distinguished_name = req_distinguished_name req_extensions = v3_req [ req_distinguished_name ] countryName = Country Name (2 letter code) [ v3_req ] basicConstraints = CA:FALSE subjectAltName = ' . $san . ' keyUsage = nonRepudiation, digitalSignature, keyEncipherment'); $csr = openssl_csr_new(array("CN" => $domain, "ST" => $this->state, "C" => $this->countryCode, "O" => "Unknown"), $privateKey, array("config" => $tmpConfPath, "digest_alg" => "sha256")); if (!$csr) { throw new \RuntimeException("CSR couldn't be generated! " . openssl_error_string()); } openssl_csr_export($csr, $csr); fclose($tmpConf); $csrPath = $this->getDomainPath($domain) . "/last.csr"; file_put_contents($csrPath, $csr); return $this->getCsrContent($csrPath); }
<?php // 建立 .cer/.pfx 证书文件 function _var($mixed, $is_dump = false) { if ($is_dump) { var_dump($mixed); } } $dn = array("countryName" => "CN", "stateOrProvinceName" => "Beijing", "localityName" => "Beijing", "organizationName" => "Eyou", "organizationalUnitName" => "Develop team", "commonName" => "Li Bo", "emailAddress" => "*****@*****.**"); $config = array('config' => '/etc/pki/tls/openssl.cnf', 'encrypt_key' => 1, 'private_key_type' => OPENSSL_KEYTYPE_RSA, "digest_alg" => "sha1", 'x509_extensions' => 'v3_ca', 'private_key_bits' => 1024, "encrypt_key_cipher" => OPENSSL_CIPHER_AES_256_CBC); $privkey = openssl_pkey_new($config); var_dump($privkey); $csr = openssl_csr_new($dn, $privkey); var_dump($csr); $sscert = openssl_csr_sign($csr, null, $privkey, 365); var_dump($sscert); exit; $path = __DIR__ . '/keys'; $path_pub = "{$path}/cert-x509.crt"; $path_priv = "{$path}/cert-pkcs12.pfx"; openssl_csr_export($csr, $csrout) and _var($csrout); openssl_x509_export_to_file($sscert, $path_pub); // export to pfx style // PKCS #12(公钥加密标准 #12)是业界格式,适用于证书及相关私钥的传输、备份和还原。 $pub_key = file_get_contents($path_pub); openssl_pkcs12_export_to_file($pub_key, $path_priv, $privkey, 'mypassword', $config); while (($e = openssl_error_string()) !== false) { echo $e . "\n"; } echo "ok, create certificate/private-key";
/** * @param bool $verbose * * @return string */ public function export(bool $verbose = false) : string { openssl_csr_export($this->getHandle(), $output, !$verbose); return $output; }
function createNewcertificate() { global $gbl, $sgbl, $login, $ghtml; foreach ($this->ssl_data_b as $key => $value) { if (!cse($key, "_r")) { continue; } $nk = strtil($key, "_r"); $temp[$nk] = $value; } foreach ($temp as $key => $t) { if ($key === "countryName") { $l = explode(":", $t); $name = $l[0]; } else { $name = $t; } $ltemp[$key] = $name; } $config['private_key_bits'] = 1024; $privkey = openssl_pkey_new($config); openssl_pkey_export($privkey, $text_key_content); $csr = openssl_csr_new($ltemp, $privkey); openssl_csr_export($csr, $text_csr_content); $sscert = openssl_csr_sign($csr, null, $privkey, 3650); openssl_x509_export($sscert, $text_crt_content); $this->text_key_content = $text_key_content; $this->text_csr_content = $text_csr_content; $this->text_crt_content = $text_crt_content; }
/** * 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; }