Skip to content

Instantly share code, notes, and snippets.

@veny
Last active February 27, 2021 17:57
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save veny/6c72c7bf89fd464b28c7512d2c472a5e to your computer and use it in GitHub Desktop.
Save veny/6c72c7bf89fd464b28c7512d2c472a5e to your computer and use it in GitHub Desktop.
PHP, RSA, Encrypt/Decrypt
<?php
// generate private/public key as follows:
// > openssl genrsa -out private.pem 2048
// > openssl rsa -in private.pem -outform PEM -pubout -out public.pem
$data = "String to encrypt";
$privKey = openssl_pkey_get_private('file:///path/to/private.pem');
$encryptedData = "";
openssl_private_encrypt($data, $encryptedData, $privKey);
echo 'Encrypted: ' . $encryptedData;
$pubKey = openssl_pkey_get_public('file:///path/to/public.pem');
$decryptedData = "";
openssl_public_decrypt($encryptedData, $decryptedData, $pubKey);
echo "\n---\nDecrypted: " . $decryptedData;
echo "\n[OK]\n";
@seismicza
Copy link

I think you have it backwards sir. Public key is for encryption and private key is for decryption.

@chrishieu
Copy link

it should switch between position of private key and public key

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment