Please refer to the following URL.
https://www.php.net/manual/en/function.openssl-pkey-get-private.php
To narrow down the problem, use the 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); }
The following may be a problem.
- Way
The following path styles should work.
$keyfile="file:///home/john/php/key.pem"; // unix absoulute path $keyfile="file://C:\\users\\john\\php\\key.pem"; // windows absoulute path $keyfile="file://".__DIR__.DIRECTORY_SEPARATOR."key.pem"; //absoulute path for unix, windows $keyfile="file://key.pem"; // relative path, unix, windows, (php,key files in same directory) $key = openssl_pkey_get_private($keyfile);
If the path does not exist, the error will look like
"error: 02001002: system library: fopen: there is no such file or directory"
Web environment
Check your web root and web user access rights to the folder and key file.
To reduce the number of problems, test it on the env of the php embedded web server, and not on wamp.
>php -S localhost:80
- Corrupted key file
stored as a specific type, which includes spaces. This error may occur, as in the following.
"error: 0906D06C: PEM routines: PEM_read_bio: no start line"
in my case, key file was saved as UTF-8 with BOM(whitespaces)
Debug Key File 1 - READ FROM VARIABLE
This code should work. I got the key file from http://micmap.org/php-by-example/en/function/openssl_pkey_get_private
Please replace $ str with yours.
$str = <<<EOF -----BEGIN RSA PRIVATE KEY----- MIIEogIBAAKCAQEA0llCeBjy18RylTdBih9GMUSZIC3GzeN0vQ9W8E3nwy2jdeUn H3GBXWpMo3F43V68zM2Qz5epRNmlLSkY/PJUfJIC8Yc1VEokT52q87hH/XJ5eS8h eZnjuSlPAGi8oZ3ImVbruzV7XmlD+QsCSxJW7tBv0dqJ71e1gAAisCXK2m7iyf/u l6rT0Zz0ptYH4IZfwc/hQ9JcMg69uM+3bb4oBFsixMmEQwxKZsXk3YmO/YRjRbay +6+79bSV/frW+lWhknyGSIJp2CJArYcOdbK1bXx1dRWpbNSExo7dWwuPC0Y7a5AE eoZofieQPPBhXlp1hPgLYGat71pDqBjKLvF5GwIDAQABAoIBACPItYsSy3U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V88xwCoDg9ZIFprWA P5p/cnvj6aHnqL58XiH0+bE0Lt3J+U6N6JelQQevgBHooMFh4FpDXcVda7xB3rK3 woqbi8fNhr827H2maxIZPtVG95/mvR4k5z1Jrdnr34ZUmtC6U5Q= -----END RSA PRIVATE KEY----- EOF; $key = openssl_pkey_get_private($str); if ($key === false) { var_dump(openssl_error_string()); }else{ var_dump($key); }
OUTPUT
resource (4) of type (OpenSSL key)
Debug Key File 2 - READ FROM FILE
copy the key strings ($ str) into the key file, for example, "key.pem".
$str = <<<EOF -----BEGIN RSA PRIVATE KEY----- ...YOUR KEY STINGS HERE... -----END RSA PRIVATE KEY----- EOF; $str2 = file_get_contents("key.pem"); $len1 = strlen ($str); $len2 = strlen ($str2); if($len1 !== $len2) echo "File has been corrupted."; $key = openssl_pkey_get_private($str2); if ($key === false) { var_dump(openssl_error_string()); }else{ var_dump($key); }