php生成证书和密钥

            $dn = array(
                "countryName" => 'XX', //所在国家名称
                "stateOrProvinceName" => 'State', //所在省份名称
                "localityName" => 'SomewhereCity', //所在城市名称
                "organizationName" => 'MySelf',   //注册人姓名
                "organizationalUnitName" => 'Whatever', //组织名称
                "commonName" => 'mySelf', //公共名称
                "emailAddress" => 'user@domain.com' //邮箱
            );

            $privkeypass = '123456'; //私钥密码
            $numberofdays = 365;     //有效时长
            $cerpath = "./my.cer"; //生成证书路径
            $pfxpath = "./my.pfx"; //密钥文件路径


            $configArgs = array(
                'config' => 'C:\xampp\apache\bin\openssl.cnf',
                "digest_alg" => "sha512",
                "private_key_bits" => 4096,
                "private_key_type" => OPENSSL_KEYTYPE_RSA,
            );

            // Create the private and public key
            $res = openssl_pkey_new($configArgs);

            $csr = openssl_csr_new($dn, $res, $configArgs);

            $sscert = openssl_csr_sign($csr, null, $res, $numberofdays, $configArgs);

            openssl_x509_export($sscert, $csrkey); //导出证书$csrkey

            openssl_pkcs12_export($sscert, $privatekey, $res, $privkeypass); //导出密钥$privatekey
            
            //生成证书文件
            $fp = fopen($cerpath, "w");
            fwrite($fp, $csrkey);
            fclose($fp);

            //生成密钥文件
            $fp = fopen($pfxpath, "w");
            fwrite($fp, $privatekey);
            fclose($fp); 
加密和解密
            $privkeypass = '123456'; //私钥密码
            $pfxpath = "./my.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); //验证
            var_dump($res); //输出验证结果,1:验证成功,0:验证失败


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值