gnupg_encrypt

(PECL gnupg >= 0.1)

gnupg_encryptChiffre un texte donné

Description

gnupg_encrypt(resource $identifier, string $plaintext): string|false

Chiffre le paramètre plaintext avec les clés qui ont été fixées avec gnupg_addencryptkey auparavant et retourne le texte chiffré.

Liste de paramètres

identifier

L'identifiant gnupg, généré par un appel à la fonction gnupg_init() ou à la fonction gnupg.

plaintext

Le texte à chiffrer.

Valeurs de retour

En cas de succès, cette fonction retourne le texte chiffré. En cas d'échec, cette fonction retourne false.

Exemples

Exemple #1 Exemple avec gnupg_encrypt() (Style procédural)

<?php
$res
= gnupg_init();
gnupg_addencryptkey($res,"8660281B6051D071D94B5B230549F9DC851566DC");
$enc = gnupg_encrypt($res, "juste un test");
echo
$enc;
?>

Exemple #2 Exemple avec gnupg_encrypt() (Style orienté objet)

<?php
$gpg
= new gnupg();
$gpg->addencryptkey("8660281B6051D071D94B5B230549F9DC851566DC");
$enc = $gpg->encrypt("juste un test");
echo
$enc;
?>

add a note add a note

User Contributed Notes 7 notes

