Quantcast
Channel: User Hamfri - Stack Overflow
Viewing all articles
Browse latest Browse all 42

Answer by Hamfri for How to import pgp private key in PHP with gnupg?

$
0
0

Assuming that you are on Ubuntu/Debian based operating system this is how I would approach the situation:Install dependencies.

  1. sudo apt-get update
  2. sudo apt-get install software-properties-common gnupg gnupg2
  3. sudo add-apt-repository -y ppa:ondrej/php
  4. sudo apt-get install php7.4-{gnupg,intl,mbstring,cli,xml}

Steps for creating a simple test script.

  1. Create a directory called test_pgp
  2. cd /test_pgp
  3. Generate OpenPGP keys gpg --full-generate-key (follow the prompt but don'tenter a passphrase).
  4. Export the public key gpg --armor --export your_email@example.com >public_key.asc
  5. 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


Viewing all articles
Browse latest Browse all 42

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>