There is really little information about PHP generating certificate keys. After searching for a long time, I finally found the relevant information in the official documents. Based on my own understanding, I compiled the following code, which is divided into two parts: generating certificate keys and encryption. Decrypt data. Just copy it and make two files and run them. Detailed comments have been written, I believe all PHP programmers can understand them.
generate.php
- $dn = array(
- "countryName" => 'XX', //Name of the country where you are located
- "stateOrProvinceName" => 'State', //Name of the province where you are located
- "localityName" => 'SomewhereCity', //The name of the city
- "organizationName" => 'MySelf', //The name of the registrant
- "organizationalUnitName" => 'Whatever', //The name of the organization
- "commonName " => 'mySelf', //Public name
- "emailAddress" => 'user@domain.com' //Email
- );
-
- $privkeypass = '111111'; //Private key password
- $numberofdays = 365; //Validity period
- $cerpath = "./test.cer"; //Generate certificate path
- $pfxpath = "./test.pfx"; //Key file path
-
-
- //Generate certificate
- $ privkey = openssl_pkey_new();
- $csr = openssl_csr_new($dn, $privkey);
- $sscert = openssl_csr_sign($csr, null, $privkey, $numberofdays);
- openssl_x509_export($sscert, $csrkey); //Export Certificate $csrkey
- openssl_pkcs12_export($sscert, $privatekey, $privkey, $privkeypass); //Export key $privatekey
- //Generate certificate file
- $fp = fopen($cerpath, "w");
- fwrite($ fp, $csrkey);
- fclose($fp);
- //Generate key file
- $fp = fopen($pfxpath, "w");
- fwrite($fp, $privatekey);
- fclose($fp) ;
- ?>
Copy code
crypt.php
- $privkeypass = '111111'; //Private key password
- $pfxpath = " ./test.pfx"; //Key file path
- $priv_key = file_get_contents($pfxpath); //Get key file contents
- $data = "test"; //Encrypted data test test
-
- //Private key Encryption
- openssl_pkcs12_read($priv_key, $certs, $privkeypass); //Read public key and private key
- $prikeyid = $certs['pkey']; //Private key
- openssl_sign($data, $signMsg, $prikeyid ,OPENSSL_ALGO_SHA1); //Register to generate encrypted information
- $signMsg = base64_encode($signMsg); //base64 transcoded encrypted information
-
-
- //Public key decryption
- $unsignMsg=base64_decode($signMsg);//base64 decoded encryption Information
- openssl_pkcs12_read($priv_key, $certs, $privkeypass); //Read public key and private key
- $pubkeyid = $certs['cert']; //Public key
- $res = openssl_verify($data, $unsignMsg , $pubkeyid); //Verification
- echo $res; //Output the verification result, 1: verification successful, 0: verification failed
- ?>
Copy code
|