Asymmetric encryption using PHP

Viewed 12088

I have a problem that is driving me crazy.

I have created a pair of keys doing:

$res = openssl_pkey_new(array('private_key_bits' => 2048));

/* Extract the private key from $res to $privKey */
openssl_pkey_export($res, $privKey);

/* Extract the public key from $res to $pubKey */
$pubKey = openssl_pkey_get_details($res);
$pubKey = $pubKey["key"];

Using this code, I have $pubKey and $privKey.

I can encrypt/decrypt correctly, but I have a big doubt regarding the DECRYPTION.

At the moment I crypt data doing:

openssl_public_encrypt($data, $encrypted, $pubKey);

It encrypt my data correctly, but reading the PHP Doc, I found:

http://php.net/manual/en/function.openssl-public-decrypt.php

Can I decrypt data using PUBLIC KEY ?? Why ??

I know the public key is useful to ENCRYPT data, but only the owner of the private key can DECRYPT data.

If I can decrypt data using the public key, let the users that know the public key decrypt easily the messages.

Could someone explain this to me? I'm looking for a method to use two keys, the first to ENCRYPT and the second (only the second) to DECRYPT.

Thanks

4 Answers

Short Answer

A message encrypted by a public key can only be decrypted by the matching private key.

Long Answer

Asymmetric encryption works both ways.

So why is there even an openssl_public_decrypt() function? you might ask. As the documentation states it can decrypt a message which has been encrypted by a private key. As wally mentioned before this can be used for signatures.

Let's say Alice waits for a message from Bob, but not from anybody else. So Bob uses his own private key to encrypt the message (e.g using openssl_private_encrypt()). When Alice recieves any message she tries to decrypt it using Bob's public key. If this succeeds she knows that the message came from Bob.

Note that encrypting using the private key would not be secure because anybody (who has access to the public key) can decrypt the message. In practise you would probably use a combination of both methods (append a signature encrypted with Bob's private key and then encrypt the entire message using Alice's public key).

Related