Search code examples
phpopensslphp-openssl

openssl_pkey_get_private returning false for one key


I am having two keys. For one it is working completely fine and giving the response as resource(368) of type (OpenSSL key) but for the other key it is just returning a false.

In both the cases I am not providing the path, but instead the string itself.

The key in which its working is like this :

-----BEGIN RSA PRIVATE KEY-----
MIIJKAIBAAKCAgEA74waKCtYqw7U7gE93BCn0CPmulFd1K8AaJqqBjOLe//okAuA
<...........................................................>
MGgCk1mrd65nf6JWsxb3RVcQ7jYxyFs3Pr4LFcgn1K0aTLnlwarBFjt+J3Y=
-----END RSA PRIVATE KEY-----

And the key in which it is not working is like this :

-----BEGIN RSA PRIVATE KEY-----
Proc-Type: 4,ENCRYPTED
DEK-Info: AES-128-CBC,14CA8(removing some values)2B6244

LwBvVX6TbdS9XYg0xywoLbhiaYK5UE6SQnATXJ8fXfJit+F4XcOfmWyQn+UsJRnM
<...........................................................>
s8M/Fe7YpkORsGSzQ6f5YslfmbmCsdCFDiBnTaIe45NP8IBULWY/vm45bYFteKUs
-----END RSA PRIVATE KEY-----

PS : I have hidden most part of keys for security.

Is there anything about the keys value also that affects the openssl to throw an error?

CODE :

$pkey = openssl_pkey_get_private(my_private_key_in_string_form);

EDIT :

What I on my research could find is that the second key is in an encrypted form whereas the first one is in the raw form. But I am yet not able to find how to convert this encrypted private key to its raw form from an already created key.


Solution

  • Looking at the keys, the one which works is not protected with passpharase, the one that you say fails is protected with passpharase, also the call to openssl_pkey_get_private() , does not have second optional parameter for passpharese. I am referring the dcumentation from https://www.php.net/manual/en/function.openssl-pkey-get-private.php

    So if your private key is encrypted, you have to specify the passpharase so that the key can be read properly by the openssl_pkey_get_private() API