Hey there, asymmetric encryption is awesome, right? It's the core encryption concept for all end-to-end encrypted chat systems like WhatsApp, signal, wire, etc. But how do we do that asymmetric encryption in PHP? Well, before we start doing asymmetric encryption, let's understand the core concept behind the system.
Let's say, Alice, want to send a message to Bob, that no middle man but can read. To do that, Alice needs to access Bob's public key, encrypt her message using Bob's private key and send the encrypted message to bob again.
But wait, if Alice can get Bob's encryption key, doesn't that mean, anyone can Bob's public encryption key? Well, yes, anyone can. But here's the tricky part, even if someone can encrypt a message for Bob using his public key, it doesn't mean, anyone can decrypt and read Bob's message using his Public key. Because the public key can only encrypt messages. Decryption takes the private key, which only Bob knows and he doesn't share his private key with anyone! And that's the whole concept of Asymmetric Encryption. Enough of talks, time to write some code.
Oh, Did I mention I wrote a complete article on Encryption in PHP?
We'll be using the OpenSSL PHP extension for this. So, make sure you have a valid openssl.cnf
installed on your system. If you don't have this on your device, don't panic, here is the installation process
Now here's the code block for a complete asymmetric encryption process on PHP using the OpenSSL extension. If you have any doubt or confusion about the code block below, make sure you check out my full article I mentioned above ;p
<?php
//Initial
$res = openssl_pkey_new(array("private_key_bits" => 4096));
//Export the private key
openssl_pkey_export($result, $privKey);
//Get the public key
$publicKey = openssl_pkey_get_details($result)['key'];
//Alice's Secret Message
$plaintext = "Well, I'm from Blogdesire ;p";
//Export the encrypted message to $encrypted
openssl_public_encrypt($plaintext,$encrypted,$publicKey);
//Print encrypted message
echo $encrypted;
//Time to decrypt the message using the private key
openssl_private_decrypt($encrypted, $original_message, $privKey);
//Print the decrypted message
echo $original_message;
Hope you found this helpful.
Top comments (1)
just change $res in $result
thanks a lot it work