简体   繁体   中英

openssl_pkey_get_private returning false

Im trying to verify some private keys but the php method openssl_pkey_get_private() always return false . And the openssl_error_string() is returning:

error:0906D06C:PEM routines:PEM_read_bio:no start line

    $return = openssl_pkey_get_private($path.'_priKEY.pem');
    if ($return === false) {
        var_dump(openssl_error_string());
    }

Tried this with private key extracted from .pfx file, other from .p12 file, and even an self generated key (with openssl). Already tried with "RSA PRIVATE KEY", "ENCRYPTED PRIVATE KEY" and "PRIVATE KEY". Nothing changes.

Private key content:

-----BEGIN PRIVATE KEY-----
MIIEvgIBADANBgkqhkiG9w0B
[......................]
Wxdadnf7MB7DicckIZTKVy1L
-----END PRIVATE KEY-----

It looks like you did not provide the right format for the path to the file. Make sure it starts with file:// , followed by and absolute or relative path. Yes, if you choose an absolute path, then the path to the filename will be something like file:///absolute/path/to/keyfile.pem , starting with three slashes. For relative paths, it will be file://relative/path/to/keyfile.pem .

According to the documentation for openssl_pkey_get_private() , you can provide the key either as a path to a file, or as a string containing the actual key. Only if the value starts with file:// , it is interpreted as the path (URI) to a file. Otherwise, the value is interpreted as a string containing the PEM-encoded key. In the latter case, it expects a start line that it recognizes as PEM, like -----BEGIN PRIVATE KEY----- . That is why you get that error message, your argument neither starts with file:// nor with a PEM start line.

If you do not like the file:// path format, you could always read the contents of the file yourself before providing it to openssl_pkey_get_private() , something like:

$return = openssl_pkey_get_private(file_get_contents($path.'_priKEY.pem'));

Please refer to next URL.

https://www.php.net/manual/en/function.openssl-pkey-get-private.php

To narrow down your issue, please use same directory for your php file and key file and try this working code.

Working code

$keyfile="file://".__DIR__.DIRECTORY_SEPARATOR."key.pem"; //absolute path
$key = openssl_pkey_get_private($keyfile);

if ($key === false) {
    var_dump(openssl_error_string());
}else{
    var_dump($key);
}

Also please refer to Openssl and PHP

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM