Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to import pgp private key in PHP with gnupg?

I'm need to to sign MD5-hash with previosly generated private key (private.pgp) and passphrase. (for example 123456abc) within php script that running on apache2. I'm using gnupg also.

This is how i'm doing it now:

<?php
 $keyring = "/pubkeys/.gnupg";  //this direcrtory owned by www-data
 putenv("GNUPGHOME=$keyring"); 

 $res = gnupg_init();
 var_dump($res); //for debug

 $info = gnupg_import($res,'private.pgp');
  var_dump($info); //for debug

 ?>

So, gnupg_import() returns me false. Why this is happening? I've also tried to read key from a file in the same dir with this php-script, but had the same error. Please, help.

Thank you.

like image 374
Ivan Vetrov Avatar asked Oct 30 '22 15:10

Ivan Vetrov


2 Answers

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't enter a passphrase).
  4. Export the public key gpg --armor --export [email protected] > public_key.asc
  5. Export the private key gpg --armor --export-secret-keys [email protected] > private_key.asc

After executing steps 4 & 5 above you should have two files private_key.asc and public_key.asc Now 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 text
try{
    $gpg->addencryptKey($fingerprint);
    $ciphertext = $gpg->encrypt($plain_text);
    echo "\n". $ciphertext ."\n";
}
catch(Exception $e){
    die('Error '.$e->getMessage());
}

// decrypt text
try{
    $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

like image 52
Hamfri Avatar answered Nov 01 '22 03:11

Hamfri


The manual is your friend: php.net/manual/en/function.gnupg-import.php The second argument is supposed to be the data, not the filename. – Sammitch

like image 36
Armali Avatar answered Nov 01 '22 04:11

Armali