php 生成RSA公钥和私钥 可刷新运行 刷新

RSA可用于加密和签名

代码:

function generate(int $private_key_bits = 1024)
{
    $rsa = [
        "private_key" => "",
        "public_key" => ""
    ];
    $config = [
        "digest_alg" => "sha512",
        "private_key_bits" => $private_key_bits,
        "private_key_type" => OPENSSL_KEYTYPE_RSA,
    ];
    $res = openssl_pkey_new($config);
    openssl_pkey_export($res, $rsa['private_key']);
    $rsa['public_key'] = openssl_pkey_get_details($res)["key"];
    return $rsa;
}


$rsa=generate();

$private_key=$rsa['private_key'];
$public_key=$rsa['public_key'];

echo "private_key:\n" . $private_key . "\n\r";
echo "public_key:\n" . $public_key . "\n\r";

输出:

private_key:
-----BEGIN PRIVATE KEY-----
MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAL4FbadVnKZSfoke
L6r6ftlMK+YrfgrXfC5bPLPTZCtGmc6SwndxGcrWDJ5iw2bXK9xqu/ynkkMCQCm6
UDwVuDdCX7bJSR0v40+bpKK6AvaaIy7oxmRimbsX845wtMh16Ls8eSW9M1zm/jdk
tm4kad+/p2k9A8qEC+6mcU6dnDJ1AgMBAAECgYEAime7ydEyy3Z00fzZrYjNEgtI
QltVcCIqQj2URkrnwBmpd+wvlv4bUkF8aXT4bJS3TtGzYUDQ6NvfzkT1of4T8XHv
Lls9JI4usyLkHqTliZ57m7ZYSRfZY7jgnV8+nKGroV9X3Dg/Vp+rKvCUfjp4vrfO
HXz7nJJHztWmgAd+t5UCQQDsAJ6hIBYsj9Ovoea3KOtO5e6B1U2O1/ktYLRKlC/h
muzTjd5Iss4DfkQXgEY9DcG2cbbAxDYefEi4i54EKcZXAkEAzh9hjUU+MMfxqYDj
rkQ2JMknUITxb59v3KOPzaDO+r7UfdaxcTuwHg8SxHApl+A1/qErQh0Q8N3qECCI
o+EWEwJAVH7ETJvYVIwKFk+48srLtKvOAN4FrqbUp9J/ulPj8LovIG8irpSV/dov
NtrOSv2p5VBBRjL5zWBiCPCz2nm6cQJAXbwBlc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