Exemplo n.º 1
0
 public function exportCertificatePkcs12($file)
 {
     \debug("OpenSSL CSR: Exporting certificate as PKCS12: {$file}");
     $pkcs = null;
     openssl_pkcs12_export($this->signed, $pkcs, $this->pkey, $this->pkeypass, ["friendly_names" => true]);
     file_put_contents($file, $pkcs);
 }
 public static function createSerializedFairPlayOptionConfiguration($cert, $pkey, $pfxPassword, $pfxPasswordKeyId, $askId, $contentIv)
 {
     openssl_pkcs12_export($cert, $certBytes, $pkey, $pfxPassword);
     $certString = base64_encode($certBytes);
     $template = new FairPlayConfiguration();
     $template->ASkId = $askId;
     $template->ContentEncryptionIV = $contentIv;
     $template->FairPlayPfx = $certString;
     $template->FairPlayPfxPasswordId = $pfxPasswordKeyId;
     return json_encode($template);
 }
 /**
  * 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;
     }
 }
Exemplo n.º 4
0
     }
     exit;
 } elseif ($act == "p12") {
     // export cert+key in p12 format
     if (isset($id)) {
         $exp_name = urlencode("{$a_cert[$id]['descr']}.p12");
         $args = array();
         $args['friendly_name'] = $a_cert[$id]['descr'];
         $ca = lookup_ca($a_cert[$id]['caref']);
         if ($ca) {
             $args['extracerts'] = openssl_x509_read(base64_decode($ca['crt']));
         }
         $res_crt = openssl_x509_read(base64_decode($a_cert[$id]['crt']));
         $res_key = openssl_pkey_get_private(array(0 => base64_decode($a_cert[$id]['prv']), 1 => ""));
         $exp_data = "";
         openssl_pkcs12_export($res_crt, $exp_data, $res_key, null, $args);
         $exp_size = strlen($exp_data);
         header("Content-Type: application/octet-stream");
         header("Content-Disposition: attachment; filename={$exp_name}");
         header("Content-Length: {$exp_size}");
         echo $exp_data;
     }
     exit;
 } elseif ($act == "csr") {
     if (!isset($id)) {
         header("Location: system_certmanager.php");
         exit;
     }
     $pconfig['descr'] = $a_cert[$id]['descr'];
     $pconfig['csr'] = base64_decode($a_cert[$id]['csr']);
     $pconfig['cert'] = null;
Exemplo n.º 5
0
function test_openssl_pkcs12_read()
{
    $privkey = openssl_pkey_new();
    VERIFY($privkey != null);
    $csr = openssl_csr_new(null, $privkey);
    VERIFY($csr != null);
    $scert = openssl_csr_sign($csr, null, $privkey, 365);
    openssl_pkcs12_export($scert, $pkcs12, $privkey, "1234");
    VERIFY(openssl_pkcs12_read($pkcs12, $certs, "1234"));
    VERIFY(strlen($certs['cert']) > 500);
    VERIFY(strlen($certs['pkey']) > 500);
}
Exemplo n.º 6
0
 /**
  * Process requests to obtain pkcs12 file.
  * @return void
  */
 function getPageServerPkcs12()
 {
     $this->html->setPageTitle('Get PKCS12 Certificate');
     $id = $this->html->crumbGet(WA_QS_ID);
     if (!is_numeric($id) or $id < 1) {
         $this->html->errorMsgSet('Must specify valid certificate id.');
         die($this->html->loadTemplate('client.view.php'));
     }
     $this->moduleRequired('server,ca');
     $this->server->resetProperties();
     if ($this->server->populateFromDb($id) === false) {
         $this->html->errorMsgSet('Failed to locate the specified certificate.');
         die($this->html->loadTemplate('server.view.php'));
     }
     $this->html->setVar('data', &$this->server);
     // Have they been given the chance to enter the private key password?
     $conf = isset($_POST[WA_QS_CONFIRM]) ? $_POST[WA_QS_CONFIRM] : false;
     $keyPass = isset($_POST['keyPass']) ? $_POST['keyPass'] : null;
     $expPass = isset($_POST['expPass']) ? $_POST['expPass'] : false;
     if ($conf !== 'yes' or $expPass === false) {
         die($this->html->loadTemplate('server.pkcs12.php'));
     }
     // Get down to bidness
     $cert = $this->server->getProperty('Certificate');
     $pk = $this->server->getProperty('PrivateKey');
     // Get and decrypt the private key...
     $pkey = openssl_pkey_get_private($pk, $keyPass);
     if ($pkey === false) {
         $this->html->errorMsgSet('Invalid pass phrase for private key.');
         die($this->html->loadTemplate('server.pkcs12.php'));
     }
     // Extra args - name of certificate for import and chain CA certificates
     $certs = array();
     $serverName = $this->server->getProperty('CommonName');
     $certName = 'Server Certificate - ' . $serverName;
     // Obtain chain of issuer certificate ids.
     $issuerIds = $this->ca->getCaChainIds($this->server->getProperty('ParentId'));
     if (is_array($issuerIds) and count($issuerIds) > 0) {
         foreach ($issuerIds as $id) {
             $pem = $this->ca->getPemCertById($id);
             if (is_string($pem)) {
                 $certs[] = trim($pem);
             }
         }
     }
     if (is_array($certs) and count($certs) > 0) {
         $certs = implode("\n", $certs);
     } else {
         $certs = '';
     }
     $extraArgs = array('extracerts' => $certs, 'friendly_name' => $certName);
     $rc = openssl_pkcs12_export($cert, $pkcs12, $pkey, $expPass, $extraArgs);
     if (!($rc === true)) {
         $this->html->errorMsgSet('Failed to export PKCS12 Certficate Store.');
         die($this->html->loadTemplate('server.pkcs12.php'));
     }
     header('Pragma: private');
     header('Expires: 0');
     header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
     header('Cache-Control: private');
     header('Content-Description: File Transfer');
     header('Content-Type: application/x-pkcs12');
     header('Content-Disposition: attachment; filename="' . $serverName . '.p12"');
     header('Content-Transfer-Encoding: binary');
     header('Content-Length: ' . strlen($pkcs12));
     die($pkcs12);
 }
