PHP通过OpenSSL生成证书、密钥并且加密解密数据

清华大佬耗费三个月吐血整理的几百G的资源,免费分享!....>>>

关于PHP生成证书密钥的资料真是好少啊,查了半天,最终还是在官方文档找到了相关资料,又根据自己的理解,整理成了以下代码,分成两部分:生成证书密钥、加密解密数据。直接复制下来做成两个文件运行就好啦。已经写了详细的注释,相信PHP程序员都能看得懂。

generate.php

    <?php  
    $dn = array(  
        "countryName" => 'XX', //所在国家名称  
        "stateOrProvinceName" => 'State', //所在省份名称  
        "localityName" => 'SomewhereCity', //所在城市名称  
        "organizationName" => 'MySelf',   //注册人姓名  
        "organizationalUnitName" => 'Whatever', //组织名称  
        "commonName" => 'mySelf', //公共名称  
        "emailAddress" => 'user@domain.com' //邮箱  
    );  
      
    $privkeypass = '111111'; //私钥密码  
    $numberofdays = 365;     //有效时长  
    $cerpath = "./test.cer"; //生成证书路径  
    $pfxpath = "./test.pfx"; //密钥文件路径  
      
      
    //生成证书  
    $privkey = openssl_pkey_new();  
    $csr = openssl_csr_new($dn, $privkey);  
    $sscert = openssl_csr_sign($csr, null, $privkey, $numberofdays);  
    openssl_x509_export($sscert, $csrkey); //导出证书$csrkey  
    openssl_pkcs12_export($sscert, $privatekey, $privkey, $privkeypass); //导出密钥$privatekey  
    //生成证书文件  
    $fp = fopen($cerpath, "w");  
    fwrite($fp, $csrkey);  
    fclose($fp);  
    //生成密钥文件  
    $fp = fopen($pfxpath, "w");  
    fwrite($fp, $privatekey);  
    fclose($fp);  
    ?>  

crypt.php
    <?php  
    $privkeypass = '111111'; //私钥密码  
    $pfxpath = "./test.pfx"; //密钥文件路径  
    $priv_key = file_get_contents($pfxpath); //获取密钥文件内容  
    $data = "test"; //加密数据测试test  
      
    //私钥加密  
    openssl_pkcs12_read($priv_key, $certs, $privkeypass); //读取公钥、私钥  
    $prikeyid = $certs['pkey']; //私钥  
    openssl_sign($data, $signMsg, $prikeyid,OPENSSL_ALGO_SHA1); //注册生成加密信息  
    $signMsg = base64_encode($signMsg); //base64转码加密信息  
      
      
    //公钥解密  
    $unsignMsg=base64_decode($signMsg);//base64解码加密信息  
    openssl_pkcs12_read($priv_key, $certs, $privkeypass); //读取公钥、私钥  
    $pubkeyid = $certs['cert']; //公钥  
    $res = openssl_verify($data, $unsignMsg, $pubkeyid); //验证  
    echo $res; //输出验证结果,1:验证成功,0:验证失败  
    ?>