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}"); }
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 }
function ocsp_verify_json($raw_cert_data, $raw_next_cert_data, $ocsp_uri) { //uses openssl cli to validate cert status with ocsp global $random_blurp, $timeout; $result = array(); $tmp_dir = '/tmp/'; $root_ca = getcwd() . '/cacert.pem'; $pem_issuer = ""; $pem_client = ""; openssl_x509_export($raw_cert_data, $pem_client); openssl_x509_export_to_file($raw_cert_data, $tmp_dir . $random_blurp . '.cert_client.pem'); openssl_x509_export($raw_next_cert_data, $pem_issuer); openssl_x509_export_to_file($raw_next_cert_data, $tmp_dir . $random_blurp . '.cert_issuer.pem'); $isser_loc = $tmp_dir . $random_blurp . '.cert_issuer.pem'; // Some OCSP's want HTTP/1.1 but OpenSSL does not do that. Add Host header as workaround. $ocsp_host = parse_url($ocsp_uri, PHP_URL_HOST); $output = shell_exec('timeout ' . $timeout . ' | openssl ocsp -no_nonce -CAfile ' . $root_ca . ' -issuer ' . $isser_loc . ' -cert ' . $tmp_dir . $random_blurp . '.cert_client.pem -url "' . escapeshellcmd($ocsp_uri) . '" -header "HOST" "' . escapeshellcmd($ocsp_host) . '" 2>&1'); $filter_output = shell_exec('timeout ' . $timeout . ' | openssl ocsp -no_nonce -CAfile ' . $root_ca . ' -issuer ' . $isser_loc . ' -cert ' . $tmp_dir . $random_blurp . '.cert_client.pem -url "' . escapeshellcmd($ocsp_uri) . '" -header "HOST" "' . escapeshellcmd($ocsp_host) . '" 2>&1 | grep -v -e "to get local issuer certificate" -e "signer certificate not found" -e "Response Verify" -e "' . $tmp_dir . $random_blurp . '.cert_client.pem"'); $output = preg_replace("/[[:blank:]]+/", " ", $output); $ocsp_status_lines = explode("\n", $output); $ocsp_status_lines = array_map('trim', $ocsp_status_lines); foreach ($ocsp_status_lines as $line) { if (endsWith($line, ":") == false) { list($k, $v) = explode(":", $line, 2); if (trim($k)) { $lines[trim($k)] = trim($v); } } } if ($lines[$tmp_dir . $random_blurp . ".cert_client.pem"] == "good") { $result["status"] = "good"; } else { if ($lines[$tmp_dir . $random_blurp . ".cert_client.pem"] == "revoked") { $result["status"] = "revoked"; } else { $result["error"] = $filter_output; $result["status"] = "unknown"; } } if (isset($lines["This Update"])) { $result["this_update"] = $lines["This Update"]; } if (isset($lines["Next Update"])) { $result["next_update"] = $lines["Next Update"]; } if (isset($lines["Reason"])) { $result["reason"] = $lines["Reason"]; } if (isset($lines["Revocation Time"])) { $result["revocation_time"] = $lines["Revocation Time"]; } $result["ocsp_uri"] = $ocsp_uri; //remove temp files after use unlink($tmp_dir . $random_blurp . '.cert_client.pem'); unlink($tmp_dir . $random_blurp . '.cert_issuer.pem'); return $result; }
function spki_hash($raw_cert_data) { global $random_blurp; $tmp_dir = '/tmp/'; openssl_x509_export_to_file($raw_cert_data, $tmp_dir . $random_blurp . '.cert_client.pem'); $output = shell_exec('openssl x509 -noout -in ' . $tmp_dir . $random_blurp . '.cert_client.pem -pubkey | openssl asn1parse -noout -inform pem -out ' . $tmp_dir . $random_blurp . '.public.key; openssl dgst -sha256 -binary ' . $tmp_dir . $random_blurp . '.public.key | openssl enc -base64 2>&1'); unlink($tmp_dir . $random_blurp . '.cert_client.pem'); unlink($tmp_dir . $random_blurp . '.public.key'); return trim(htmlspecialchars($output)); }
/** * Given this Remote Desktop instance, generate files with pkcs12 and * x509 certificate to a given directory using a password for the desktop * and the private key. * * Returns the path to the x509 file. * * @return string */ public function export($directory, $filePrefix, $keyPassword, $overwrite = false) { if (!is_writeable($directory)) { throw new \RuntimeException("Key Export directory is not writable: " . $directory); } $pkcs12File = $directory . "/" . $filePrefix . ".pfx"; $x509File = $directory . "/" . $filePrefix . ".cer"; if (!$overwrite && file_exists($pkcs12File)) { throw new \RuntimeException("PKCS12 File at " . $pkcs12File . " already exists and is not overwritten."); } if (!$overwrite && file_exists($x509File)) { throw new \RuntimeException("X509 Certificate File at " . $x509File . " already exists and is not overwritten."); } $args = array('friendly_name' => 'AzureDistributionBundle for Symfony Tools'); openssl_pkcs12_export_to_file($this->certificate, $pkcs12File, $this->privKey, $keyPassword, $args); openssl_x509_export_to_file($this->certificate, $x509File, true); return $x509File; }
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 }
// Generate a new private (and public) key pair $privkey = openssl_pkey_new($SSLcnf); // Generate a certificate signing request $csr = openssl_csr_new($dn, $privkey, $SSLcnf); // You will usually want to create a self-signed certificate at this // point until your CA fulfills your request. // This creates a self-signed cert that is valid for 365 days $sscert = openssl_csr_sign($csr, null, $privkey, 365, $SSLcnf); // 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. //CERTIFICADO openssl_csr_export_to_file($csr, $fncert, false); //CERTIFICADO AUTO-ASSINADO openssl_x509_export_to_file($sscert, $fnsscert, false); //CHAVE PRIVADA (private.pem) openssl_pkey_export_to_file($privkey, $fnprivate, null, $SSLcnf); //CHAVE PÚBLICA (public.key) file_put_contents($fnpublic, openssl_pkey_get_details($privkey)['key']); /** * @todo Criar rotinas de interceptação de erros * */ // Show any errors that occurred here //while (($e = openssl_error_string()) !== false) { // echo "\n".$e."\n"; //}
public function createx509($o, $p, $x, $f = false) { $a = openssl_pkey_get_private($p, $x); $b = openssl_csr_new($o['dn'], $a, $o['config']); $c = openssl_csr_sign($b, null, $a, 365); $f === false ? openssl_x509_export($c, $d) : openssl_x509_export_to_file($c, $f); return $f === false ? $d : $f; }
public static function keygen($userid, $info = false) { $dn = is_array($info) ? $info : array("countryName" => 'NG', "stateOrProvinceName" => 'FCT', "localityName" => 'Abuja', "organizationName" => 'Ultison Technologies', "organizationalUnitName" => 'Software Operations', "commonName" => 'Ultison', "emailAddress" => '*****@*****.**'); $privkeypass = config::$privateKeyPassword; $numberofdays = 365; if (!self::cryptoInstalled()) { gio::log("... Could not generate cryptographic keys for {$userid} ...", E_USER_ERROR); return false; } gio::log("Generating cryptographic keys for {$userid}...", VERBOSE); try { $privkey = openssl_pkey_new(self::$keyOpts); $privateKey = ""; $csr = openssl_csr_new($dn, $privkey, self::$keyOpts); $sscert = openssl_csr_sign($csr, null, $privkey, $numberofdays, self::$keyOpts); openssl_x509_export($sscert, $publickey); openssl_x509_export_to_file($sscert, self::getcert($userid)); openssl_pkey_export($privkey, $privatekey, $privkeypass, self::$keyOpts); gio::savetofile($privatekey, self::getkey($userid, true), config::$privateKeyFileMode); gio::savetofile($publickey, self::getkey($userid), config::$publicKeyFileMode); } catch (Exception $e) { gio::log("Error while generating cryptographic keys for {$userid}: " . $e->message, E_USER_ERROR); return false; } gio::log("... Done generating cryptographic keys for {$userid}", VERBOSE); return true; }
private function genPublicKeyFile() { openssl_x509_export_to_file($this->publicKey, $this->publicKeyFileName); }
$comN = stripslashes($_POST['commonName']); $on = stripslashes($_POST['organizationName']); $oun = stripslashes($_POST['organizationUnitName']); $mail = stripslashes($_POST['emailAdress']); $ln = stripslashes($_POST['localityName']); $sopn = stripslashes($_POST['stateOrProvinceName']); $cn = stripslashes($_POST['countryName']); if (isset($cn) && isset($sopn) && isset($ln) && isset($on) && isset($oun) && isset($comN) && isset($mail)) { //récupération des informations du certificat principal $CAcrt = "certificat.crt"; $CAkey = array("cles.txt", "monmot2passe"); // Assigne les valeurs du nom distingué à utiliser avec le certificat. $dn = array("countryName" => $cn, "stateOrProvinceName" => $sopn, "localityName" => $ln, "organizationName" => $on, "organizationalUnitName" => $oun, "commonName" => $comN, "emailAddress" => $mail); // Génère les clés privée et publique $privkey = openssl_pkey_new(); // Génère la requête de signature de certificat $csr = openssl_csr_new($dn, $privkey); // Cette commande crée une certificat signer par l'autorité supérieur valide 1 ans soit 365 jours $sscert = openssl_csr_sign($csr, $CAcrt, $CAkey, 365); // préserver la clé privée, la CSR et le certificat auto-signé, //de façon à ce qu'ils puissent être installés sur le site internet. // éléments dans des fichiers. // Typiquement, l'autorité de certification émettra un "vrai" certificat. openssl_csr_export_to_file($csr, "requeteSignaturePerso" . $comN . ".txt"); openssl_x509_export_to_file($sscert, "certificatPerso" . $comN . ".txt"); openssl_pkey_export_to_file($privkey, "clesPerso" . $comN . ".txt"); // Affiche les erreurs qui sont survenues while (($e = openssl_error_string()) !== false) { echo $e . "\n"; } }
$SSL = array('encrypt_key' => true, 'private_key_type' => OPENSSL_KEYTYPE_DSA, 'digest_alg' => 'md5', 'x509_extensions' => 'v3_ca', 'private_key_bits' => 1024); $config = array("digest_alg" => "md5", "private_key_bits" => 1024, "private_key_type" => OPENSSL_KEYTYPE_RSA); $privkey_enc = openssl_pkey_new($config); $csr = openssl_csr_new($dn, $privkey_enc, $SSL); $sscert = openssl_csr_sign($csr, null, $privkey_enc, 365); openssl_csr_export($csr, $csrout); openssl_x509_export($sscert, $sscertout); openssl_pkey_export($privkey_enc, $privkeyout); $pubkey = openssl_pkey_get_details($privkey_enc)["key"]; // var_dump($csrout); // echo "\n"; // var_dump($sscertout); // echo "\n"; // var_dump($privkeyout); echo "\n"; openssl_x509_export_to_file($sscert, "certificate.crt"); openssl_pkey_export_to_file($privkey_enc, "key.pem"); file_put_contents("key.pub", $pubkey); $zip = new ZipArchive(); $zip->open("certif.zip", ZipArchive::CREATE); $zip->addFile("certificate.crt"); $zip->addFile("key.pub"); $zip->addFile("key.pem"); $zip->close(); unlink("certificate.crt"); unlink("key.pub"); unlink("key.pem"); // Show any errors that occurred here // while (($e = openssl_error_string()) !== false) { // echo $e . "\n"; // }
function spki_hash($raw_cert_data) { global $timeout; global $random_blurp; $tmp_dir = '/tmp/'; //below command returns the SPKI hash of a public key. openssl_x509_export_to_file($raw_cert_data, $tmp_dir . $random_blurp . '.cert_client.pem'); $output = shell_exec('timeout ' . $timeout . 'openssl x509 -noout -in ' . $tmp_dir . $random_blurp . '.cert_client.pem -pubkey | openssl asn1parse -noout -inform pem -out ' . $tmp_dir . $random_blurp . '.public.key; openssl dgst -sha256 -binary ' . $tmp_dir . $random_blurp . '.public.key | openssl enc -base64 2>&1'); //remove those files again. unlink($tmp_dir . $random_blurp . '.cert_client.pem'); unlink($tmp_dir . $random_blurp . '.public.key'); return trim(htmlspecialchars($output)); }
/** * Create and download the following certificates: * - CertificateAuthority.key * - CertificateAuthority.crt * - Server.key * - Server.crt * - admin.p12 * The following form inputs are used: */ function create_and_download_certificates() { global $error_msg; $tempDir = $GLOBALS['temporary_files_dir']; $zipName = $tempDir . "/ssl.zip"; if (file_exists($zipName)) { unlink($zipName); } /* Retrieve the certificate name settings from the form input */ if ($_POST["commonName"]) { $commonName = formData('commonName', 'P', true); } if ($_POST["emailAddress"]) { $emailAddress = formData('emailAddress', 'P', true); } if ($_POST["countryName"]) { $countryName = formData('countryName', 'P', true); } if ($_POST["stateOrProvinceName"]) { $stateOrProvinceName = formData('stateOrProvinceName', 'P', true); } if ($_POST["localityName"]) { $localityName = formData('localityName', 'P', true); } if ($_POST["organizationName"]) { $organizationName = formData('organizationName', 'P', true); } if ($_POST["organizationalUnitName"]) { $organizationName = formData('organizationalUnitName', 'P', true); } if ($_POST["clientCertValidity"]) { $clientCertValidity = formData('clientCertValidity', 'P', true); } /* Create the Certficate Authority (CA) */ $arr = create_csr("OpenEMR CA for " . $commonName, $emailAddress, $countryName, $stateOrProvinceName, $localityName, $organizationName, $organizationalUnitName); if ($arr === false) { $error_msg .= xl('Error, unable to create the Certificate Authority certificate.', 'e'); delete_certificates(); return; } $ca_csr = $arr[0]; $ca_key = $arr[1]; $ca_crt = create_crt($ca_key, $ca_csr, NULL, $ca_key); if ($ca_crt === false) { $error_msg .= xl('Error, unable to create the Certificate Authority certificate.', 'e'); delete_certificates(); return; } openssl_pkey_export_to_file($ca_key, $tempDir . "/CertificateAuthority.key"); openssl_x509_export_to_file($ca_crt, $tempDir . "/CertificateAuthority.crt"); /* Create the Server certificate */ $arr = create_csr($commonName, $emailAddress, $countryName, $stateOrProvinceName, $localityName, $organizationName, $organizationalUnitName); if ($arr === false) { $error_msg .= xl('Error, unable to create the Server certificate.', 'e'); delete_certificates(); return; } $server_csr = $arr[0]; $server_key = $arr[1]; $server_crt = create_crt($server_key, $server_csr, $ca_crt, $ca_key); if (server_crt === false) { $error_msg .= xl('Error, unable to create the Server certificate.', 'e'); delete_certificates(); return; } openssl_pkey_export_to_file($server_key, $tempDir . "/Server.key"); openssl_x509_export_to_file($server_crt, $tempDir . "/Server.crt"); /* Create the client certificate for the 'admin' user */ $serial = 0; $res = sqlStatement("select id from users where username='******'"); if ($row = sqlFetchArray($res)) { $serial = $row['id']; } $user_cert = create_user_certificate("admin", $emailAddress, $serial, $tempDir . "/CertificateAuthority.crt", $tempDir . "/CertificateAuthority.key", $clientCertValidity); if ($user_cert === false) { $error_msg .= xl('Error, unable to create the admin.p12 certificate.', 'e'); delete_certificates(); return; } $adminFile = $tempDir . "/admin.p12"; $handle = fopen($adminFile, 'w'); fwrite($handle, $user_cert); fclose($handle); /* Create a zip file containing the CertificateAuthority, Server, and admin files */ try { if (!class_exists('ZipArchive')) { $_SESSION["zip_error"] = "Error, Class ZipArchive does not exist"; return; } $zip = new ZipArchive(); if (!$zip) { $_SESSION["zip_error"] = "Error, Could not create file archive"; return; } if ($zip->open($zipName, ZIPARCHIVE::CREATE)) { $files = array("CertificateAuthority.key", "CertificateAuthority.crt", "Server.key", "Server.crt", "admin.p12"); foreach ($files as $file) { $zip->addFile($tempDir . "/" . $file, $file); } } else { $_SESSION["zip_error"] = "Error, unable to create zip file with all the certificates"; return; } $zip->close(); if (ini_get('zlib.output_compression')) { ini_set('zlib.output_compression', 'Off'); } } catch (Exception $e) { $_SESSION["zip_error"] = "Error, Could not create file archive"; return; } download_file($zipName, "zip"); }
<?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";
function export_certificate_to_file() { $this->clear_debug_buffer(); // Create empty certificate file; $this->set_certificate_file(); openssl_x509_export_to_file($this->certificate, FILE_LOCATION . $this->certificate_resource_file); $this->debug("export_certificate_to_file"); }
function test_openssl_x509_export_to_file() { $fcert = file_get_contents(__DIR__ . "/test_x509.crt"); $cert = openssl_x509_read($fcert); $tmp = tempnam('/tmp', 'x509vmopenssltest'); unlink($tmp); VS(file_get_contents($tmp), false); VERIFY(openssl_x509_export_to_file($cert, $tmp)); $fcert2 = file_get_contents($tmp); $cert2 = openssl_x509_read($fcert2); $info = openssl_x509_parse($cert2); VS($info['subject']['O'], "RSA Data Security, Inc."); unlink($tmp); }
/** * @param string $fileName * @param string $format * @param bool $verbose * * @return bool */ public function exportToFile(string $fileName, string $format = self::FORMAT_PEM, bool $verbose = FALSE) : bool { return openssl_x509_export_to_file($this->getHandle(), $fileName, !$verbose); }
/** * Generates the private key and certificate used by iDeal * * @return bool True on success, false on failure */ private function GenerateKeyAndCertificate() { if (file_exists($this->_keyFile) && file_exists($this->_certFile)) { return false; } // Create the keypair if (($key = openssl_pkey_new()) === false) { // could not create key $this->SetError(GetLang('IdealCantCreateKeyPair')); return false; } if (file_exists($this->_keyFile)) { if (!unlink($this->_keyFile)) { // could not delete old key file $this->SetError(GetLang('IdealCantDeleteKeyFile', array("keyFile" => $this->_keyFile))); return false; } } // export our key if (!openssl_pkey_export_to_file($key, $this->_keyFile, GetConfig('EncryptionToken'))) { // could not export key $this->SetError(GetLang('IdealCantExportKey')); return false; } chmod($this->_keyFile, ISC_WRITEABLE_FILE_PERM); $dn = array( "countryName" => GetCountryISO2ByName(GetConfig('CompanyCountry')), "stateOrProvinceName" => GetConfig('CompanyState'), "localityName" => GetConfig('CompanyCity'), "organizationName" => GetConfig('CompanyName'), "organizationalUnitName" => GetConfig('CompanyName'), "commonName" => GetConfig('CompanyName'), "emailAddress" => GetConfig('AdminEmail') ); // create our certificate if (($csr = openssl_csr_new($dn, $key)) === false) { // could not create cert $this->SetError(GetLang('IdealCantCreateCert')); return false; } // self sign our certificate if (($sscert = openssl_csr_sign($csr, null, $key, 3650)) === false) { // could not sign cert $this->SetError(GetLang('IdealCantSignCert')); return false; } if (file_exists($this->_certFile)) { if (!unlink($this->_certFile)) { // could not delete old cert file $this->SetError(GetLang('IdealCantDeleteCertFile', array("certFile" => $this->_certFile))); return false; } } // export certificate to file if (!openssl_x509_export_to_file($sscert, $this->_certFile)) { // could not export cert $this->SetError(GetLang('IdealCantExportCert')); return false; } chmod($this->_certFile, ISC_WRITEABLE_FILE_PERM); return true; }
var_dump(openssl_x509_export($e, $output5)); // read an array, fails $outfilename = tempnam("/tmp", "ssl"); if ($outfilename === false) { die("failed to get a temporary filename!"); } echo "---\n"; var_dump(openssl_x509_export_to_file($a, $outfilename)); // read cert as a binary string var_dump(openssl_x509_export_to_file($b, $outfilename)); // read cert from a filename string var_dump(openssl_x509_export_to_file($c, $outfilename)); // read an invalid cert, fails var_dump(openssl_x509_export_to_file($d, $outfilename)); // read cert from a resource var_dump(openssl_x509_export_to_file($e, $outfilename)); // read an array, fails echo "---\n"; var_dump($exists = file_exists($outfilename)); if ($exists) { @unlink($outfilename); } echo "---\n"; if (PHP_EOL !== "\n") { $a = str_replace(PHP_EOL, "\n", $a); } var_dump(strcmp($output, $a)); var_dump(strcmp($output, $output2)); var_dump(strcmp($output, $output3)); var_dump(strcmp($output, $output4)); // different
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"; }