php 中生成公私钥及加解密过程

本文演示了如何使用PHP的openssl扩展来生成密钥对,并利用这些密钥进行数据加密与解密的过程。具体步骤包括创建RSA密钥对、导出私钥、获取公钥详情、使用公钥加密明文以及用私钥解密密文。
$configargs = array(
        'config' => 'C:\Users\chengxt\Desktop\PHPnow-1.5.6\PHPnow-1.5.6\Apache-22\bin\openssl.cnf',    //valid openssl.cnf
    //    'digest_alg' => 'md5',
    //    'x509_extensions' => 'v3_ca',
    //    'req_extensions'   => 'v3_req',
    //    'private_key_bits' => 1024,
    //    'private_key_type' => OPENSSL_KEYTYPE_RSA,
    //    'encrypt_key' => false,
        );
    $plaintext = "Hello";
    
    //create the keypair
    $res=openssl_pkey_new($configargs);
    if(empty($res)){
        echo "error: no key was generated by openssl_pkey_new()";
        echo openssl_error_string();
    }else{
        echo "a private key was generated by openssl_pkey_new()";
    }
    
    //get private key
    openssl_pkey_export($res, $privkey,null,$configargs);
    //$privkey = openssl_pkey_get_private($pem);    //get key from pem format data, $pem = file path or pem string
    
    //get public key
    $pubkey=openssl_pkey_get_details($res);
    $pubkey=$pubkey["key"];
    
    //encrypt & decrypt
    openssl_public_encrypt($plaintext,$crypted,$pubkey);
    openssl_private_decrypt($crypted,$decrypted,$privkey);
    
    //output key file
    file_put_contents("pub.key",$pubkey);
    file_put_contents("pri.key",$privkey);
    
    //print test result
    echo "<h1>Private Key</h1><pre>$privkey</pre>";
    echo "<h1>Public Key</h1><pre>$pubkey</pre>";
    echo "<h1>Plaintext</h1><pre>$plaintext</pre>";
    echo "<h1>Crypted</h1><pre>$crypted</pre>";
    echo "<h1>Decrypted</h1><pre>$decrypted</pre>";


评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值