'How can we do PGP encryption/decryption using RSA in Php?
I have installed GnuPG library and used below code for encryption and decryption:
$public_key = '/path/0xC6235F66-pub.asc';
$private_key = '/path/0xC6235F66-sec.asc';
function encryptText($public_key, $text)
{
// Set GnuPG homedir to /tmp
putenv("GNUPGHOME=/tmp");
$public_key = file_get_contents($public_key);
// Create new GnuPG instance
$gpg = new gnupg();
// Import given public key
$key = $gpg->import($public_key);
// Add imported key for encryption
$gpg->addencryptkey($key['fingerprint']);
// Encrypt the secret to a PGP message
$enc = $gpg->encrypt($text);
// Clear the encryption key
$gpg->clearencryptkeys();
// Return the PGP message
return $enc;
}
function decryptText($private_key, $encryptedText)
{
// Set GnuPG homedir to /tmp
putenv("GNUPGHOME=/tmp");
$private_key = file_get_contents($private_key);
// Create new GnuPG instance
$gpg = new gnupg();
// Import given public key
$key = $gpg->import($private_key);
// Add imported key for encryption
$gpg->addencryptkey($key['fingerprint']);
// Encrypt the secret to a PGP message
$decText = $gpg->decrypt($encryptedText);
// Clear the encryption key
$gpg->clearencryptkeys();
// Return the PGP message
return $decText;
}
$encrypted = encryptText($public_key, $input = 'just an example');
echo 'Encrypted text: '.$encrypted;
$decrypted = decryptText($private_key, $encrypted);
echo 'Decrypted text: '.$decrypted;
echo 'Match: ';
var_dump($input === $decrypted);
Using the above encryptText() function I got the encrypted text but unable to decrypt the same with function decryptText(). As i know, PGP encryption using rsa works with private & public key. I have both the keys in place and using public key for encryption which is giving some encrypted string output but unable to decrypt the encrypted string.
Please help here.
Solution 1:[1]
You should not hard-code the fingerprint. You should also use the private key to decrypt.
function encryptText($public_key, $data)
{
$gpg = gnupg_init();
['fingerprint' => $fingerprint] = gnupg_import($gpg, $public_key);
gnupg_addencryptkey($gpg, $fingerprint);
return base64_encode(gnupg_encrypt($gpg, $data));
}
function decryptText($private_key, $data)
{
$gpg = gnupg_init();
['fingerprint' => $fingerprint] = gnupg_import($gpg, $private_key);
gnupg_addencryptkey($gpg, $fingerprint);
return gnupg_decrypt($gpg, base64_decode($data));
}
print $encrypted = encryptText($public_key, $input = 'just an example');
print $decrypted = decryptText($private_key, $encrypted);
var_dump($input === $decrypted);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ron van der Heijden |
