key parameter is not a valid public key error in openssl_public_encrypt()

本地PHP 7.0.8,以下代码运行OK

function getAuthorizedUrl($base_url, $encrypted_params, $non_encrypted_params = [])
{
    $appId = '1111';
    $pid = '111111';
    $public_key = "-----BEGIN PUBLIC KEY-----\nMy public key here\n-----END PUBLIC KEY-----"; 
    
    $str = http_build_query($encrypted_params);

    $openssl_public_encrypt = openssl_public_encrypt($str, $encrypted, $public_key);
    if (!$openssl_public_encrypt) {
        throw new \Exception('openssl_public_encrypt failed! ');
    }
    $data = base64_encode($encrypted);
    $query_str = http_build_query(compact('appId', 'pid', 'data') + $non_encrypted_params);
    $url = $base_url . '?' . $query_str;

    return $url;
}

发布到线上后报错:key parameter is not a valid public key error in openssl_public_encrypt()
线上PHP 7.1.17

看php手册文章 function.openssl-pkey-get-public.php 有这么一段:
key parameter is not a valid public key error in openssl_public_encrypt()_第1张图片
果断尝试了,修改成如下后运行正常了

function getAuthorizedUrl($base_url, $encrypted_params, $non_encrypted_params = [])
{
    $appId = '1111';
    $pid = '111111';
    $public_key = "My public key here"; 

    $public_key = "-----BEGIN PUBLIC KEY-----\n" . wordwrap($public_key, 64, "\n", true) . "\n-----END PUBLIC KEY-----";

    $str = http_build_query($encrypted_params);

    $openssl_public_encrypt = openssl_public_encrypt($str, $encrypted, $public_key);
    if (!$openssl_public_encrypt) {
        throw new \Exception('openssl_public_encrypt failed! ');
    }
    $data = base64_encode($encrypted);
    $query_str = http_build_query(compact('appId', 'pid', 'data') + $non_encrypted_params);
    $url = $base_url . '?' . $query_str;

    return $url;
}

你可能感兴趣的:(php)