When I'm creating private key strings with the following PHP code (and same config-parameter), they are enclosed between different strings:
$configs = array('config' => 'OpenSSL.cnf',
'digest_alg' => 'sha1',
'x509_extensions' => 'v3_ca',
'req_extensions' => 'v3_req',
'private_key_bits' => 2048,
'private_key_type' => OPENSSL_KEYTYPE_RSA,
'encrypt_key' => false,
'encrypt_key_cipher' => OPENSSL_CIPHER_3DES);
$privateKeyResourceId = openssl_pkey_new($this->configs);
openssl_pkey_export($privateKeyResourceId, $privateKeyString);
On Linux the $privateKeyString looks like this:
-----BEGIN PRIVATE KEY-----NBgkqhkiG9w0BAQE....ASDFasjkfa-----END PRIVATE KEY-----
On Windows the $privateKeyString looks like this:
-----BEGIN RSA PRIVATE KEY-----NBgkqhkiG9E....ASDFasjkfa-----END RSA PRIVATE KEY-----
When I copy the Windows private key string to Linux it works until I remove the 'RSA' from the start/end (same behavior vice versa). Why is this?
According to a user note php.net this is a known issue:
Please take note that older versions of PHP/OpenSSL exports the RSA private key with '-----BEGIN RSA PRIVATE KEY-----' PEM tag, which includes just the privateKey field, thus omitting the version and privateKeyAlgorithm fields.
The effect of that would be that if you're converting it to DER, and
then back to PEM, but using '-----BEGIN PRIVATE KEY-----' PEM tag,
that the openssl_pkey_get_privatekey() function will fail!Senthryl's
code can be used to prefix the PEM encoded data with the version and
privateKeyAlgorithm fields again.
The newer PHP/OpenSSL versions exports the RSA private key with
'-----BEGIN PRIVATE KEY-----' PEM tag, which includes the version and
privateKeyAlgorithm fields.
I noticed these differences between my two servers:
PHP Version 5.3.3 (OpenSSL 1.0.0a-fips 1 Jun 2010) on Fedora Core 12 x64
PHP Version 5.2.9 (OpenSSL 0.9.8g 19 Oct 2007) on Fedora Core 10 x64
This is a differece between openssl versions not PHP. The following openssl command creates different key headers/footers between openssl versions 0.9.x and 1.0.0x:
openssl req -new -keyout mykey.key -out mycertreq.csr -nodes -sha1 -newkey rsa:2048
For version 0.9.x, the key header/footer is:
-----BEGIN RSA PRIVATE KEY-----
-----END RSA PRIVATE KEY-----
For version 1.0.0x, the key header/footer is:
-----BEGIN PRIVATE KEY-----
-----END PRIVATE KEY-----
For the later version of openssl, I have to run the key file through the following command to make it compatible with the older default:
openssl rsa -in mykey.key -text > mykey.pem
The "mykey.pem" file then has the header/footers (and format) that is compatible with AWS and like services.