Skip to content

Instantly share code, notes, and snippets.

@vantezzen
Created July 2, 2018 18:46
Show Gist options
  • Save vantezzen/4b7d492d137fcd5eafbf93bed7224ed3 to your computer and use it in GitHub Desktop.
Save vantezzen/4b7d492d137fcd5eafbf93bed7224ed3 to your computer and use it in GitHub Desktop.
Working example of a simple en- and decryption using the singpolyma/openpgp-php library
<?php
// Encrypt a string using a public key
// $string: String to encrypt
// $key: Public key block to use when encrypting
// return: encrypted, enarmored PGP MESSAGE block
function encrypt($string, $key) {
$key = OpenPGP_Message::parse(OpenPGP::unarmor($key, "PGP PUBLIC KEY BLOCK"));
$data = new OpenPGP_LiteralDataPacket($string, array('format' => 'u', 'filename' => 'stuff.txt'));
$encrypted = OpenPGP_Crypt_Symmetric::encrypt($key, new OpenPGP_Message(array($data)));
$enc = OpenPGP::enarmor($encrypted->to_bytes(), "PGP MESSAGE");
$enc = wordwrap($enc, 64, "\n", 1);
return $enc;
}
// Decrypt an encrypted, armored PGP MESSAGE block
// $encrypted: PGP MESSAGE block to decrypt
// $key: Private key block
// $pass: Password for the private key
// return: Decrypted string
function decrypt($encrypted, $key, $pass) {
$keyEncrypted = OpenPGP_Message::parse(OpenPGP::unarmor($key, 'PGP PRIVATE KEY BLOCK'));
$text = "";
foreach($keyEncrypted as $p) {
if(!($p instanceof OpenPGP_SecretKeyPacket)) continue;
$key = OpenPGP_Crypt_Symmetric::decryptSecretKey($pass, $p);
$msg = OpenPGP_Message::parse(OpenPGP::unarmor($encrypted, 'PGP MESSAGE'));
$decryptor = new OpenPGP_Crypt_RSA($key);
$decrypted = $decryptor->decrypt($msg);
$text = $decrypted->packets[0]->data;
}
return $text;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment