I kept banging my head against the wall today trying to figure out why the RSA keys I was generating were encrypted (they have this stuff in them)Proc-Type: 4,ENCRYPTEDDEK-Info: DES-EDE3-CBC,BEA1180EADE1524F

I finally realized that the issue was that I was passing a password into the "openssl_pkey_export" method inadvertently.

So the moral of the story is: you have to use NULL as the password. using an empty string will still cause the key to be encrypted.

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.

Exporting a public key for use with JCE is trickier, since the Java libraries require the key to be input as a byte array. In effect, the public key outputted by openssl_pkey_get_details() must be base64 decoded as above, and then parsed as ASN.1 to receive the actual key bytes (this can be done either on the PHP side or the Java side).