user1873420
user1873420

Reputation: 101

convert .key to .pem

I need to encrypt with private key and I'm attempting to do so with the following code:

$content = file_get_contents("file.key");

$plaintext = "14d9df79-8c4c-4380-8444-d31e1fd3f78a";

openssl_private_encrypt($plaintext, $encrypted, $content);

$transfer = base64_encode($encrypted);

echo "text encrypted is:" . $transfer;  //encrypted string

I'm getting the error: openssl_private_encrypt(): key param is not a valid private key in

Do I have to do something to the key file? It is binary.

Upvotes: 0

Views: 25311

Answers (3)

user1873420
user1873420

Reputation: 101

Solved I just use the

openssl pkcs8 .....

command

hope this is useful to someone else

Upvotes: -2

Martin
Martin

Reputation: 6015

First, try converting a key into PEM format using openssl:

openssl rsa -inform der -in file.key -outform pem -out filekey.pem

Next, extract the private key from the PEM file using openssl_pkey_get_private

$key = openssl_pkey_get_private(file_get_contents("filekey.pem"));

$plaintext = "14d9df79-8c4c-4380-8444-d31e1fd3f78a";

openssl_private_encrypt($plaintext, $encrypted, $key);

$transfer = base64_encode($encrypted);

echo "text encrypted is:" . $transfer;  //encrypted string

Upvotes: 3

symcbean
symcbean

Reputation: 48357

I don't know of any x509 file format using a .key extension. There's pem (which is the format you need to load into openssl), DER (files may have .der, .crt or .cer extension) or PKCS#12 (.pfx .p12). It's probably DER or PKCS#12:

 openssl pkcs12 -in file.key -out file.pem -nodes

...converts a PKCS#12 to file.pem,

openssl x509 -inform der -in file.key -out file.pem

...converts a DER file. They'll report an error if it's the wrong file format. OTOH you could just use the 'file' command to find out the file type. (this is assuming that you've got a Posix / Linux system - you didn't say).

Or you could just ask the person who gave it to you what format it is.

Upvotes: 3

Related Questions