up
13
nick johnson
16 years ago
After spending some time trying to get this extension to work, I've found that you have to have the GNUPGHOME environment variable set so that the keychain can be found, and have it set equal to the .gnupg directory itself, not the apache/httpd user's home directory (which is what is shown in dan's example code).  below is an example of this and a simple function I was working on at the time to encrypt a piece of data for storage in a database.

<?php
   
// set the environment so gnupg can find the keyring
   
putenv("GNUPGHOME=/home/apache/.gnupg");

    function
encrypt_string($str,$fingerprint) {
       
$res = gnupg_init();
       
gnupg_addencryptkey($res,$fingerprint);
       
$enc = gnupg_encrypt($res, $str);
        return
$enc;
    }
?>
up
10
Mahbub Kabir
10 years ago
// to generate a key type in gpg --gen-key in the command line
// to export public key gpg --export -a "User Name" > public.key

<?php
putenv
("GNUPGHOME=/tmp");

// it assumes public key exists in the /tmp/keys folder
$publicKey = file_get_contents(getenv('GNUPGHOME') . '/keys/public.key');

   
$gpg = new gnupg();
   
$gpg->seterrormode(gnupg::ERROR_EXCEPTION);
   
$info = $gpg->import($publicKey);
   
$gpg->addencryptkey($info['fingerprint']);

   
$uploadFileContent = file_get_contents('/tmp/file-to-encrypt');
   
$enc = $gpg->encrypt($uploadFileContent);
    echo
$enc

Hope this helps
up
2
emiliocolombo3 at gmail dot com
8 years ago
Examples

Getting Key Information

<?php
putenv
('GNUPGHOME=/home/sender/.gnupg');

// create new GnuPG object
$gpg = new gnupg();

// throw exception if error occurs
$gpg->seterrormode(gnupg::ERROR_EXCEPTION);

// get list of keys containing string 'example'
try {
 
$keys = $gpg->keyinfo('example');
 
print_r($info);
} catch (
Exception $e) {
  echo
'ERROR: ' . $e->getMessage();
}
?>

Encrypt a Simple Mail

<?php
// set path to keyring directory
// set path to keyring directory
putenv('GNUPGHOME=/home/sender/.gnupg');

// create new GnuPG object
$gpg = new gnupg();

// throw exception if error occurs
$gpg->seterrormode(gnupg::ERROR_EXCEPTION);

// recipient's email address
$recipient = 'dgar@example.org';

// plaintext message
$plaintext =
"Dear Dave,\n
  The answer is 42.\n
John"
;

// find key matching email address
// encrypt plaintext message
// display and also write to file
try {
 
$gpg->addencryptkey($recipient);
 
$ciphertext = $gpg->encrypt($plaintext);
  echo
'<pre>' . $ciphertext . '</pre>';
 
file_put_contents('/tmp/ciphertext.gpg', $ciphertext);
} catch (
Exception $e) {
  die(
'ERROR: ' . $e->getMessage());
}
?>

Decryption The Mail

<?php
// set path to keyring directory
putenv('GNUPGHOME=/home/recipient/.gnupg');

// create new GnuPG object
$gpg = new gnupg();

// throw exception if error occurs
$gpg->seterrormode(gnupg::ERROR_EXCEPTION);

// recipient's email address
$recipient = 'dgar@example.org';

// ciphertext message
$ciphertext = file_get_contents('/tmp/ciphertext.gpg');

// register secret key by providing passphrase
// decrypt ciphertext with secret key
// display plaintext message
try {
 
$gpg->adddecryptkey($recipient, 'guessme');
 
$plaintext = $gpg->decrypt($ciphertext);
  echo
'<pre>' . $plaintext . '</pre>';
} catch (
Exception $e) {
  die(
'ERROR: ' . $e->getMessage());
}
?>
up
1
paul at cressbrook dot co dot uk
17 years ago
Hi

I found that the apache or httpd user (or whichever user the webserver is using to run) needed to have write access to the .gnupg directory for the gnupg_php functions to work. This could be your problem.  It seems a rather unsatisfactory feature of this module - gnupg keeps giving warnings that it is unsafe.
up
3
dan at f-box dot org
16 years ago
This is a simple example of a Procedural use of import addencryptkey and encrypt. Obviously in a real world use you would only be importing the key once.

<?php

putenv
("GNUPGHOME=/tmp");
$pubkey = "-----BEGIN PGP PUBLIC KEY BLOCK-----
Version: GnuPG v1.2.6 (GNU/Linux)

mQGiBEe68W8RBACVuFuv4d+roDSCdRO1SuO8dQwds4VTjVOqgVKQtq6+8Fe95RY8
BAf1IyLj4bxvWPhr0wZdVwTosD/sFoPtdCyhVcF932nP0GLHsTEeVwSz9mid22HI
O4Kmwj2kE+I+C9QdzAg0zaWQnVaF9UC7pIdMR6tEnADI8nkVDdZ+zb2ziwCg6Yqu
tk3KAzKRT1SNUzTE/n9y2PED/1tIWiXfGBGzseX0W/e1G+MjuolWOXv4BXeiFGmn
8wnHsQ4Z4Tzk+ag0k+6pZZXjcL6Le486wpZ9MAe6LM31XDpQDVtyCL8t63nvQpB8
TUimbseBZMb3TytCubNLGFe5FnNLGDciElcD09d2xC6Xv6zE2jj4GtBW1bXqYWtl
jm0PA/4u6av6o6pIgLRfAawspr8kaeZ8+FU4NbIiS6xZmBUEQ/o7q95VKGgFVKBi
ugDOlnbgSzBIwSlsRVT2ivu/XVWnhQaRCotSm3AzOc2XecqrJ6F1gqk0n+yP/1h1
yeTvvfS5zgqNTG2UmovjVsKFzaDqmsYZ+sYfwc209z9PY+6FuLQnQXBhY2hlVGVz
dCAoVGVzdGluZykgPGFwYWNoZUBsb2NhbGhvc3Q+iF4EExECAB4FAke68W8CGwMG
CwkIBwMCAxUCAwMWAgECHgECF4AACgkQJE9COu2PFIEGDwCglArzAza13xjbdR04
DQ1U9FWQhMYAnRrWQeGTRm+BYm6SghNpDOKcmMqruQENBEe68XAQBADPIO+JFe5t
BQmI4l60bNMNSUqsL0TtIP8G6Bpd8q2xBOemHCLfGT9Y5DN6k0nneBQxajSfWBQ5
ZdKFwV5ezICz9fnGisEf9LPSwctfUIcvumbcPPsrUOUZX7BuCHrcfy1nebS3myO/
ScTKpW8Wz8AjpKTBG55DMkXSvnx+hS+PEwADBQP/dNnVlKYdNKA70B4QTEzfvF+E
5lyiauyT41SQoheTMhrs/3RIqUy7WWn3B20aTutHWWYXdYV+E85/CarhUmLNZGA2
tml1Mgl6F2myQ/+MiKi/aj9NVhcuz38OK/IAze7kNJJqK+UEWblB2Wfa31/9nNzv
ewVHa1xHtUyVDaewAACISQQYEQIACQUCR7rxcAIbDAAKCRAkT0I67Y8UgRwEAKDT
L6DwyEZGLTpAqy2OLUH7SFKm2ACgr3tnPuPFlBtHx0OqY4gGiNMJHXE=
=jHPH
-----END PGP PUBLIC KEY BLOCK-----"
;

$enc = (null);
$res = gnupg_init();
echo
"gnupg_init RTV = <br/><pre>\n";
var_dump($res);
echo
"</pre>\n";
$rtv = gnupg_import($res, $pubkey);
echo
"gnupg_import RTV = <br/><pre>\n";
var_dump($rtv);
echo
"</pre>\n";
$rtv = gnupg_addencryptkey($res, "C25F29936D9046D73A77DCF8244F423AED8F1481");
echo
"gnupg_addencryptkey RTV = <br /><pre>\n";
var_dump($rtv);
echo
"</pre>\n";
$enc = gnupg_encrypt($res, "just a test to see if anything works");
echo
"Encrypted Data: " . $enc . "<br/>";

?>
up
1
Stressed dev. Permission issue (SELinux)
2 years ago
If you're using CentOS 8 and you're having folder permissions problems, remember to disable SELinux during development. (/etc/selinux/config), just change to disabled or permissive. Then when your project is going live switch it back to enforcing and add the proper se context.
up
-5
jkushner at livemercial dot com
17 years ago
Very nice function, yet I cant seem to get it to work correctly.
Here is what I have..

/**
* Test Values. Will be grabbed from database.
*/
$_STR_recipientKeyId='78F21BCA81042C23';

// This is a wrapper class I made that engulfs the gnupg class
if(!class_exists('core_Gnupg')){
    require(CORE_PATH_CLASS.'Gnupg.class.php');
}

//$_OBJ_gpg is just an instantiation of that class.
//returnInfo takes in the userID name, and uses the keyinfo() //function to return an array of data for that user.
$_ARR_keyinfo=$_OBJ_gpg->returnInfo($_STR_recipientUserId);

//now I have the fully functional userid
//ex: Jonathan Kushner <jkushner@livemercial.com>
$_STR_recipientUserId=$_ARR_keyinfo[0]['uids'][0]['uid'];
    
###########################

See, originally I was using the fingerprint from the $_ARR_keyinfo above and passing that into the encrypt function, but it still associated the encrypted data with my personal private key that I have associated with apache.

Any ideas?
To Top