Exemplo n.º 7
0
 /**
  * 生成证书
  */
 private function process()
 {
     $privkey = openssl_pkey_new($this->config);
     $csr = openssl_csr_new($this->dn, $privkey);
     $sscert = openssl_csr_sign($csr, NULL, $privkey, $this->iNumberOfDays);
     openssl_x509_export($sscert, $csrkey);
     openssl_pkcs12_export($sscert, $privatekey, $privkey, $this->sPrivKeyPass);
     //生成公钥证书
     $fp = fopen($this->sCerPath, "w");
     fwrite($fp, $csrkey);
     fclose($fp);
     //生成密钥证书
     $fp = fopen($this->sPfxPath, "w");
     fwrite($fp, $privatekey);
     fclose($fp);
 }
Exemplo n.º 8
0
    function generateCertificate($sip_address,$email,$password) {
        if (!$this->init) return false;

        if (!is_array($this->enrollment)) {
            print _("Error: missing enrollment settings");
            return false;
        }

        if (!$this->enrollment['ca_conf']) {
            //print _("Error: missing enrollment ca_conf settings");
            return false;
        }

        if (!$this->enrollment['ca_crt']) {
            //print _("Error: missing enrollment ca_crt settings");
            return false;
        }

        if (!$this->enrollment['ca_key']) {
            //print _("Error: missing enrollment ca_key settings");
            return false;
        }

    	$config = array(
    		'config'           => $this->enrollment['ca_conf'],
    		'digest_alg'       => 'md5',
    		'private_key_bits' => 1024,
    		'private_key_type' => OPENSSL_KEYTYPE_RSA,
    		'encrypt_key'      => false,
    	);

		$dn = array(
    		"countryName"            => $this->enrollment['countryName'],
	    	"stateOrProvinceName"    => $this->enrollment['stateOrProvinceName'],
    		"localityName"           => $this->enrollment['localityName'],
    		"organizationName"       => $this->enrollment['organizationName'],
    		"organizationalUnitName" => $this->enrollment['organizationalUnitName'],
    		"commonName"             => $sip_address,
    		"emailAddress"           => $email
		);

		$this->key = openssl_pkey_new($config);
		$this->csr = openssl_csr_new($dn, $this->key);

        openssl_csr_export($this->csr, $this->csr_out);
        openssl_pkey_export($this->key, $this->key_out, $password, $config);

		$ca="file://".$this->enrollment['ca_crt'];

        $this->crt = openssl_csr_sign($this->csr, $ca, $this->enrollment['ca_key'], 3650, $config);

		if ($this->crt==FALSE) {
			while (($e = openssl_error_string()) !== false) {
				echo $e . "\n";
				print "<br><br>";
			}
            return false;
		}

        openssl_x509_export   ($this->crt, $this->crt_out);
        openssl_pkcs12_export ($this->crt, $this->pk12_out, $this->key, $password);

        return array(
                     'crt'  => $this->crt_out,
                     'key'  => $this->key_out,
                     'pk12' => $this->pk12_out,
                     'ca'   => file_get_contents($this->enrollment['ca_crt'])
                     );
    }
