. PFX private key certificate encryption,. Cer public key certificate decryption – PHP practice

Time:2021-8-30

origin

  enterprise projects need to be connected with third parties, which inevitably involves some encryption and decryption. As a member of an outsourcing company, this situation is more common. I’ve done it several times in the middle, and I met it allRSAEncryption, and then this is a special case.pfxPrivate key certificate encryption and.cerThe function of public key certificate decryption is summarized here.

. PFX private key signature

$toSign = "hello world";  //  String to be encrypted
$psd = 'zsmm';  //  Certificate private key password
$certs = array();
$cert_ path = "c:/cert/test.pfx";  //  Absolute address of the certificate

openssl_pkcs12_read(file_get_contents($cert_path), $certs, $psd);
if(!$certs){
    Exit ('failed to get secret key! ');
}

if (openssl_sign($toSign, $binarySignature, $certs['pkey'])) {
    echo base64_ encode($binarySignature);     //  What is encrypted is binary, which needs Base64 coding
}

. cer public key signature verification

.cerCertificates do not need to be usedopenssl x509 -inform der -in pub.cer -out pub.pemCommand to convert the certificate format.

$data = "hello world";    //  Original text before signature
$sign= "binarySignature";    //  autograph
$cert_ path = "c:/cert/test.cer'";  //  Absolute address of the certificate

$source = openssl_pkey_get_public(file_get_contents($cert_path));
echo openssl_ verify($data, $sign, $source);      //  1: Signature verification passed, 0: signature verification failed, - 1: system internal error