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

$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>";


你可能感兴趣的:(PHP,String,解密,File,null,Path)