Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
March 19, 2022 06:55 pm GMT

Asymmetric Encryption In PHP

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 $encryptedopenssl_public_encrypt($plaintext,$encrypted,$publicKey);//Print encrypted messageecho $encrypted;//Time to decrypt the message using the private keyopenssl_private_decrypt($encrypted, $original_message, $privKey);//Print the decrypted messageecho $original_message;

Hope you found this helpful.


Original Link: https://dev.to/khokon/asymmetric-encryption-in-php-3m21

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To