echo "check a pair of keys: cert signed by self and private: \n"; check_pair($cert_self, $priv); // 验证证书是否有效 function check_cert($cert) { // 只能是文件路径,可以是多个 x509 证书 // 不能是 pem 格式字符串和 OpenSSL X.509 资源 $cainfo = __DIR__ . '/ca/ca_cert.cer'; $purpose = [X509_PURPOSE_SSL_CLIENT, X509_PURPOSE_SSL_SERVER, X509_PURPOSE_NS_SSL_SERVER, X509_PURPOSE_SMIME_SIGN, X509_PURPOSE_SMIME_ENCRYPT, X509_PURPOSE_CRL_SIGN, X509_PURPOSE_ANY]; foreach ($purpose as $p) { var_dump(openssl_x509_checkpurpose($cert, $p, [$cainfo])); } } echo "check certificate valid: signed ca\n"; check_cert($certout_ca); echo "\ncheck certificate valid: signed self\n"; check_cert($certout_self); echo "\ncheck certificate valid: another certificate\n"; check_cert($certout_other); echo "\n"; openssl_pkey_export($priv, $priv_key, null, $config); $cleartext = '1234 5678 9012 3456'; echo "Clear txt: \n{$cleartext}\n"; openssl_public_encrypt($cleartext, $crypttext, $certout_self); // right echo "\nCrypt signed self text:\n" . base64_encode($crypttext) . "\n"; openssl_public_encrypt($cleartext, $crypttext, $certout_ca); // right echo "\nCrypt signed CA text:\n" . base64_encode($crypttext) . "\n"; openssl_private_decrypt($crypttext, $decrypted, $priv_key); echo "\nDecrypted text:\n{$decrypted}\n\n";
$contents = file_get_contents($file_contents); openssl_pkcs12_read($pkcs12, $cert, $pass); while ($msg = openssl_error_string()) { echo $msg . "<br />\n"; } openssl_private_decrypt($contents, $decrypted, $cert['pkey']); if ($plain === $decrypted) { echo "+Ok, decrypt succ!\n"; } else { echo "-Err, decrypt fail!(" . __LINE__ . ")\n"; } } if (!is_dir($path)) { mkdir($path, 0775); } else { exec("rm -fr {$path}/*", $out, $ret); } create_ca(); create_cert(); check_cert(); encrypt(); decrypt(); /* * 测试: * (1)CA 证书不过期,用户证书过期 * (2)CA 证书过期,用户证书不过期 * * 结论: * (1)CA 证书过期,则用户证书验证失败 * (2)CA 证书有效,用户证书过期,则验证失败 */