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 "

Private Key

$privkey
"; echo "

Public Key

$pubkey
"; echo "

Plaintext

$plaintext
"; echo "

Crypted

$crypted
"; echo "

Decrypted

$decrypted
";


你可能感兴趣的:(php,解密,php,file,string,path,null)