Assuming that you are on Ubuntu/Debian based operating system this is how I would approach the situation:Install dependencies.
- sudo apt-get update
- sudo apt-get install software-properties-common gnupg gnupg2
- sudo add-apt-repository -y ppa:ondrej/php
- sudo apt-get install php7.4-{gnupg,intl,mbstring,cli,xml}
Steps for creating a simple test script.
- Create a directory called test_pgp
- cd /test_pgp
- Generate OpenPGP keys gpg --full-generate-key (follow the prompt but don'tenter a passphrase).
- Export the public key gpg --armor --export your_email@example.com >public_key.asc
- Export the private key gpg --armor --export-secret-keysyour_email@example.com >private_key.asc
After executing steps 4 & 5 above you should have two files private_key.asc and public_key.ascNow create pgp_example.php file on the same folder and add the following lines of code:
<?php$gpg = new gnupg();$privateAsciiKey = file_get_contents('private_key.asc');$publicAsciiKey = file_get_contents('public_key.asc');/** * import private and public keys */$privateKey = $gpg->import($privateAsciiKey);$publicKey = $gpg->import($publicAsciiKey);$fingerprint = $publicKey['fingerprint'];$passphrase = ''; // empty string because we didn't set a passphrase.$plain_text = "Put Some text to encrypt here";// catch errors$gpg->seterrormode(gnupg::ERROR_EXCEPTION);// encrypt plain texttry{ $gpg->addencryptKey($fingerprint); $ciphertext = $gpg->encrypt($plain_text); echo "\n". $ciphertext ."\n";}catch(Exception $e){ die('Error '.$e->getMessage());}// decrypt texttry{ $gpg->adddecryptkey($fingerprint, $passphrase); $plain_text = $gpg->decrypt($ciphertext); echo "\n". $plain_text ."\n";}catch(Exception $e){ die('Error: '. $e->getMessage());}
To execute this code open terminal and run php pgp_example.php