Exemplo n.º 9
0
 public function getPKCS12SelfSigned($countryName, $stateOrProvinceName, $localityName, $organizationName, $organizationalUnitName, $commonName, $emailAddress)
 {
     $dn = array("countryName" => $countryName, "stateOrProvinceName" => $stateOrProvinceName, "localityName" => $localityName, "organizationName" => $organizationName, "organizationalUnitName" => $organizationalUnitName, "commonName" => $commonName, "emailAddress" => $emailAddress, "extendedKeyUsage" => "clientAuth", "authorityInfoAccess" => "URI:http://" . getenv('HTTP_HOST') . "/");
     $privkey = openssl_pkey_new($this->config);
     $csr = openssl_csr_new($dn, $privkey, $this->config);
     $sscert = openssl_csr_sign($csr, null, $privkey, $this->csr_days_valid, $this->config);
     // Self signed
     openssl_x509_export($sscert, $this->publickey);
     openssl_pkcs12_export($this->publickey, $pks12, $privkey, null);
     return $pks12;
 }
Exemplo n.º 10
0
 public function createpkcs12($c, $k, $p, $a = array('friendly_name' => '', 'extracerts' => ''), $f = false, $d = false)
 {
     $key = openssl_pkey_get_private($k, $p);
     $f === false ? openssl_pkcs12_export($c, $r, $key, $p, $a) : openssl_pkcs12_export_to_file($c, $r, $key, $p, $a);
     return $r;
 }
Exemplo n.º 11
0
// 利用 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);
$csr = openssl_csr_new($dn, $privkey);
$sscert = openssl_csr_sign($csr, null, $privkey, 365);
openssl_csr_export($csr, $csrout) and _var($csrout);
openssl_x509_export($sscert, $cer_x509) and _var($cer_x509);
openssl_pkey_export($privkey, $pkeyout, "mypassword", $config) and _var($pkeyout);
openssl_pkcs12_export($cer_x509, $pkcs12, $privkey, 'mypassword', $config) && _var(base64_encode($pkcs12));
openssl_pkcs12_read($pkcs12, $cert, 'mypassword') && _var($cert);
//_var(getenv('OPENSSL_CONF'));
// Show any errors that occurred here
//while (($e = openssl_error_string()) !== false) {
//    echo $e . "\n";
//}
//exit;
$cleartext = '1234 5678 9012 3456';
echo "\nClear txt: \n{$cleartext}\n";
$pub_key = $cert['cert'];
$priv_key = $cert['pkey'];
openssl_public_encrypt($cleartext, $crypttext, $pub_key);
echo "\nCrypt text:\n" . base64_encode($crypttext) . "\n";
openssl_private_decrypt($crypttext, $decrypted, $priv_key);
echo "\nDecrypted text:\n{$decrypted}\n\n";
Exemplo n.º 12
0
// ********** 签署证书 **********
//$cert = openssl_csr_sign($csr, null, $priv, 365); // right
//$cert = openssl_csr_sign($csrout, null, $priv, 365); // right
// CA 签证书
//$cert = openssl_csr_sign($csr, $ca_certout, $ca_pfx, 365); // wrong
//$cert = openssl_csr_sign($csr, $ca_pubout, $ca_privout, 365); // wrong
$cert = openssl_csr_sign($csr, $ca_certout, $ca_privout, 365);
// right
// ********* 导出证书 ***********
openssl_csr_export($csr, $csrout) and var_dump('CSR', $csrout);
openssl_x509_export($cert, $certout) and var_dump('Certificate', $certout);
openssl_pkey_export($priv, $pkeyout, $password, $config) and var_dump('Private', $pkeyout);
$pkey = openssl_pkey_get_private($pkeyout, $password);
// $pkey 参数可以是没有密码导出的密钥
// 或者是 OpenSSL key 资源
openssl_pkcs12_export($certout, $pfx, $pkey, $password);
openssl_pkcs12_read($pfx, $certs, $password) && var_dump($certs);
$cleartext = '1234 5678 9012 3456';
echo "Clear txt: \n{$cleartext}\n";
// ************ 公私钥 ***************
$pub_key = $certout;
// right
//$pub_key = $cert; // right
//$pub_key = openssl_pkey_get_public($certout); // right OpenSSL key
//$pub_key = openssl_pkey_get_public($cert); // right OpenSSL key
//$pub_key = openssl_pkey_get_details($priv)['key']; // right public key
//$pub_key = $csrout; // wrong
$priv_key = openssl_pkey_get_private($pkeyout, $password);
// right OpenSSL key
//$priv_key = $pkeyout; // wrong private key
//$priv_key = $pfx; // wrong pcks12 cert
Exemplo n.º 13
0
 /**
  * Exports the data to be stored in a .p12 file (encrypted certificate and private key)
  * @param X509 $X509
  * @param PrivateKey $PrivateKey or PEM
  * @param String $Password to encrypt the whole file
  * @return String
  */
 function PKCS12_Export($X509, $PrivateKey, $Password = "")
 {
     $out = '';
     openssl_pkcs12_export($X509, $out, $PrivateKey, $Password);
     return $out;
 }
