当私钥保存在文件中时,php openssl无法正常工作

When i save private key (not public key, when public key save to file - works fine!) to file the result of decode is false.

function generate_keys() {
    $config = array(
        "config" => "C:/xampp/php/extras/openssl/openssl.cnf",
        "private_key_type"=>OPENSSL_KEYTYPE_RSA,
        "private_key_bits"=>512,
    );

    $res = openssl_pkey_new($config);
    $privKey = '';
    openssl_pkey_export($res, $privKey, 'test', $config);
    $fpr = fopen("private.txt", "w");
    fwrite($fpr, $privKey);
    fclose($fpr);

    $arr = array(
    "countryName" => "UA",
        "stateOrProvinceName" => "Kievskaya Oblast",
        "localityName" => "Kiev",
        "organizationName" => "Organization",
        "organizationalUnitName" => "Soft",
        "commonName" => "localhost",
        "emailAddress" => "ilovesssl@php.net"
    );
    $csr = openssl_csr_new($arr, $privKey, $config);

    $cert = openssl_csr_sign($csr, NULL, $privKey, 365, $config);
    openssl_x509_export($cert, $str_cert);

    $public_key = openssl_pkey_get_public($str_cert);
    $public_key_details = openssl_pkey_get_details($public_key);

    $public_key_string = $public_key_details['key'];

    $fpr1 = fopen("public.txt","w");
    fwrite($fpr1, $public_key_string);
    fclose($fpr1);

    return array('private'=>$privKey,'public'=>$public_key_string);

}

$keys = generate_keys(); // if get private key from here - works fine!

    $path = "public.txt";
    $fpr = fopen($path,"r");
    $pub_key = fread($fpr,1024);
    fclose($fpr);

    openssl_public_encrypt('test string', $passcrypt, $pub_key);
}

$path = "private.txt";
$fpr = fopen($path,"r");
$pr_key = fread($fpr, 1024); // if i get key from file result is false! 
fclose($fpr);

openssl_private_decrypt($passcrypt, $decrypted, openssl_pkey_get_private($pr_key, 'test'));

echo var_dump($decrypted == "test string");

When i save private key to variable the result is true, but when i save it to file and then get it from file the result is false.

doudizhi947129
doudizhi947129 结果有些:|
9 个月之前 回复
duananyu9231
duananyu9231 在Windows中,使用“rb”和“wb”作为fopen-mode。
9 个月之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问