Last active
April 5, 2019 13:56
-
-
Save chriha/39cfdd32f5e28bad27a28101d65c2ba7 to your computer and use it in GitHub Desktop.
Asymmetric Encryption - encrypt data via public and decrypt via private key
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Create private key: | |
* $ openssl genrsa -out private.key 2048 | |
* | |
* Create public key: | |
* $ openssl rsa -in private.key -outform PEM -pubout -out public.pem | |
*/ | |
$privateKey = openssl_get_privatekey( file_get_contents( 'private.key' ) ); | |
$publicKey = openssl_get_publickey( file_get_contents( 'public.pem' ) ); | |
$data = 'ThisIsAn$Encrypted(Password'; | |
echo "# Data in:\n$data\n\n"; | |
$encrypted = $e = null; | |
openssl_seal( $data, $encrypted, $e, [ $publicKey ] ); | |
$sealedData = base64_encode( $encrypted ); | |
$envelope = base64_encode( $e[0] ); | |
echo "# Sealed data:\n$sealedData\n\n"; | |
echo "# Envelope:\n$envelope\n\n"; | |
$input = base64_decode( $sealedData ); | |
$eInput = base64_decode( $envelope ); | |
$plaintext = null; | |
openssl_open( $input, $plaintext, $eInput, $privateKey ); | |
echo "# Data out:\n$plaintext\n"; | |
echo "- - - - - - - - - - - - - - - - - -\n\n"; | |
// Something to encrypt | |
$text = 'This is the text to encrypt'; | |
echo "# This is the original text:\n$text\n\n"; | |
// Encrypt using the public key | |
openssl_public_encrypt( $text, $encrypted, $publicKey ); | |
$encrypted_hex = bin2hex( $encrypted ); | |
$encryptedBase64 = base64_encode( $encrypted ); | |
echo "This is the encrypted text:\n$encrypted_hex\n\n"; | |
echo "This is the encrypted text (base64):\n$encryptedBase64\n\n"; | |
// Decrypt the data using the private key | |
openssl_private_decrypt( base64_decode( $encryptedBase64 ), $decrypted, $privateKey ); | |
echo "This is the decrypted text: $decrypted\n\n"; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment