/** * @param string $serverEncryptKey * @param string $serverSignKey * @throws EncryptionException */ private function init($serverEncryptKey = null, $serverSignKey = null) { $token = $this->sc->getToken(); if ($token instanceof TokenInterface && $token->getUser() instanceof GnuPGUserInterface) { $encryptKey = $token->getUser()->getPublicGnuPGKeyFingerprint() ?: $serverEncryptKey; $signKey = $token->getUser()->getPublicSignGnuPGKeyFingerprint() ?: $serverSignKey; } else { $encryptKey = $serverEncryptKey; $signKey = $serverSignKey; } $this->gpg = new \gnupg(); if (!is_null($encryptKey)) { $this->gpg->addencryptkey($encryptKey); $this->ability |= EncryptionAbility::ENCRYPT; } if (!is_null($signKey)) { $this->gpg->addsignkey($signKey); $this->ability |= EncryptionAbility::SIGN; } if (EncryptionAbility::NONE === $this->ability) { throw EncryptionException::missingConfiguration(); } }
public function encrypt_and_sign_message($recipient_key_id, $plaintext, $signer_key_id, $passphrase) { $this->set_env(); try { $gpg = new gnupg(); // throw exception if error occurs $gpg->seterrormode(gnupg::ERROR_EXCEPTION); $gpg->addencryptkey($recipient_key_id); $gpg->addsignkey($signer_key_id, $passphrase); $cipher_text = $gpg->encryptsign($plaintext); $this->restore_env(); return $cipher_text; } catch (Exception $e) { // restore the envelope $this->restore_env(); // re-throw the exception throw $e; } }
<?php // new class $gnupg = new gnupg(); // not really needed. Clearsign is default $gnupg->setsignmode(gnupg::SIG_MODE_CLEAR); // add key with passphrase 'test' for signing $gnupg->addsignkey("8660281B6051D071D94B5B230549F9DC851566DC", "test"); // sign $signed = $gnupg->sign("just a test"); echo $signed;
/** * GnuPG encrypt a message using the recipient public key and optionally sign * http://devzone.zend.com/article/3753-Using-GnuPG-with-PHP * NOTE: GnuPG must be installed and configured with PHP. * The recipient must be in your public key ring * @param string $recipient Recipient Indentity (e.g. email address) * @param string $message Message to encrypt * @param string $sender Sender Identity * @param string $senderKey Key Sender Secret Key (Only required if signing) * @param boolean $binary Output in binary (non-ASCII armored) * @return string */ public static function _encryptGnuPG($recipient, $message, $sender = FALSE, $senderKey = '', $binary = FALSE) { // Create new GnuPG object $gpg = new \gnupg(); // Set error mode $gpg->seterrormode(\gnupg::ERROR_EXCEPTION); // If binary if ($binary) { // Turn off armored mode $gpg->setarmor(0); } // Add the recipient encryption key $gpg->addencryptkey($recipient); // If there is a sender if ($sender !== FALSE) { // Add signature $gpg->addsignkey($sender, $senderKey); // Return encrypted and signed data return $gpg->encryptsign($message); } // Return encrypted data return $gpg->encrypt($message); }