Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
741 views
in Technique[技术] by (71.8m points)

openssl - How to create a digital certificate and export to .p12 file in PHP?

How to create a digital certificate and export to .p12 file in PHP?

I want the .p12 file to have private key included. And also want to check whether the key pair is already issued (logged in database).

I found a function called 'openssl_pkcs12_export_to_file' but don't know where to start. Seems that I need an X509 cert and a private key first.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
<?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();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...