2011-12-01 64 views
3

如何在PHP中創建數字證書並導出爲.p12文件?如何在PHP中創建數字證書並導出到.p12文件?

我希望.p12文件包含私鑰。還想檢查密鑰對是否已經發出(登錄數據庫)。

我發現一個名爲'openssl_pkcs12_export_to_file'的函數,但不知道從哪裏開始。似乎首先需要X509證書和私鑰。

回答

3
<?php 
error_reporting(-1); 

function dump($Var) { 
    echo "<hr/><pre>"; 
    var_dump($Var); 
    echo "</pre><hr/>"; 
} 

function check_errors() { 
    echo "<hr/><pre>"; 
    $Count = 0; 
    while (($e=openssl_error_string())!==false) { 
    echo $e."<br>"; 
    $Count++; 
    } 
    if ($Count==0) 
    echo "No error"; 
    echo "</pre><hr/>"; 
} 

$Configs = array(
    "config" => "e:/progetti/php/openssl/openssl.cfg", 
    "digest_alg" => "sha1", 
    "x509_extensions" => "v3_ca", 
    "req_extensions" => "v3_req", 
    "private_key_bits" => 1024, 
    "private_key_type" => OPENSSL_KEYTYPE_RSA, 
    "encrypt_key" => true, 
    "encrypt_key_cipher" => OPENSSL_CIPHER_3DES 
); 
$Info = array(
    "countryName" => "VN", 
    "stateOrProvinceName" => "Hanoi", 
    "localityName" => "Long Bien", 
    "organizationName" => "Test Company", 
    "organizationalUnitName" => "Test Department", 
    "commonName" => "Tester", 
    "emailAddress" => "[email protected]" 
); 

$Private_Key = null; 
$Unsigned_Cert = openssl_csr_new($Info,$Private_Key,$Configs); 
check_errors(); 
dump($Private_Key); 
dump($Unsigned_Cert); 

$Signed_Cert = openssl_csr_sign($Unsigned_Cert,null,$Private_Key,365,$Configs); 
check_errors(); 
dump($Signed_Cert); 

openssl_pkcs12_export_to_file($Signed_Cert,"test.p12",$Private_Key,"123456"); 
check_errors(); 
3

創建自簽名證書:

<?php 
$dn = array(
    "countryName" => "UK", 
    "stateOrProvinceName" => "Somerset", 
    "localityName" => "Glastonbury", 
    "organizationName" => "The Brain Room Limited", 
    "organizationalUnitName" => "PHP Documentation Team", 
    "commonName" => "Wez Furlong", 
    "emailAddress" => "[email protected]" 
); 

$privkey = openssl_pkey_new(); 
$csr = openssl_csr_new($dn, $privkey); 
$sscert = openssl_csr_sign($csr, null, $privkey, 365); 

openssl_csr_export($csr, $csrout) and var_dump($csrout); 
openssl_x509_export($sscert, $certout) and var_dump($certout); 
openssl_pkey_export($privkey, $pkeyout, "mypassword") and var_dump($pkeyout); 

// Show any errors that occurred here 
while (($e = openssl_error_string()) !== false) { 
    echo $e . "\n"; 
} 
?> 
相關問題