Exemplo n.º 14
0
/**
 * Create a new client certificate for a username or client hostname.
 * @param $commonName   - The username or hostname
 * @param $emailAddress - The user's email address
 * @param $serial       - The serial number
 * @param $cacert       - Path to Certificate Authority cert file.
 * @param $cakey        - Path to Certificate Authority key file.
 * @param $valid_days   - validity in number of days for the user certificate
 * @return string       - The client certificate signed by the Certificate Authority, or false on error.
 */
function create_user_certificate($commonName, $emailAddress, $serial, $cacert, $cakey, $valid_days)
{
    $opensslConf = $GLOBALS['webserver_root'] . "/library/openssl.cnf";
    $config = array('config' => $opensslConf);
    /* Generate a certificate signing request */
    $arr = create_csr($commonName, $emailAddress, "", "", "", "", "");
    if ($arr === false) {
        return false;
    }
    $csr = $arr[0];
    $privkey = $arr[1];
    /* user id is used as serial number to sign a certificate */
    $serial = 0;
    $res = sqlStatement("select id from users where username='******'");
    if ($row = sqlFetchArray($res)) {
        $serial = $row['id'];
    }
    $cert = openssl_csr_sign($csr, file_get_contents($cacert), file_get_contents($cakey), $valid_days, $config, $serial);
    if ($cert === false) {
        return false;
    }
    /* Convert the user certificate to .p12 (PKCS 12) format, which is the
     * standard format used by browsers.
     */
    if (openssl_pkcs12_export($cert, $p12Out, $privkey, "") === false) {
        return false;
    }
    return $p12Out;
}
Exemplo n.º 15
0
 /**
  * @param string $password
  * @return string
  * @throws RuntimeException
  */
 public function export($password = NULL)
 {
     $options = [];
     if ($this->hasChain()) {
         $options['extracerts'] = $this->getChain();
     }
     $status = openssl_pkcs12_export($this->getCertificate(), $result, $this->getPrivateKey(), $password, $options);
     if (!$status) {
         throw new RuntimeException(OpenSSL::getLastError());
     }
     return $result;
 }
Exemplo n.º 16
0
if (!is_writable($zippath)) {
    die("ERROR: temp directory read only {$zippath}");
}
if (isset($_POST['element_1'])) {
    $p12k = "";
    $cert = $_POST['element_1'];
    $key = $_POST['element_2'];
    $pass = $_POST['element_3'];
    if (FALSE == ($pkey = openssl_pkey_get_private($key))) {
        die('failed to open key\\n $key');
    }
    if (FALSE == ($x509 = openssl_x509_read($cert))) {
        die('failed to open cert\\n $cert');
    }
    $cert_info = print_r(openssl_x509_parse($x509), TRUE);
    if (FALSE == openssl_pkcs12_export($x509, $p12k, $pkey, $pass)) {
        while (($e = openssl_error_string()) !== false) {
            echo $e . "\n";
        }
        die("\nfailed to make p12, probably you supplied cert from another key?\n {$cert_info}");
    }
    $zip = new ZipArchive();
    $filename = "{$zippath}/p12_" . time() . ".zip";
    if ($zip->open($filename, ZIPARCHIVE::CREATE) !== TRUE) {
        die("cant open <{$filename}>\n");
    }
    $zip->addFromString("certinfo.txt", "{$cert_info}\n");
    $zip->addFromString("password.txt", "{$pass}\n");
    $zip->addFromString("cert.pem", "{$cert}\n");
    $zip->addFromString("key.pem", "{$key}\n");
    $zip->addFromString("cert.p12", "{$p12k}\n");