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-----
MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBAKSsR+Bb4f6RkQ1H
6k1IL6Nm+UVwWbvQ2/WlMBHQUFEvoMohewLvLWTZFAIh66KScvmbuhguHo04RO9a
a5IMQ4iW3JqWgAJb4xs07JBsKBygJTMJUkg6R2B2+uKiv45l+Yn3ge9zVriwvl4w
C6H68c+A1E7xUuC8FtsPAgtPSNdhAgMBAAECgYBcRI/tfW5Ohl/BEkeNT+Ipa3xG
VSJiYy+sHwelI5StOMOeHk5foYZM2HkmjL0MFYTIqWIHRGgn9pxhhMd7SNXZX2vk
DgUyoZPoeROoJyQWBwpnL8zGDZVcwN+cyDHzIhNIiQegMGLetchv0awgazaN2OnK
b3XF/EgDz+DM10wK1QJBANYcy1uNO19tWNKqo0p51u+zgFdaX707Mqt+6gAhoAx0
/2h7g+yc/hp+S7stD1OfU5pXOR1shNkErYuPWFIXtTsCQQDE43OOSmzeCFzEfCEw
ZyJNE5ac1MQS6u+9cO5IrfvuEf0Mm7vbz+XDhahEHHjZibuL+SzhdTrASk35NMX+
HOwTAkAsK6SILoqhFR3N2AX3x0rgCFfhrXMyxpOdbYE4pbcu2rQWCeUdWwXQ0V0u
MA2JYsUMghH2T/zYCG8E63188gchAkApP4WcD9eTBKl6u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