function test_openssl_csr_get_subject() { $csr = openssl_csr_new(null, $ignore); VERIFY($csr != null); $subject = openssl_csr_get_subject($csr)['O']; VERIFY($subject == "Internet Widgits Pty Ltd" || $subject == "Default Company Ltd"); }
/** * Process request and draw page to examine a csr. * @return void */ function getPageCsrView() { global $_WA; $_WA->html->setPageTitle('Examine Certificate Signing Request'); // Prepopulate data we will be pulling $csr_subject = false; $csr_key = false; $csr_asn = false; // Check to see if they have provided a file. $csr_pem = $_WA->html->parseCertificateRequest('csr_file', 'csr'); if (is_string($csr_pem)) { $_WA->moduleRequired('cert'); $csr_subject = openssl_csr_get_subject($csr_pem, false); $junk = preg_split('/(-----((BEGIN)|(END)) CERTIFICATE REQUEST-----)/', $csr_pem); if (isset($junk[1])) { $enc = base64_decode($junk[1]); $csr_asn = $_WA->cert->parseAsn($enc); } $key = openssl_csr_get_public_key($csr_pem); if (is_resource($key)) { $csr_key = openssl_pkey_get_details($key); } } $_WA->html->setVar('csr_pem', &$csr_pem); $_WA->html->setVar('csr_subject', &$csr_subject); $_WA->html->setVar('csr_key', &$csr_key); $_WA->html->setVar('csr_asn', &$csr_asn); die($_WA->html->loadTemplate('utils.csr.view.php')); }
public function test signCertificateRequest with subject alternative names() { $dummyDistinguishedName = new DistinguishedName('acmephp.com', 'FR', 'france', 'Paris', 'acme', 'IT', '*****@*****.**', ['www.acmephp.com']); $dummyKeyPair = (new KeyPairGenerator())->generateKeyPair(1024); $result = $this->service->signCertificateRequest(new CertificateRequest($dummyDistinguishedName, $dummyKeyPair)); $this->assertInternalType('string', $result); $this->assertContains('-----BEGIN CERTIFICATE REQUEST-----', $result); $csrResult = openssl_csr_get_subject($result, false); $this->assertSame(['commonName' => 'acmephp.com', 'countryName' => 'FR', 'stateOrProvinceName' => 'france', 'localityName' => 'Paris', 'organizationName' => 'acme', 'organizationalUnitName' => 'IT', 'emailAddress' => '*****@*****.**'], $csrResult); }
/** * Process requests to generate a client certificate from a CSR. * @return void */ function getPageCsrSign() { global $_WA; $_WA->html->setPageTitle('Generate Certificate from CSR'); $conf = isset($_POST[WA_QS_CONFIRM]) ? $_POST[WA_QS_CONFIRM] : false; $csr = isset($_POST['csr']) ? $_POST['csr'] : false; // // Have they provided a valid csr yet? // if (!is_string($csr) or strlen($csr) < 1) { die($_WA->html->loadTemplate('get.csr.php')); } // // Validate the csr // $info = openssl_csr_get_subject($csr, false); if (!is_array($info) or !isset($info['commonName'])) { $_WA->html->errorMsgSet('Could not decode the CSR'); die($_WA->html->loadTemplate('get.csr.php')); } // // Fields required for the next phase... // $caId = isset($_POST['caId']) ? $_POST['caId'] : false; $days = isset($_POST['Days']) ? $_POST['Days'] : false; $test1 = (is_numeric($caId) and $caId > 0); $test2 = (is_numeric($days) and $days > 0); if (!$test1 or !$test2) { die($_WA->html->loadTemplate('client.sign.php')); } $rc = $_WA->actionClientCsrSign(); if (!($rc === true)) { $_WA->html->errorMsgSet($rc); die($_WA->html->loadTemplate('client.sign.php')); } // Success ;) $_WA->html->setPageTitle('Sign Certificate Results'); $qs = $_WA->html->getMenuQs(MENU_CERTS_CLIENT); $_WA->html->addMenuLink($qs, 'Return', 'greenoutline'); $h = array(); $h[] = $_WA->html->getPageHeader(); $h[] = 'Congratulations, the certificate has been signed and imported ' . 'successfully.'; $h[] = $_WA->html->getPageFooter(); die(implode("\n", $h) . "\n"); }
/** * @see CryptoElement::getSubject() */ public function getSubject() { $sa = openssl_csr_get_subject($this->content); $res = false; if (is_null($sa) || !is_array($sa) || $sa == "") { return false; } foreach ($sa as $key => $value) { if (is_array($value)) { foreach ($value as $subvalue) { $res .= "/{$key}={$subvalue}"; } } else { $res .= "/{$key}={$value}"; } } return $res; }
function opensrs_ssl_sslstepthree($params) { $_LANG = opensrs_ssl_loadLanguage(); //Prepare CSR if (isset($params['configdata']['csr'])) { $csr = trim($params['configdata']['csr']); } else { $csr = trim($params['csr']); } $csr = trim($params['configdata']['csr']); $csr = trim(preg_replace('/(.*)CERTIFICATE(.*)/', '', $csr)); $csr = "-----BEGIN CERTIFICATE REQUEST-----\n" . $csr . "\n-----END CERTIFICATE REQUEST-----"; $csr = trim($csr); //Domain $subject = openssl_csr_get_subject($csr); $domain = $subject['CN']; //Period $period = $params['configoptions']['Period'] ? $params['configoptions']['Period'] : $params['configoption5']; //Search in seal $seal_in_search = $params['customfields']['Search in seal'] ? $params['customfields']['Search in seal'] : $params['configoption6']; //Server Count $server_count = $params['customfields']['Server Count'] ? $params['customfields']['Server Count'] : $params['configoption7']; //Cert Type $product_type = opensrs_ssl_getCertType($params['configoption4']); $openSRS = new OpenSRS($params['configoption1'], 0, $params['configoption2'], $params['configoption3'] == 'on' ? 0 : 1); $types = opensrs_ssl_getRequiredContacts($product_type); $fields = array(); $contact_types = array('admin', 'billing', 'tech', 'organization', 'signer'); $send = array(); $q = mysql_safequery("SELECT remoteid FROM tblsslorders WHERE serviceid = ?", array($params['serviceid'])); $row = mysql_fetch_assoc($q); $send = array('action' => 'sw_register', 'object' => 'trust_service', 'attributes' => array('approver_email' => $params['approveremail'] ? $params['approveremail'] : $params['clientsdetails']['email'], 'product_type' => $product_type, 'contact_set' => array(), 'csr' => $csr, 'domain' => $domain, 'handle' => 'process', 'period' => $period, 'reg_type' => 'new', 'server_count' => $server_count, 'server_type' => opensrs_ssl_getServerType($params['configdata']['servertype'], $product_type))); $contact = array(); $details = $params['configdata']['fields']; foreach ($contact_types as $type) { $t = ucfirst($type); if (in_array($type, $types)) { $contact[$type]['first_name'] = $details[$t . 'FirstName']; $contact[$type]['last_name'] = $details[$t . 'LastName']; $contact[$type]['title'] = $details[$t . 'Title']; $contact[$type]['org_name'] = $details[$t . 'Name']; $contact[$type]['address1'] = $details[$t . 'Address1']; $contact[$type]['address2'] = $details[$t . 'Address2']; $contact[$type]['address3'] = $details[$t . 'Address3']; $contact[$type]['city'] = $details[$t . 'City']; $contact[$type]['state'] = $details[$t . 'State']; $contact[$type]['postal_code'] = $details[$t . 'PostalCode']; $contact[$type]['state'] = $details[$t . 'State']; $contact[$type]['country'] = $details[$t . 'Country']; $contact[$type]['email'] = $details[$t . 'Email']; $contact[$type]['phone'] = $details[$t . 'Phone']; $contact[$type]['fax'] = $details[$t . 'Fax']; } } $send['attributes']['contact_set'] = $contact; if ($seal_in_search) { $send['attributes']['seal_in_search'] = '1'; $send['attributes']['trust_seal'] = '1'; } $res = $openSRS->send($send); if (!$openSRS->isSuccess()) { return array('error' => opensrs_ssl_translate($openSRS->getError())); } $order_id = $res['attributes']['order_id']; mysql_safequery("UPDATE tblsslorders SET remoteid = ? WHERE serviceid = ?", array($order_id, $params['serviceid'])); mysql_safequery("UPDATE tblhosting SET domain = ? WHERE id = ?", array($domain, $params['serviceid'])); }
function csr_parse_json($csr) { //if csr or cert is pasted in form tis function parses the csr or it send the cert to cert_parse. global $random_blurp; global $timeout; $result = array(); if (strpos($csr, "BEGIN CERTIFICATE REQUEST") !== false) { $cert_data = openssl_csr_get_public_key($csr); $cert_details = openssl_pkey_get_details($cert_data); $cert_key = $cert_details['key']; $cert_subject = openssl_csr_get_subject($csr); $result["subject"] = $cert_subject; $result["key"] = $cert_key; $result["details"] = $cert_details; if ($cert_details) { $result["csr_pem"] = $csr; $sans = get_sans_from_csr($csr); if (count($sans) > 1) { $result["csr_sans"] = $sans; } } } elseif (strpos($csr, "BEGIN CERTIFICATE") !== false) { $result = cert_parse_json($csr, null, null, null, null, true); } else { $result = array("error" => "data not valid csr"); } return $result; }
function get_csr_details($person, $auth_key) { $csr = get_csr_from_db_raw($person->getX509ValidCN(), $auth_key); $subj = openssl_csr_get_subject($csr['csr'], false); $result = array('auth_token' => $csr['auth_key'], 'length' => csr_pubkey_length($csr['csr']), 'uploaded' => $csr['uploaded_date'], 'from_ip' => Output::formatIP($csr['from_ip'], true)); foreach ($subj as $key => $value) { $result[$key] = $value; } return $result; }
/** * verifyCSR() * * This function will test the CSR against several fields. * It will test the subject against the person-attributes (which in turn are * gathered from simplesamlphp-attributes (Feide, surfnet etc). * * @param String The CSR in base64 PEM format * @return Boolean True if valid CSR */ private function verifyCSR($csr) { /* by default, the CSR is valid, we then try to prove that it's invalid * * A better approach could be to distrust all CSRs and try to prove that * they are OK, however this leads to messy code (as the tests becomes * somewhat more involved) and I'm not convinced that it will be any safer. */ if (!isset($csr)) { Framework::error_output(__FILE__ . ":" . __LINE__ . " CSR not provided by caller1"); return false; } $subject = openssl_csr_get_subject($csr); /* check fields of CSR to predefined values and user-specific values * Make sure that the emailAddress is not set, as this is * non-compatible with ARC. */ if (isset($subject['emailAddress'])) { Framework::error_output("will not accept email in DN of certificate. Download latest version of script."); return false; } else { if (!match_dn($subject, $this->getFullDN())) { $msg = ""; $msg .= "Error in subject! <BR/>\n"; $msg .= "The fields in your CSR was not set properly.<BR>\n"; $msg .= "To try again, please download a new version of the script, "; $msg .= "generate a new key and upload again.<BR>\n"; Framework::error_output($msg); return false; } } return true; }
<?php /** * @package phpmyca * @author Mike Green <*****@*****.**> * @copyright Copyright (c) 2010, Mike Green * @license http://opensource.org/licenses/gpl-2.0.php GPLv2 */ basename($_SERVER['PHP_SELF']) == basename(__FILE__) && die('Access Denied'); // breadcrumb $qs_back = $this->getMenuQs(MENU_CERTS_SERVER); // generate some displayable information from provided csr $csr = isset($_POST['csr']) ? $_POST['csr'] : false; $dnconfig = false; if (is_string($csr)) { $dnconfig = openssl_csr_get_subject($csr, false); } // footer links $this->addMenuLink($qs_back, 'Cancel', 'redoutline'); $this->addMenuLink('javascript:document.signcert.submit();', 'Generate Certificate', 'greenoutline'); echo $this->getPageHeader(); echo $this->getFormHeader('signcert'); echo $this->getFormBreadCrumb(); ?> <INPUT TYPE="hidden" NAME="<?php echo WA_QS_CONFIRM; ?> " VALUE="yes"> <?php $val = isset($_POST['csr']) ? $_POST['csr'] : ''; ?>
/** * Sign a server cert from user provided csr * Post variable possibilities: caId, caPassPhrase, Days, PassPhrase. * @param string $csr (required) * @return void */ public function actionServerCsrSign() { $this->moduleRequired('ca'); // Normalize/validate variables $caId = isset($_POST['caId']) ? $_POST['caId'] : false; $caPassPhrase = isset($_POST['caPassPhrase']) ? stripslashes(trim($_POST['caPassPhrase'])) : false; $CommonName = isset($_POST['CommonName']) ? stripslashes(trim($_POST['CommonName'])) : false; $csr = isset($_POST['csr']) ? $_POST['csr'] : false; $Days = isset($_POST['Days']) ? $_POST['Days'] : false; if (!is_string($caPassPhrase) or strlen($caPassPhrase) < 1) { $caPassPhrase = null; } // Validate required if (!is_numeric($caId) or $caId < 1) { return 'Must specify valid Certificate Authority.'; } if (!is_string($csr) or strlen($csr) < 1) { return 'Must provide PEM encoded CSR.'; } $dnargs = openssl_csr_get_subject($csr, false); if (!is_array($dnargs) or !isset($dnargs['commonName'])) { return 'Invalid or no CSR specified.'; } if (!is_numeric($Days) or $Days < 1) { return 'Must specify valid number of days.'; } $cfgargs = array(); $cfgargs['config'] = OPENSSL_CONF; $cfgargs['x509_extensions'] = 'v3_server'; // // Sign with the specified CA // $this->ca->resetProperties(); $ca = $this->ca->queryById($caId); if (!is_array($ca)) { return 'Failed to locate the specified CA.'; } if (!isset($ca['PrivateKey']) or !is_string($ca['PrivateKey'])) { return 'Cannot issue certs from 3rd party CAs.'; } if (!isset($ca['ValidTo']) or !is_string($ca['ValidTo'])) { return 'Cannot determine if CA cert is still valid.'; } if ($ca['ValidTo'] < date('Y-m-d H:i:s')) { return 'CA is expired.'; } if (!isset($ca['SerialLastIssued']) or !is_numeric($ca['SerialLastIssued'])) { return 'Cannot determine last serial number issued by CA.'; } $caCertPem = $ca['Certificate']; $caPrivateKeyPem = $ca['PrivateKey']; $caLastSerial = $ca['SerialLastIssued']; $SerialNumber = $caLastSerial + 1; $pKey = array($caPrivateKeyPem, $caPassPhrase); $signedCsr = openssl_csr_sign($csr, $caCertPem, $pKey, $Days, $cfgargs, $SerialNumber); if ($signedCsr === false) { // ignore 0E06D06C $errors = openssl_error_string(); $junk = explode(':', $errors); if ($junk[1] !== '0E06D06C') { return 'Failed to sign the cert request: ' . $errors; } } // Export the cert $rc = openssl_x509_export($signedCsr, $certPem); if ($rc === false) { $errors = openssl_error_string(); return 'Failed to export the x509 certificate: ' . $errors; } // Call upon actionServerImport to import it into the database $rc = $this->actionServerImport($certPem, null, null, $csr); if (!($rc === true)) { return 'Failed to import the server cert: ' . $rc; } return true; }
<?php $csr = file_get_contents(dirname(__FILE__) . '/005_crt.txt'); if ($out = openssl_csr_get_subject($csr, 1)) { var_dump($out); } echo "\n"; $cn = utf8_decode($out['CN']); var_dump($cn);
/** * Get the CSR subject * * @return string CSR content on success, false on failure */ private function getCsrSubject() { if (!$this->csr_content) { return false; } $this->csr_subject = openssl_csr_get_subject($this->csr_content); if (!$this->csr_subject) { return false; } $i = 0; $this->csr_others = array(); foreach ($this->csr_subject as $key => $value) { switch (strtolower($key)) { case 'c': $this->csr_c = $value; break; case 'st': if (is_array($value)) { $this->csr_st = $value; } else { $this->csr_st[0] = $value; } break; case 'street': case 's': if (is_array($value)) { $this->csr_s = $value; } else { $this->csr_s[0] = $value; } break; case 'l': $this->csr_l = $value; break; case 'o': $this->csr_o = $value; break; case 'ou': if (is_array($value)) { $this->csr_ou = $value; } else { $this->csr_ou[0] = $value; } break; case 'cn': $this->csr_cn = $value; break; case 'emailaddress': case 'mail': $this->csr_email = $value; break; default: if (is_array($value)) { foreach ($value as $val) { if (strtolower($key) == 'undef') { $this->csr_others[$i]['title'] = $this->app->getText('APP_REQUEST_SUBJECT_OTHER'); } else { $this->csr_others[$i]['title'] = $key; } $this->csr_others[$i]['value'] = $val; $i++; } } else { if (strtolower($key) == 'undef') { $this->csr_others[$i]['title'] = $this->app->getText('APP_REQUEST_SUBJECT_OTHER'); } else { $this->csr_others[$i]['title'] = $key; } $this->csr_others[$i]['value'] = $value; } $i++; break; } } return true; }
/** * @param bool $longNames * * @return array */ public function getSubject1(bool $longNames = false) : array { return openssl_csr_get_subject($this->getHandle(), $longNames); }
function csr_parse_json($csr) { $result = array(); if (strpos($csr, "BEGIN CERTIFICATE REQUEST") !== false) { $cert_data = openssl_csr_get_public_key($csr); $cert_details = openssl_pkey_get_details($cert_data); $cert_key = $cert_details['key']; $cert_subject = openssl_csr_get_subject($csr); $result["subject"] = $cert_subject; $result["key"] = $cert_key; $result["details"] = $cert_details; } elseif (strpos($csr, "BEGIN CERTIFICATE") !== false) { $result = cert_parse_json($csr); } else { $result = array("error" => "data not valid csr"); } return $result; }
echo json_encode(array("ko" => "ko", "message" => "alreadyExists")); exit; } $personBo->save($person); $account["acc_person_id"] = $person["per_id"]; $password = $account["acc_password"]; $account["acc_password"] = AccountBo::computePassword($account["acc_password"]); $accountBo->save($account); $accountBo->login($account["acc_login"], $password, $_SESSION); } } // Private key and CSR part if (isset($_REQUEST["hasPrivateKey"]) && $_REQUEST["hasPrivateKey"] != "0") { $privateKeyContent = null; $csrContent = $_REQUEST["csrInput"]; $subject = openssl_csr_get_subject($csrContent); $cn = $subject["CN"]; } else { // We create the private key and the CSR $serial = $vpnBo->getSerial(); $openSslConfig = array("digest_alg" => "sha512", "private_key_bits" => 4096, "private_key_type" => OPENSSL_KEYTYPE_RSA); // Create the private and public key $res = openssl_pkey_new($openSslConfig); $cn = $person["per_firstname"] . " " . $person["per_lastname"] . " - " . $serial; $dn = array("countryName" => "FR", "stateOrProvinceName" => "France", "organizationName" => "Armagnet", "commonName" => $cn, "emailAddress" => $person["per_mail"]); // Create the Certificate Signature Request $csr = openssl_csr_new($dn, $res); openssl_csr_export($csr, $csrContent); $keyPath = "key_" . time(); $defaultPassword = "******"; // Extract the private key from $res to $privKey
/** * Extracs a DistinguishedName from a CSR * @param CertificateSigningRequest $CSR * @param boolean $ShortNames to return short names as array keys * @return DistinguishedName */ function CSR_DistinguishedName($CSR, $ShortNames = true) { return openssl_csr_get_subject($CSR, $ShortNames); }
<?php function stringAsHex($string) { $unpacked = unpack("H*", $string); return implode(" ", str_split($unpacked[1], 2)); } $config = array("digest_alg" => "sha1", "x509_extensions" => "v3_ca", "req_extensions" => "v3_req", "private_key_bits" => 2048, "private_key_type" => OPENSSL_KEYTYPE_RSA, "encrypt_key" => false); $csr_info = array("countryName" => "US", "stateOrProvinceName" => "Utah", "localityName" => "Lindon", "organizationName" => "Chinese", "organizationalUnitName" => "IT 互", "commonName" => "www.example.com"); $private = openssl_pkey_new($config); while (openssl_error_string()) { } $csr_res = openssl_csr_new($csr_info, $private, ['config' => __DIR__ . "/openssl.cnf"]); if (!$csr_res) { while ($e = openssl_error_string()) { $err = $e; } die("Failed; last error: {$err}"); } openssl_csr_export($csr_res, $csr); $output = openssl_csr_get_subject($csr); echo "A: " . $csr_info["organizationalUnitName"] . "\n"; echo "B: " . stringAsHex($csr_info["organizationalUnitName"]) . "\n"; echo "C: " . $output['OU'] . "\n"; echo "D: " . stringAsHex($output['OU']) . "\n";