12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516 |
- <?php
-
- /* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
-
- /**
- * Crypt_GPG is a package to use GPG from PHP
- *
- * This package provides an object oriented interface to GNU Privacy
- * Guard (GPG). It requires the GPG executable to be on the system.
- *
- * Though GPG can support symmetric-key cryptography, this package is intended
- * only to facilitate public-key cryptography.
- *
- * This file contains the main GPG class. The class in this file lets you
- * encrypt, decrypt, sign and verify data; import and delete keys; and perform
- * other useful GPG tasks.
- *
- * Example usage:
- * <code>
- * <?php
- * // encrypt some data
- * $gpg = new Crypt_GPG();
- * $gpg->addEncryptKey($mySecretKeyId);
- * $encryptedData = $gpg->encrypt($data);
- * ?>
- * </code>
- *
- * PHP version 5
- *
- * LICENSE:
- *
- * This library is free software; you can redistribute it and/or modify
- * it under the terms of the GNU Lesser General Public License as
- * published by the Free Software Foundation; either version 2.1 of the
- * License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, see
- * <http://www.gnu.org/licenses/>
- *
- * @category Encryption
- * @package Crypt_GPG
- * @author Nathan Fredrickson <nathan@silverorange.com>
- * @author Michael Gauthier <mike@silverorange.com>
- * @copyright 2005-2013 silverorange
- * @license http://www.gnu.org/copyleft/lesser.html LGPL License 2.1
- * @version CVS: $Id$
- * @link http://pear.php.net/package/Crypt_GPG
- * @link http://pear.php.net/manual/en/package.encryption.crypt-gpg.php
- * @link http://www.gnupg.org/
- */
-
- /**
- * Base class for GPG methods
- */
- require_once 'Crypt/GPGAbstract.php';
-
- /**
- * Signature handler class
- */
- require_once 'Crypt/GPG/VerifyStatusHandler.php';
-
- /**
- * Decryption handler class
- */
- require_once 'Crypt/GPG/DecryptStatusHandler.php';
-
- /**
- * Information about a created signature
- */
- require_once 'Crypt/GPG/SignatureCreationInfo.php';
-
- // {{{ class Crypt_GPG
-
- /**
- * A class to use GPG from PHP
- *
- * This class provides an object oriented interface to GNU Privacy Guard (GPG).
- *
- * Though GPG can support symmetric-key cryptography, this class is intended
- * only to facilitate public-key cryptography.
- *
- * @category Encryption
- * @package Crypt_GPG
- * @author Nathan Fredrickson <nathan@silverorange.com>
- * @author Michael Gauthier <mike@silverorange.com>
- * @copyright 2005-2013 silverorange
- * @license http://www.gnu.org/copyleft/lesser.html LGPL License 2.1
- * @link http://pear.php.net/package/Crypt_GPG
- * @link http://www.gnupg.org/
- */
- class Crypt_GPG extends Crypt_GPGAbstract
- {
- // {{{ class constants for data signing modes
-
- /**
- * Signing mode for normal signing of data. The signed message will not
- * be readable without special software.
- *
- * This is the default signing mode.
- *
- * @see Crypt_GPG::sign()
- * @see Crypt_GPG::signFile()
- */
- const SIGN_MODE_NORMAL = 1;
-
- /**
- * Signing mode for clearsigning data. Clearsigned signatures are ASCII
- * armored data and are readable without special software. If the signed
- * message is unencrypted, the message will still be readable. The message
- * text will be in the original encoding.
- *
- * @see Crypt_GPG::sign()
- * @see Crypt_GPG::signFile()
- */
- const SIGN_MODE_CLEAR = 2;
-
- /**
- * Signing mode for creating a detached signature. When using detached
- * signatures, only the signature data is returned. The original message
- * text may be distributed separately from the signature data. This is
- * useful for miltipart/signed email messages as per
- * {@link http://www.ietf.org/rfc/rfc3156.txt RFC 3156}.
- *
- * @see Crypt_GPG::sign()
- * @see Crypt_GPG::signFile()
- */
- const SIGN_MODE_DETACHED = 3;
-
- // }}}
- // {{{ class constants for fingerprint formats
-
- /**
- * No formatting is performed.
- *
- * Example: C3BC615AD9C766E5A85C1F2716D27458B1BBA1C4
- *
- * @see Crypt_GPG::getFingerprint()
- */
- const FORMAT_NONE = 1;
-
- /**
- * Fingerprint is formatted in the format used by the GnuPG gpg command's
- * default output.
- *
- * Example: C3BC 615A D9C7 66E5 A85C 1F27 16D2 7458 B1BB A1C4
- *
- * @see Crypt_GPG::getFingerprint()
- */
- const FORMAT_CANONICAL = 2;
-
- /**
- * Fingerprint is formatted in the format used when displaying X.509
- * certificates
- *
- * Example: C3:BC:61:5A:D9:C7:66:E5:A8:5C:1F:27:16:D2:74:58:B1:BB:A1:C4
- *
- * @see Crypt_GPG::getFingerprint()
- */
- const FORMAT_X509 = 3;
-
- // }}}
- // {{{ class constants for boolean options
-
- /**
- * Use to specify ASCII armored mode for returned data
- */
- const ARMOR_ASCII = true;
-
- /**
- * Use to specify binary mode for returned data
- */
- const ARMOR_BINARY = false;
-
- /**
- * Use to specify that line breaks in signed text should be normalized
- */
- const TEXT_NORMALIZED = true;
-
- /**
- * Use to specify that line breaks in signed text should not be normalized
- */
- const TEXT_RAW = false;
-
- // }}}
- // {{{ protected class properties
-
- /**
- * Engine used to control the GPG subprocess
- *
- * @var Crypt_GPG_Engine
- *
- * @see Crypt_GPG::setEngine()
- */
- protected $engine = null;
-
- /**
- * Keys used to encrypt
- *
- * The array is of the form:
- * <code>
- * array(
- * $key_id => array(
- * 'fingerprint' => $fingerprint,
- * 'passphrase' => null
- * )
- * );
- * </code>
- *
- * @var array
- * @see Crypt_GPG::addEncryptKey()
- * @see Crypt_GPG::clearEncryptKeys()
- */
- protected $encryptKeys = array();
-
- /**
- * Keys used to decrypt
- *
- * The array is of the form:
- * <code>
- * array(
- * $key_id => array(
- * 'fingerprint' => $fingerprint,
- * 'passphrase' => $passphrase
- * )
- * );
- * </code>
- *
- * @var array
- * @see Crypt_GPG::addSignKey()
- * @see Crypt_GPG::clearSignKeys()
- */
- protected $signKeys = array();
-
- /**
- * Keys used to sign
- *
- * The array is of the form:
- * <code>
- * array(
- * $key_id => array(
- * 'fingerprint' => $fingerprint,
- * 'passphrase' => $passphrase
- * )
- * );
- * </code>
- *
- * @var array
- * @see Crypt_GPG::addDecryptKey()
- * @see Crypt_GPG::clearDecryptKeys()
- */
- protected $decryptKeys = array();
-
- /**
- * Information about the last signature that was generated.
- * A string (line) beginning with "SIG_CREATED "
- *
- * @see handleSignStatus()
- * @var string
- */
- protected $lastSignatureInfo = null;
-
- // }}}
- // {{{ importKey()
-
- /**
- * Imports a public or private key into the keyring
- *
- * Keys may be removed from the keyring using
- * {@link Crypt_GPG::deletePublicKey()} or
- * {@link Crypt_GPG::deletePrivateKey()}.
- *
- * @param string $data the key data to be imported.
- *
- * @return array an associative array containing the following elements:
- * - <kbd>fingerprint</kbd> - the fingerprint of the
- * imported key,
- * - <kbd>public_imported</kbd> - the number of public
- * keys imported,
- * - <kbd>public_unchanged</kbd> - the number of unchanged
- * public keys,
- * - <kbd>private_imported</kbd> - the number of private
- * keys imported,
- * - <kbd>private_unchanged</kbd> - the number of unchanged
- * private keys.
- *
- * @throws Crypt_GPG_NoDataException if the key data is missing or if the
- * data is is not valid key data.
- *
- * @throws Crypt_GPG_Exception if an unknown or unexpected error occurs.
- * Use the <kbd>debug</kbd> option and file a bug report if these
- * exceptions occur.
- */
- public function importKey($data)
- {
- return $this->_importKey($data, false);
- }
-
- // }}}
- // {{{ importKeyFile()
-
- /**
- * Imports a public or private key file into the keyring
- *
- * Keys may be removed from the keyring using
- * {@link Crypt_GPG::deletePublicKey()} or
- * {@link Crypt_GPG::deletePrivateKey()}.
- *
- * @param string $filename the key file to be imported.
- *
- * @return array an associative array containing the following elements:
- * - <kbd>fingerprint</kbd> - the fingerprint of the
- * imported key,
- * - <kbd>public_imported</kbd> - the number of public
- * keys imported,
- * - <kbd>public_unchanged</kbd> - the number of unchanged
- * public keys,
- * - <kbd>private_imported</kbd> - the number of private
- * keys imported,
- * - <kbd>private_unchanged</kbd> - the number of unchanged
- * private keys.
- * private keys.
- *
- * @throws Crypt_GPG_NoDataException if the key data is missing or if the
- * data is is not valid key data.
- *
- * @throws Crypt_GPG_FileException if the key file is not readable.
- *
- * @throws Crypt_GPG_Exception if an unknown or unexpected error occurs.
- * Use the <kbd>debug</kbd> option and file a bug report if these
- * exceptions occur.
- */
- public function importKeyFile($filename)
- {
- return $this->_importKey($filename, true);
- }
-
- // }}}
- // {{{ exportPrivateKey()
-
- /**
- * Exports a private key from the keyring
- *
- * The exported key remains on the keyring. To delete the key, use
- * {@link Crypt_GPG::deletePrivateKey()}.
- *
- * If more than one key fingerprint is available for the specified
- * <kbd>$keyId</kbd> (for example, if you use a non-unique uid) only the
- * first private key is exported.
- *
- * @param string $keyId either the full uid of the private key, the email
- * part of the uid of the private key or the key id of
- * the private key. For example,
- * "Test User (example) <test@example.com>",
- * "test@example.com" or a hexadecimal string.
- * @param boolean $armor optional. If true, ASCII armored data is returned;
- * otherwise, binary data is returned. Defaults to
- * true.
- *
- * @return string the private key data.
- *
- * @throws Crypt_GPG_KeyNotFoundException if a private key with the given
- * <kbd>$keyId</kbd> is not found.
- *
- * @throws Crypt_GPG_Exception if an unknown or unexpected error occurs.
- * Use the <kbd>debug</kbd> option and file a bug report if these
- * exceptions occur.
- */
- public function exportPrivateKey($keyId, $armor = true)
- {
- return $this->_exportKey($keyId, $armor, true);
- }
-
- // }}}
- // {{{ exportPublicKey()
-
- /**
- * Exports a public key from the keyring
- *
- * The exported key remains on the keyring. To delete the public key, use
- * {@link Crypt_GPG::deletePublicKey()}.
- *
- * If more than one key fingerprint is available for the specified
- * <kbd>$keyId</kbd> (for example, if you use a non-unique uid) only the
- * first public key is exported.
- *
- * @param string $keyId either the full uid of the public key, the email
- * part of the uid of the public key or the key id of
- * the public key. For example,
- * "Test User (example) <test@example.com>",
- * "test@example.com" or a hexadecimal string.
- * @param boolean $armor optional. If true, ASCII armored data is returned;
- * otherwise, binary data is returned. Defaults to
- * true.
- *
- * @return string the public key data.
- *
- * @throws Crypt_GPG_KeyNotFoundException if a public key with the given
- * <kbd>$keyId</kbd> is not found.
- *
- * @throws Crypt_GPG_Exception if an unknown or unexpected error occurs.
- * Use the <kbd>debug</kbd> option and file a bug report if these
- * exceptions occur.
- */
- public function exportPublicKey($keyId, $armor = true)
- {
- return $this->_exportKey($keyId, $armor, false);
- }
-
- // }}}
- // {{{ deletePublicKey()
-
- /**
- * Deletes a public key from the keyring
- *
- * If more than one key fingerprint is available for the specified
- * <kbd>$keyId</kbd> (for example, if you use a non-unique uid) only the
- * first public key is deleted.
- *
- * The private key must be deleted first or an exception will be thrown.
- * See {@link Crypt_GPG::deletePrivateKey()}.
- *
- * @param string $keyId either the full uid of the public key, the email
- * part of the uid of the public key or the key id of
- * the public key. For example,
- * "Test User (example) <test@example.com>",
- * "test@example.com" or a hexadecimal string.
- *
- * @return void
- *
- * @throws Crypt_GPG_KeyNotFoundException if a public key with the given
- * <kbd>$keyId</kbd> is not found.
- *
- * @throws Crypt_GPG_DeletePrivateKeyException if the specified public key
- * has an associated private key on the keyring. The private key
- * must be deleted first.
- *
- * @throws Crypt_GPG_Exception if an unknown or unexpected error occurs.
- * Use the <kbd>debug</kbd> option and file a bug report if these
- * exceptions occur.
- */
- public function deletePublicKey($keyId)
- {
- $fingerprint = $this->getFingerprint($keyId);
-
- if ($fingerprint === null) {
- throw new Crypt_GPG_KeyNotFoundException(
- 'Public key not found: ' . $keyId,
- self::ERROR_KEY_NOT_FOUND,
- $keyId
- );
- }
-
- $operation = '--delete-key ' . escapeshellarg($fingerprint);
- $arguments = array(
- '--batch',
- '--yes'
- );
-
- $this->engine->reset();
- $this->engine->setOperation($operation, $arguments);
- $this->engine->run();
-
- $code = $this->engine->getErrorCode();
-
- switch ($code) {
- case self::ERROR_NONE:
- break;
- case self::ERROR_DELETE_PRIVATE_KEY:
- throw new Crypt_GPG_DeletePrivateKeyException(
- 'Private key must be deleted before public key can be ' .
- 'deleted.',
- $code,
- $keyId
- );
- default:
- throw new Crypt_GPG_Exception(
- 'Unknown error deleting public key. Please use the ' .
- '\'debug\' option when creating the Crypt_GPG object, and ' .
- 'file a bug report at ' . self::BUG_URI,
- $code
- );
- }
- }
-
- // }}}
- // {{{ deletePrivateKey()
-
- /**
- * Deletes a private key from the keyring
- *
- * If more than one key fingerprint is available for the specified
- * <kbd>$keyId</kbd> (for example, if you use a non-unique uid) only the
- * first private key is deleted.
- *
- * Calls GPG with the <kbd>--delete-secret-key</kbd> command.
- *
- * @param string $keyId either the full uid of the private key, the email
- * part of the uid of the private key or the key id of
- * the private key. For example,
- * "Test User (example) <test@example.com>",
- * "test@example.com" or a hexadecimal string.
- *
- * @return void
- *
- * @throws Crypt_GPG_KeyNotFoundException if a private key with the given
- * <kbd>$keyId</kbd> is not found.
- *
- * @throws Crypt_GPG_Exception if an unknown or unexpected error occurs.
- * Use the <kbd>debug</kbd> option and file a bug report if these
- * exceptions occur.
- */
- public function deletePrivateKey($keyId)
- {
- $fingerprint = $this->getFingerprint($keyId);
-
- if ($fingerprint === null) {
- throw new Crypt_GPG_KeyNotFoundException(
- 'Private key not found: ' . $keyId,
- self::ERROR_KEY_NOT_FOUND,
- $keyId
- );
- }
-
- $operation = '--delete-secret-key ' . escapeshellarg($fingerprint);
- $arguments = array(
- '--batch',
- '--yes'
- );
-
- $this->engine->reset();
- $this->engine->setOperation($operation, $arguments);
- $this->engine->run();
-
- $code = $this->engine->getErrorCode();
-
- switch ($code) {
- case self::ERROR_NONE:
- break;
- case self::ERROR_KEY_NOT_FOUND:
- throw new Crypt_GPG_KeyNotFoundException(
- 'Private key not found: ' . $keyId,
- $code,
- $keyId
- );
- default:
- throw new Crypt_GPG_Exception(
- 'Unknown error deleting private key. Please use the ' .
- '\'debug\' option when creating the Crypt_GPG object, and ' .
- 'file a bug report at ' . self::BUG_URI,
- $code
- );
- }
- }
-
- // }}}
- // {{{ getKeys()
-
- /**
- * Gets the available keys in the keyring
- *
- * Calls GPG with the <kbd>--list-keys</kbd> command and grabs keys. See
- * the first section of <b>doc/DETAILS</b> in the
- * {@link http://www.gnupg.org/download/ GPG package} for a detailed
- * description of how the GPG command output is parsed.
- *
- * @param string $keyId optional. Only keys with that match the specified
- * pattern are returned. The pattern may be part of
- * a user id, a key id or a key fingerprint. If not
- * specified, all keys are returned.
- *
- * @return array an array of {@link Crypt_GPG_Key} objects. If no keys
- * match the specified <kbd>$keyId</kbd> an empty array is
- * returned.
- *
- * @throws Crypt_GPG_Exception if an unknown or unexpected error occurs.
- * Use the <kbd>debug</kbd> option and file a bug report if these
- * exceptions occur.
- *
- * @see Crypt_GPG_Key
- */
- public function getKeys($keyId = '')
- {
- return parent::_getKeys($keyId);
- }
-
- // }}}
- // {{{ getFingerprint()
-
- /**
- * Gets a key fingerprint from the keyring
- *
- * If more than one key fingerprint is available (for example, if you use
- * a non-unique user id) only the first key fingerprint is returned.
- *
- * Calls the GPG <kbd>--list-keys</kbd> command with the
- * <kbd>--with-fingerprint</kbd> option to retrieve a public key
- * fingerprint.
- *
- * @param string $keyId either the full user id of the key, the email
- * part of the user id of the key, or the key id of
- * the key. For example,
- * "Test User (example) <test@example.com>",
- * "test@example.com" or a hexadecimal string.
- * @param integer $format optional. How the fingerprint should be formatted.
- * Use {@link Crypt_GPG::FORMAT_X509} for X.509
- * certificate format,
- * {@link Crypt_GPG::FORMAT_CANONICAL} for the format
- * used by GnuPG output and
- * {@link Crypt_GPG::FORMAT_NONE} for no formatting.
- * Defaults to <code>Crypt_GPG::FORMAT_NONE</code>.
- *
- * @return string the fingerprint of the key, or null if no fingerprint
- * is found for the given <kbd>$keyId</kbd>.
- *
- * @throws Crypt_GPG_Exception if an unknown or unexpected error occurs.
- * Use the <kbd>debug</kbd> option and file a bug report if these
- * exceptions occur.
- */
- public function getFingerprint($keyId, $format = self::FORMAT_NONE)
- {
- $output = '';
- $operation = '--list-keys ' . escapeshellarg($keyId);
- $arguments = array(
- '--with-colons',
- '--with-fingerprint'
- );
-
- $this->engine->reset();
- $this->engine->setOutput($output);
- $this->engine->setOperation($operation, $arguments);
- $this->engine->run();
-
- $code = $this->engine->getErrorCode();
-
- switch ($code) {
- case self::ERROR_NONE:
- case self::ERROR_KEY_NOT_FOUND:
- // ignore not found key errors
- break;
- default:
- throw new Crypt_GPG_Exception(
- 'Unknown error getting key fingerprint. Please use the ' .
- '\'debug\' option when creating the Crypt_GPG object, and ' .
- 'file a bug report at ' . self::BUG_URI,
- $code
- );
- }
-
- $fingerprint = null;
-
- $lines = explode(PHP_EOL, $output);
- foreach ($lines as $line) {
- if (substr($line, 0, 3) == 'fpr') {
- $lineExp = explode(':', $line);
- $fingerprint = $lineExp[9];
-
- switch ($format) {
- case self::FORMAT_CANONICAL:
- $fingerprintExp = str_split($fingerprint, 4);
- $format = '%s %s %s %s %s %s %s %s %s %s';
- $fingerprint = vsprintf($format, $fingerprintExp);
- break;
-
- case self::FORMAT_X509:
- $fingerprintExp = str_split($fingerprint, 2);
- $fingerprint = implode(':', $fingerprintExp);
- break;
- }
-
- break;
- }
- }
-
- return $fingerprint;
- }
-
- // }}}
- // {{{ getLastSignatureInfo()
-
- /**
- * Get information about the last signature that was created.
- *
- * @return Crypt_GPG_SignatureCreationInfo
- */
- public function getLastSignatureInfo()
- {
- if ($this->lastSignatureInfo === null) {
- return null;
- }
- return new Crypt_GPG_SignatureCreationInfo($this->lastSignatureInfo);
- }
- // }}}
- // {{{ encrypt()
-
- /**
- * Encrypts string data
- *
- * Data is ASCII armored by default but may optionally be returned as
- * binary.
- *
- * @param string $data the data to be encrypted.
- * @param boolean $armor optional. If true, ASCII armored data is returned;
- * otherwise, binary data is returned. Defaults to
- * true.
- *
- * @return string the encrypted data.
- *
- * @throws Crypt_GPG_KeyNotFoundException if no encryption key is specified.
- * See {@link Crypt_GPG::addEncryptKey()}.
- *
- * @throws Crypt_GPG_Exception if an unknown or unexpected error occurs.
- * Use the <kbd>debug</kbd> option and file a bug report if these
- * exceptions occur.
- *
- * @sensitive $data
- */
- public function encrypt($data, $armor = self::ARMOR_ASCII)
- {
- return $this->_encrypt($data, false, null, $armor);
- }
-
- // }}}
- // {{{ encryptFile()
-
- /**
- * Encrypts a file
- *
- * Encrypted data is ASCII armored by default but may optionally be saved
- * as binary.
- *
- * @param string $filename the filename of the file to encrypt.
- * @param string $encryptedFile optional. The filename of the file in
- * which to store the encrypted data. If null
- * or unspecified, the encrypted data is
- * returned as a string.
- * @param boolean $armor optional. If true, ASCII armored data is
- * returned; otherwise, binary data is
- * returned. Defaults to true.
- *
- * @return void|string if the <kbd>$encryptedFile</kbd> parameter is null,
- * a string containing the encrypted data is returned.
- *
- * @throws Crypt_GPG_KeyNotFoundException if no encryption key is specified.
- * See {@link Crypt_GPG::addEncryptKey()}.
- *
- * @throws Crypt_GPG_FileException if the output file is not writeable or
- * if the input file is not readable.
- *
- * @throws Crypt_GPG_Exception if an unknown or unexpected error occurs.
- * Use the <kbd>debug</kbd> option and file a bug report if these
- * exceptions occur.
- */
- public function encryptFile(
- $filename,
- $encryptedFile = null,
- $armor = self::ARMOR_ASCII
- ) {
- return $this->_encrypt($filename, true, $encryptedFile, $armor);
- }
-
- // }}}
- // {{{ encryptAndSign()
-
- /**
- * Encrypts and signs data
- *
- * Data is encrypted and signed in a single pass.
- *
- * NOTE: Until GnuPG version 1.4.10, it was not possible to verify
- * encrypted-signed data without decrypting it at the same time. If you try
- * to use {@link Crypt_GPG::verify()} method on encrypted-signed data with
- * earlier GnuPG versions, you will get an error. Please use
- * {@link Crypt_GPG::decryptAndVerify()} to verify encrypted-signed data.
- *
- * @param string $data the data to be encrypted and signed.
- * @param boolean $armor optional. If true, ASCII armored data is returned;
- * otherwise, binary data is returned. Defaults to
- * true.
- *
- * @return string the encrypted signed data.
- *
- * @throws Crypt_GPG_KeyNotFoundException if no encryption key is specified
- * or if no signing key is specified. See
- * {@link Crypt_GPG::addEncryptKey()} and
- * {@link Crypt_GPG::addSignKey()}.
- *
- * @throws Crypt_GPG_BadPassphraseException if a specified passphrase is
- * incorrect or if a required passphrase is not specified.
- *
- * @throws Crypt_GPG_Exception if an unknown or unexpected error occurs.
- * Use the <kbd>debug</kbd> option and file a bug report if these
- * exceptions occur.
- *
- * @see Crypt_GPG::decryptAndVerify()
- */
- public function encryptAndSign($data, $armor = self::ARMOR_ASCII)
- {
- return $this->_encryptAndSign($data, false, null, $armor);
- }
-
- // }}}
- // {{{ encryptAndSignFile()
-
- /**
- * Encrypts and signs a file
- *
- * The file is encrypted and signed in a single pass.
- *
- * NOTE: Until GnuPG version 1.4.10, it was not possible to verify
- * encrypted-signed files without decrypting them at the same time. If you
- * try to use {@link Crypt_GPG::verify()} method on encrypted-signed files
- * with earlier GnuPG versions, you will get an error. Please use
- * {@link Crypt_GPG::decryptAndVerifyFile()} to verify encrypted-signed
- * files.
- *
- * @param string $filename the name of the file containing the data to
- * be encrypted and signed.
- * @param string $signedFile optional. The name of the file in which the
- * encrypted, signed data should be stored. If
- * null or unspecified, the encrypted, signed
- * data is returned as a string.
- * @param boolean $armor optional. If true, ASCII armored data is
- * returned; otherwise, binary data is returned.
- * Defaults to true.
- *
- * @return void|string if the <kbd>$signedFile</kbd> parameter is null, a
- * string containing the encrypted, signed data is
- * returned.
- *
- * @throws Crypt_GPG_KeyNotFoundException if no encryption key is specified
- * or if no signing key is specified. See
- * {@link Crypt_GPG::addEncryptKey()} and
- * {@link Crypt_GPG::addSignKey()}.
- *
- * @throws Crypt_GPG_BadPassphraseException if a specified passphrase is
- * incorrect or if a required passphrase is not specified.
- *
- * @throws Crypt_GPG_FileException if the output file is not writeable or
- * if the input file is not readable.
- *
- * @throws Crypt_GPG_Exception if an unknown or unexpected error occurs.
- * Use the <kbd>debug</kbd> option and file a bug report if these
- * exceptions occur.
- *
- * @see Crypt_GPG::decryptAndVerifyFile()
- */
- public function encryptAndSignFile(
- $filename,
- $signedFile = null,
- $armor = self::ARMOR_ASCII
- ) {
- return $this->_encryptAndSign($filename, true, $signedFile, $armor);
- }
-
- // }}}
- // {{{ decrypt()
-
- /**
- * Decrypts string data
- *
- * This method assumes the required private key is available in the keyring
- * and throws an exception if the private key is not available. To add a
- * private key to the keyring, use the {@link Crypt_GPG::importKey()} or
- * {@link Crypt_GPG::importKeyFile()} methods.
- *
- * @param string $encryptedData the data to be decrypted.
- *
- * @return string the decrypted data.
- *
- * @throws Crypt_GPG_KeyNotFoundException if the private key needed to
- * decrypt the data is not in the user's keyring.
- *
- * @throws Crypt_GPG_NoDataException if specified data does not contain
- * GPG encrypted data.
- *
- * @throws Crypt_GPG_BadPassphraseException if a required passphrase is
- * incorrect or if a required passphrase is not specified. See
- * {@link Crypt_GPG::addDecryptKey()}.
- *
- * @throws Crypt_GPG_Exception if an unknown or unexpected error occurs.
- * Use the <kbd>debug</kbd> option and file a bug report if these
- * exceptions occur.
- */
- public function decrypt($encryptedData)
- {
- return $this->_decrypt($encryptedData, false, null);
- }
-
- // }}}
- // {{{ decryptFile()
-
- /**
- * Decrypts a file
- *
- * This method assumes the required private key is available in the keyring
- * and throws an exception if the private key is not available. To add a
- * private key to the keyring, use the {@link Crypt_GPG::importKey()} or
- * {@link Crypt_GPG::importKeyFile()} methods.
- *
- * @param string $encryptedFile the name of the encrypted file data to
- * decrypt.
- * @param string $decryptedFile optional. The name of the file to which the
- * decrypted data should be written. If null
- * or unspecified, the decrypted data is
- * returned as a string.
- *
- * @return void|string if the <kbd>$decryptedFile</kbd> parameter is null,
- * a string containing the decrypted data is returned.
- *
- * @throws Crypt_GPG_KeyNotFoundException if the private key needed to
- * decrypt the data is not in the user's keyring.
- *
- * @throws Crypt_GPG_NoDataException if specified data does not contain
- * GPG encrypted data.
- *
- * @throws Crypt_GPG_BadPassphraseException if a required passphrase is
- * incorrect or if a required passphrase is not specified. See
- * {@link Crypt_GPG::addDecryptKey()}.
- *
- * @throws Crypt_GPG_FileException if the output file is not writeable or
- * if the input file is not readable.
- *
- * @throws Crypt_GPG_Exception if an unknown or unexpected error occurs.
- * Use the <kbd>debug</kbd> option and file a bug report if these
- * exceptions occur.
- */
- public function decryptFile($encryptedFile, $decryptedFile = null)
- {
- return $this->_decrypt($encryptedFile, true, $decryptedFile);
- }
-
- // }}}
- // {{{ decryptAndVerify()
-
- /**
- * Decrypts and verifies string data
- *
- * This method assumes the required private key is available in the keyring
- * and throws an exception if the private key is not available. To add a
- * private key to the keyring, use the {@link Crypt_GPG::importKey()} or
- * {@link Crypt_GPG::importKeyFile()} methods.
- *
- * @param string $encryptedData the encrypted, signed data to be decrypted
- * and verified.
- *
- * @return array two element array. The array has an element 'data'
- * containing the decrypted data and an element
- * 'signatures' containing an array of
- * {@link Crypt_GPG_Signature} objects for the signed data.
- *
- * @throws Crypt_GPG_KeyNotFoundException if the private key needed to
- * decrypt the data is not in the user's keyring.
- *
- * @throws Crypt_GPG_NoDataException if specified data does not contain
- * GPG encrypted data.
- *
- * @throws Crypt_GPG_BadPassphraseException if a required passphrase is
- * incorrect or if a required passphrase is not specified. See
- * {@link Crypt_GPG::addDecryptKey()}.
- *
- * @throws Crypt_GPG_Exception if an unknown or unexpected error occurs.
- * Use the <kbd>debug</kbd> option and file a bug report if these
- * exceptions occur.
- */
- public function decryptAndVerify($encryptedData)
- {
- return $this->_decryptAndVerify($encryptedData, false, null);
- }
-
- // }}}
- // {{{ decryptAndVerifyFile()
-
- /**
- * Decrypts and verifies a signed, encrypted file
- *
- * This method assumes the required private key is available in the keyring
- * and throws an exception if the private key is not available. To add a
- * private key to the keyring, use the {@link Crypt_GPG::importKey()} or
- * {@link Crypt_GPG::importKeyFile()} methods.
- *
- * @param string $encryptedFile the name of the signed, encrypted file to
- * to decrypt and verify.
- * @param string $decryptedFile optional. The name of the file to which the
- * decrypted data should be written. If null
- * or unspecified, the decrypted data is
- * returned in the results array.
- *
- * @return array two element array. The array has an element 'data'
- * containing the decrypted data and an element
- * 'signatures' containing an array of
- * {@link Crypt_GPG_Signature} objects for the signed data.
- * If the decrypted data is written to a file, the 'data'
- * element is null.
- *
- * @throws Crypt_GPG_KeyNotFoundException if the private key needed to
- * decrypt the data is not in the user's keyring.
- *
- * @throws Crypt_GPG_NoDataException if specified data does not contain
- * GPG encrypted data.
- *
- * @throws Crypt_GPG_BadPassphraseException if a required passphrase is
- * incorrect or if a required passphrase is not specified. See
- * {@link Crypt_GPG::addDecryptKey()}.
- *
- * @throws Crypt_GPG_FileException if the output file is not writeable or
- * if the input file is not readable.
- *
- * @throws Crypt_GPG_Exception if an unknown or unexpected error occurs.
- * Use the <kbd>debug</kbd> option and file a bug report if these
- * exceptions occur.
- */
- public function decryptAndVerifyFile($encryptedFile, $decryptedFile = null)
- {
- return $this->_decryptAndVerify($encryptedFile, true, $decryptedFile);
- }
-
- // }}}
- // {{{ sign()
-
- /**
- * Signs data
- *
- * Data may be signed using any one of the three available signing modes:
- * - {@link Crypt_GPG::SIGN_MODE_NORMAL}
- * - {@link Crypt_GPG::SIGN_MODE_CLEAR}
- * - {@link Crypt_GPG::SIGN_MODE_DETACHED}
- *
- * @param string $data the data to be signed.
- * @param boolean $mode optional. The data signing mode to use. Should
- * be one of {@link Crypt_GPG::SIGN_MODE_NORMAL},
- * {@link Crypt_GPG::SIGN_MODE_CLEAR} or
- * {@link Crypt_GPG::SIGN_MODE_DETACHED}. If not
- * specified, defaults to
- * <kbd>Crypt_GPG::SIGN_MODE_NORMAL</kbd>.
- * @param boolean $armor optional. If true, ASCII armored data is
- * returned; otherwise, binary data is returned.
- * Defaults to true. This has no effect if the
- * mode <kbd>Crypt_GPG::SIGN_MODE_CLEAR</kbd> is
- * used.
- * @param boolean $textmode optional. If true, line-breaks in signed data
- * are normalized. Use this option when signing
- * e-mail, or for greater compatibility between
- * systems with different line-break formats.
- * Defaults to false. This has no effect if the
- * mode <kbd>Crypt_GPG::SIGN_MODE_CLEAR</kbd> is
- * used as clear-signing always uses textmode.
- *
- * @return string the signed data, or the signature data if a detached
- * signature is requested.
- *
- * @throws Crypt_GPG_KeyNotFoundException if no signing key is specified.
- * See {@link Crypt_GPG::addSignKey()}.
- *
- * @throws Crypt_GPG_BadPassphraseException if a specified passphrase is
- * incorrect or if a required passphrase is not specified.
- *
- * @throws Crypt_GPG_Exception if an unknown or unexpected error occurs.
- * Use the <kbd>debug</kbd> option and file a bug report if these
- * exceptions occur.
- */
- public function sign(
- $data,
- $mode = self::SIGN_MODE_NORMAL,
- $armor = self::ARMOR_ASCII,
- $textmode = self::TEXT_RAW
- ) {
- return $this->_sign($data, false, null, $mode, $armor, $textmode);
- }
-
- // }}}
- // {{{ signFile()
-
- /**
- * Signs a file
- *
- * The file may be signed using any one of the three available signing
- * modes:
- * - {@link Crypt_GPG::SIGN_MODE_NORMAL}
- * - {@link Crypt_GPG::SIGN_MODE_CLEAR}
- * - {@link Crypt_GPG::SIGN_MODE_DETACHED}
- *
- * @param string $filename the name of the file containing the data to
- * be signed.
- * @param string $signedFile optional. The name of the file in which the
- * signed data should be stored. If null or
- * unspecified, the signed data is returned as a
- * string.
- * @param boolean $mode optional. The data signing mode to use. Should
- * be one of {@link Crypt_GPG::SIGN_MODE_NORMAL},
- * {@link Crypt_GPG::SIGN_MODE_CLEAR} or
- * {@link Crypt_GPG::SIGN_MODE_DETACHED}. If not
- * specified, defaults to
- * <kbd>Crypt_GPG::SIGN_MODE_NORMAL</kbd>.
- * @param boolean $armor optional. If true, ASCII armored data is
- * returned; otherwise, binary data is returned.
- * Defaults to true. This has no effect if the
- * mode <kbd>Crypt_GPG::SIGN_MODE_CLEAR</kbd> is
- * used.
- * @param boolean $textmode optional. If true, line-breaks in signed data
- * are normalized. Use this option when signing
- * e-mail, or for greater compatibility between
- * systems with different line-break formats.
- * Defaults to false. This has no effect if the
- * mode <kbd>Crypt_GPG::SIGN_MODE_CLEAR</kbd> is
- * used as clear-signing always uses textmode.
- *
- * @return void|string if the <kbd>$signedFile</kbd> parameter is null, a
- * string containing the signed data (or the signature
- * data if a detached signature is requested) is
- * returned.
- *
- * @throws Crypt_GPG_KeyNotFoundException if no signing key is specified.
- * See {@link Crypt_GPG::addSignKey()}.
- *
- * @throws Crypt_GPG_BadPassphraseException if a specified passphrase is
- * incorrect or if a required passphrase is not specified.
- *
- * @throws Crypt_GPG_FileException if the output file is not writeable or
- * if the input file is not readable.
- *
- * @throws Crypt_GPG_Exception if an unknown or unexpected error occurs.
- * Use the <kbd>debug</kbd> option and file a bug report if these
- * exceptions occur.
- */
- public function signFile(
- $filename,
- $signedFile = null,
- $mode = self::SIGN_MODE_NORMAL,
- $armor = self::ARMOR_ASCII,
- $textmode = self::TEXT_RAW
- ) {
- return $this->_sign(
- $filename,
- true,
- $signedFile,
- $mode,
- $armor,
- $textmode
- );
- }
-
- // }}}
- // {{{ verify()
-
- /**
- * Verifies signed data
- *
- * The {@link Crypt_GPG::decrypt()} method may be used to get the original
- * message if the signed data is not clearsigned and does not use a
- * detached signature.
- *
- * @param string $signedData the signed data to be verified.
- * @param string $signature optional. If verifying data signed using a
- * detached signature, this must be the detached
- * signature data. The data that was signed is
- * specified in <kbd>$signedData</kbd>.
- *
- * @return array an array of {@link Crypt_GPG_Signature} objects for the
- * signed data. For each signature that is valid, the
- * {@link Crypt_GPG_Signature::isValid()} will return true.
- *
- * @throws Crypt_GPG_NoDataException if the provided data is not signed
- * data.
- *
- * @throws Crypt_GPG_Exception if an unknown or unexpected error occurs.
- * Use the <kbd>debug</kbd> option and file a bug report if these
- * exceptions occur.
- *
- * @see Crypt_GPG_Signature
- */
- public function verify($signedData, $signature = '')
- {
- return $this->_verify($signedData, false, $signature);
- }
-
- // }}}
- // {{{ verifyFile()
-
- /**
- * Verifies a signed file
- *
- * The {@link Crypt_GPG::decryptFile()} method may be used to get the
- * original message if the signed data is not clearsigned and does not use
- * a detached signature.
- *
- * @param string $filename the signed file to be verified.
- * @param string $signature optional. If verifying a file signed using a
- * detached signature, this must be the detached
- * signature data. The file that was signed is
- * specified in <kbd>$filename</kbd>.
- *
- * @return array an array of {@link Crypt_GPG_Signature} objects for the
- * signed data. For each signature that is valid, the
- * {@link Crypt_GPG_Signature::isValid()} will return true.
- *
- * @throws Crypt_GPG_NoDataException if the provided data is not signed
- * data.
- *
- * @throws Crypt_GPG_FileException if the input file is not readable.
- *
- * @throws Crypt_GPG_Exception if an unknown or unexpected error occurs.
- * Use the <kbd>debug</kbd> option and file a bug report if these
- * exceptions occur.
- *
- * @see Crypt_GPG_Signature
- */
- public function verifyFile($filename, $signature = '')
- {
- return $this->_verify($filename, true, $signature);
- }
-
- // }}}
- // {{{ addDecryptKey()
-
- /**
- * Adds a key to use for decryption
- *
- * @param mixed $key the key to use. This may be a key identifier,
- * user id, fingerprint, {@link Crypt_GPG_Key} or
- * {@link Crypt_GPG_SubKey}. The key must be able
- * to encrypt.
- * @param string $passphrase optional. The passphrase of the key required
- * for decryption.
- *
- * @return Crypt_GPG the current object, for fluent interface.
- *
- * @see Crypt_GPG::decrypt()
- * @see Crypt_GPG::decryptFile()
- * @see Crypt_GPG::clearDecryptKeys()
- * @see Crypt_GPG::_addKey()
- * @see Crypt_GPG_DecryptStatusHandler
- *
- * @sensitive $passphrase
- */
- public function addDecryptKey($key, $passphrase = null)
- {
- $this->_addKey($this->decryptKeys, false, false, $key, $passphrase);
- return $this;
- }
-
- // }}}
- // {{{ addEncryptKey()
-
- /**
- * Adds a key to use for encryption
- *
- * @param mixed $key the key to use. This may be a key identifier, user id
- * user id, fingerprint, {@link Crypt_GPG_Key} or
- * {@link Crypt_GPG_SubKey}. The key must be able to
- * encrypt.
- *
- * @return Crypt_GPG the current object, for fluent interface.
- *
- * @see Crypt_GPG::encrypt()
- * @see Crypt_GPG::encryptFile()
- * @see Crypt_GPG::clearEncryptKeys()
- * @see Crypt_GPG::_addKey()
- */
- public function addEncryptKey($key)
- {
- $this->_addKey($this->encryptKeys, true, false, $key);
- return $this;
- }
-
- // }}}
- // {{{ addSignKey()
-
- /**
- * Adds a key to use for signing
- *
- * @param mixed $key the key to use. This may be a key identifier,
- * user id, fingerprint, {@link Crypt_GPG_Key} or
- * {@link Crypt_GPG_SubKey}. The key must be able
- * to sign.
- * @param string $passphrase optional. The passphrase of the key required
- * for signing.
- *
- * @return Crypt_GPG the current object, for fluent interface.
- *
- * @see Crypt_GPG::sign()
- * @see Crypt_GPG::signFile()
- * @see Crypt_GPG::clearSignKeys()
- * @see Crypt_GPG::handleSignStatus()
- * @see Crypt_GPG::_addKey()
- *
- * @sensitive $passphrase
- */
- public function addSignKey($key, $passphrase = null)
- {
- $this->_addKey($this->signKeys, false, true, $key, $passphrase);
- return $this;
- }
-
- // }}}
- // {{{ clearDecryptKeys()
-
- /**
- * Clears all decryption keys
- *
- * @return Crypt_GPG the current object, for fluent interface.
- *
- * @see Crypt_GPG::decrypt()
- * @see Crypt_GPG::addDecryptKey()
- */
- public function clearDecryptKeys()
- {
- $this->decryptKeys = array();
- return $this;
- }
-
- // }}}
- // {{{ clearEncryptKeys()
-
- /**
- * Clears all encryption keys
- *
- * @return Crypt_GPG the current object, for fluent interface.
- *
- * @see Crypt_GPG::encrypt()
- * @see Crypt_GPG::addEncryptKey()
- */
- public function clearEncryptKeys()
- {
- $this->encryptKeys = array();
- return $this;
- }
-
- // }}}
- // {{{ clearSignKeys()
-
- /**
- * Clears all signing keys
- *
- * @return Crypt_GPG the current object, for fluent interface.
- *
- * @see Crypt_GPG::sign()
- * @see Crypt_GPG::addSignKey()
- */
- public function clearSignKeys()
- {
- $this->signKeys = array();
- return $this;
- }
-
- // }}}
- // {{{ handleSignStatus()
-
- /**
- * Handles the status output from GPG for the sign operation
- *
- * This method is responsible for sending the passphrase commands when
- * required by the {@link Crypt_GPG::sign()} method. See <b>doc/DETAILS</b>
- * in the {@link http://www.gnupg.org/download/ GPG distribution} for
- * detailed information on GPG's status output.
- *
- * @param string $line the status line to handle.
- *
- * @return void
- *
- * @see Crypt_GPG::sign()
- */
- public function handleSignStatus($line)
- {
- $tokens = explode(' ', $line);
- switch ($tokens[0]) {
- case 'NEED_PASSPHRASE':
- $subKeyId = $tokens[1];
- if (array_key_exists($subKeyId, $this->signKeys)) {
- $passphrase = $this->signKeys[$subKeyId]['passphrase'];
- $this->engine->sendCommand($passphrase);
- } else {
- $this->engine->sendCommand('');
- }
- break;
- case 'SIG_CREATED':
- $this->lastSignatureInfo = $line;
- break;
- }
- }
-
- // }}}
- // {{{ handleImportKeyStatus()
-
- /**
- * Handles the status output from GPG for the import operation
- *
- * This method is responsible for building the result array that is
- * returned from the {@link Crypt_GPG::importKey()} method. See
- * <b>doc/DETAILS</b> in the
- * {@link http://www.gnupg.org/download/ GPG distribution} for detailed
- * information on GPG's status output.
- *
- * @param string $line the status line to handle.
- * @param array &$result the current result array being processed.
- *
- * @return void
- *
- * @see Crypt_GPG::importKey()
- * @see Crypt_GPG::importKeyFile()
- * @see Crypt_GPG_Engine::addStatusHandler()
- */
- public function handleImportKeyStatus($line, array &$result)
- {
- $tokens = explode(' ', $line);
- switch ($tokens[0]) {
- case 'IMPORT_OK':
- $result['fingerprint'] = $tokens[2];
-
- if (empty($result['fingerprints'])) {
- $result['fingerprints'] = array($tokens[2]);
- } else if (!in_array($tokens[2], $result['fingerprints'])) {
- $result['fingerprints'][] = $tokens[2];
- }
-
- break;
-
- case 'IMPORT_RES':
- $result['public_imported'] = intval($tokens[3]);
- $result['public_unchanged'] = intval($tokens[5]);
- $result['private_imported'] = intval($tokens[11]);
- $result['private_unchanged'] = intval($tokens[12]);
- break;
- }
- }
-
- // }}}
-
- /**
- * Tell if there are encryption keys registered
- *
- * @return boolean True if the data shall be encrypted
- */
- public function hasEncryptKeys()
- {
- return count($this->encryptKeys) > 0;
- }
-
- /**
- * Tell if there are signing keys registered
- *
- * @return boolean True if the data shall be signed
- */
- public function hasSignKeys()
- {
- return count($this->signKeys) > 0;
- }
-
- // {{{ _addKey()
-
- /**
- * Adds a key to one of the internal key arrays
- *
- * This handles resolving full key objects from the provided
- * <kbd>$key</kbd> value.
- *
- * @param array &$array the array to which the key should be added.
- * @param boolean $encrypt whether or not the key must be able to
- * encrypt.
- * @param boolean $sign whether or not the key must be able to sign.
- * @param mixed $key the key to add. This may be a key identifier,
- * user id, fingerprint, {@link Crypt_GPG_Key} or
- * {@link Crypt_GPG_SubKey}.
- * @param string $passphrase optional. The passphrase associated with the
- * key.
- *
- * @return void
- *
- * @sensitive $passphrase
- */
- protected function _addKey(array &$array, $encrypt, $sign, $key,
- $passphrase = null
- ) {
- $subKeys = array();
-
- if (is_scalar($key)) {
- $keys = $this->getKeys($key);
- if (count($keys) == 0) {
- throw new Crypt_GPG_KeyNotFoundException(
- 'Key "' . $key . '" not found.',
- 0,
- $key
- );
- }
- $key = $keys[0];
- }
-
- if ($key instanceof Crypt_GPG_Key) {
- if ($encrypt && !$key->canEncrypt()) {
- throw new InvalidArgumentException(
- 'Key "' . $key . '" cannot encrypt.'
- );
- }
-
- if ($sign && !$key->canSign()) {
- throw new InvalidArgumentException(
- 'Key "' . $key . '" cannot sign.'
- );
- }
-
- foreach ($key->getSubKeys() as $subKey) {
- $canEncrypt = $subKey->canEncrypt();
- $canSign = $subKey->canSign();
- if ( ($encrypt && $sign && $canEncrypt && $canSign)
- || ($encrypt && !$sign && $canEncrypt)
- || (!$encrypt && $sign && $canSign)
- || (!$encrypt && !$sign)
- ) {
- // We add all subkeys that meet the requirements because we
- // were not told which subkey is required.
- $subKeys[] = $subKey;
- }
- }
- } elseif ($key instanceof Crypt_GPG_SubKey) {
- $subKeys[] = $key;
- }
-
- if (count($subKeys) === 0) {
- throw new InvalidArgumentException(
- 'Key "' . $key . '" is not in a recognized format.'
- );
- }
-
- foreach ($subKeys as $subKey) {
- if ($encrypt && !$subKey->canEncrypt()) {
- throw new InvalidArgumentException(
- 'Key "' . $key . '" cannot encrypt.'
- );
- }
-
- if ($sign && !$subKey->canSign()) {
- throw new InvalidArgumentException(
- 'Key "' . $key . '" cannot sign.'
- );
- }
-
- $array[$subKey->getId()] = array(
- 'fingerprint' => $subKey->getFingerprint(),
- 'passphrase' => $passphrase
- );
- }
- }
-
- // }}}
- // {{{ _setPinEntryEnv()
-
- /**
- * Sets the PINENTRY_USER_DATA environment variable with the currently
- * added keys and passphrases
- *
- * Keys and pasphrases are stored as an indexed array of associative
- * arrays that is JSON encoded to a flat string.
- *
- * For GnuPG 2.x this is how passphrases are passed. For GnuPG 1.x the
- * environment variable is set but not used.
- *
- * @param array $keys the internal key array to use.
- *
- * @return void
- */
- protected function _setPinEntryEnv(array $keys)
- {
- $envKeys = array();
- foreach ($keys as $id => $key) {
- $envKeys[] = array(
- 'keyId' => $id,
- 'fingerprint' => $key['fingerprint'],
- 'passphrase' => $key['passphrase']
- );
- }
- $envKeys = json_encode($envKeys);
- $_ENV['PINENTRY_USER_DATA'] = $envKeys;
- }
-
- // }}}
- // {{{ _importKey()
-
- /**
- * Imports a public or private key into the keyring
- *
- * @param string $key the key to be imported.
- * @param boolean $isFile whether or not the input is a filename.
- *
- * @return array an associative array containing the following elements:
- * - <kbd>fingerprint</kbd> - the fingerprint of the
- * imported key,
- * - <kbd>public_imported</kbd> - the number of public
- * keys imported,
- * - <kbd>public_unchanged</kbd> - the number of unchanged
- * public keys,
- * - <kbd>private_imported</kbd> - the number of private
- * keys imported,
- * - <kbd>private_unchanged</kbd> - the number of unchanged
- * private keys.
- *
- * @throws Crypt_GPG_NoDataException if the key data is missing or if the
- * data is is not valid key data.
- *
- * @throws Crypt_GPG_FileException if the key file is not readable.
- *
- * @throws Crypt_GPG_Exception if an unknown or unexpected error occurs.
- * Use the <kbd>debug</kbd> option and file a bug report if these
- * exceptions occur.
- */
- protected function _importKey($key, $isFile)
- {
- $result = array();
-
- if ($isFile) {
- $input = @fopen($key, 'rb');
- if ($input === false) {
- throw new Crypt_GPG_FileException(
- 'Could not open key file "' . $key . '" for importing.',
- 0,
- $key
- );
- }
- } else {
- $input = strval($key);
- if ($input == '') {
- throw new Crypt_GPG_NoDataException(
- 'No valid GPG key data found.',
- self::ERROR_NO_DATA
- );
- }
- }
-
- $arguments = array();
- $version = $this->engine->getVersion();
-
- if ( version_compare($version, '1.0.5', 'ge')
- && version_compare($version, '1.0.7', 'lt')
- ) {
- $arguments[] = '--allow-secret-key-import';
- }
-
- $this->engine->reset();
- $this->engine->addStatusHandler(
- array($this, 'handleImportKeyStatus'),
- array(&$result)
- );
-
- $this->engine->setOperation('--import', $arguments);
- $this->engine->setInput($input);
- $this->engine->run();
-
- if ($isFile) {
- fclose($input);
- }
-
- $code = $this->engine->getErrorCode();
-
- switch ($code) {
- case self::ERROR_DUPLICATE_KEY:
- case self::ERROR_NONE:
- // ignore duplicate key import errors
- break;
- case self::ERROR_NO_DATA:
- throw new Crypt_GPG_NoDataException(
- 'No valid GPG key data found.',
- $code
- );
- default:
- throw new Crypt_GPG_Exception(
- 'Unknown error importing GPG key. Please use the \'debug\' ' .
- 'option when creating the Crypt_GPG object, and file a bug ' .
- 'report at ' . self::BUG_URI,
- $code
- );
- }
-
- return $result;
- }
-
- // }}}
- // {{{ _exportKey()
-
- /**
- * Exports a private or public key from the keyring
- *
- * If more than one key fingerprint is available for the specified
- * <kbd>$keyId</kbd> (for example, if you use a non-unique uid) only the
- * first key is exported.
- *
- * @param string $keyId either the full uid of the key, the email
- * part of the uid of the key or the key id.
- * @param boolean $armor optional. If true, ASCII armored data is returned;
- * otherwise, binary data is returned. Defaults to
- * true.
- * @param boolean $private return private instead of public key
- *
- * @return string the key data.
- *
- * @throws Crypt_GPG_KeyNotFoundException if a key with the given
- * <kbd>$keyId</kbd> is not found.
- *
- * @throws Crypt_GPG_Exception if an unknown or unexpected error occurs.
- * Use the <kbd>debug</kbd> option and file a bug report if these
- * exceptions occur.
- */
- public function _exportKey($keyId, $armor = true, $private = false)
- {
- $fingerprint = $this->getFingerprint($keyId);
-
- if ($fingerprint === null) {
- throw new Crypt_GPG_KeyNotFoundException(
- 'Key not found: ' . $keyId,
- self::ERROR_KEY_NOT_FOUND,
- $keyId
- );
- }
-
- $keyData = '';
- $operation = $private ? '--export-secret-keys' : '--export';
- $operation .= ' ' . escapeshellarg($fingerprint);
- $arguments = ($armor) ? array('--armor') : array();
-
- $this->engine->reset();
- $this->engine->setOutput($keyData);
- $this->engine->setOperation($operation, $arguments);
- $this->engine->run();
-
- $code = $this->engine->getErrorCode();
-
- if ($code !== self::ERROR_NONE) {
- throw new Crypt_GPG_Exception(
- 'Unknown error exporting a key. Please use the ' .
- '\'debug\' option when creating the Crypt_GPG object, and ' .
- 'file a bug report at ' . self::BUG_URI,
- $code
- );
- }
-
- return $keyData;
- }
-
- // }}}
- // {{{ _encrypt()
-
- /**
- * Encrypts data
- *
- * @param string $data the data to encrypt.
- * @param boolean $isFile whether or not the data is a filename.
- * @param string $outputFile the filename of the file in which to store
- * the encrypted data. If null, the encrypted
- * data is returned as a string.
- * @param boolean $armor if true, ASCII armored data is returned;
- * otherwise, binary data is returned.
- *
- * @return void|string if the <kbd>$outputFile</kbd> parameter is null, a
- * string containing the encrypted data is returned.
- *
- * @throws Crypt_GPG_KeyNotFoundException if no encryption key is specified.
- * See {@link Crypt_GPG::addEncryptKey()}.
- *
- * @throws Crypt_GPG_FileException if the output file is not writeable or
- * if the input file is not readable.
- *
- * @throws Crypt_GPG_Exception if an unknown or unexpected error occurs.
- * Use the <kbd>debug</kbd> option and file a bug report if these
- * exceptions occur.
- */
- protected function _encrypt($data, $isFile, $outputFile, $armor)
- {
- if (!$this->hasEncryptKeys()) {
- throw new Crypt_GPG_KeyNotFoundException(
- 'No encryption keys specified.'
- );
- }
-
- if ($isFile) {
- $input = @fopen($data, 'rb');
- if ($input === false) {
- throw new Crypt_GPG_FileException(
- 'Could not open input file "' . $data .
- '" for encryption.',
- 0,
- $data
- );
- }
- } else {
- $input = strval($data);
- }
-
- if ($outputFile === null) {
- $output = '';
- } else {
- $output = @fopen($outputFile, 'wb');
- if ($output === false) {
- if ($isFile) {
- fclose($input);
- }
- throw new Crypt_GPG_FileException(
- 'Could not open output file "' . $outputFile .
- '" for storing encrypted data.',
- 0,
- $outputFile
- );
- }
- }
-
- $arguments = ($armor) ? array('--armor') : array();
- foreach ($this->encryptKeys as $key) {
- $arguments[] = '--recipient ' . escapeshellarg($key['fingerprint']);
- }
-
- $this->engine->reset();
- $this->engine->setInput($input);
- $this->engine->setOutput($output);
- $this->engine->setOperation('--encrypt', $arguments);
- $this->engine->run();
-
- if ($isFile) {
- fclose($input);
- }
-
- if ($outputFile !== null) {
- fclose($output);
- }
-
- $code = $this->engine->getErrorCode();
-
- if ($code !== self::ERROR_NONE) {
- throw new Crypt_GPG_Exception(
- 'Unknown error encrypting data. Please use the \'debug\' ' .
- 'option when creating the Crypt_GPG object, and file a bug ' .
- 'report at ' . self::BUG_URI,
- $code
- );
- }
-
- if ($outputFile === null) {
- return $output;
- }
- }
-
- // }}}
- // {{{ _decrypt()
-
- /**
- * Decrypts data
- *
- * @param string $data the data to be decrypted.
- * @param boolean $isFile whether or not the data is a filename.
- * @param string $outputFile the name of the file to which the decrypted
- * data should be written. If null, the decrypted
- * data is returned as a string.
- *
- * @return void|string if the <kbd>$outputFile</kbd> parameter is null, a
- * string containing the decrypted data is returned.
- *
- * @throws Crypt_GPG_KeyNotFoundException if the private key needed to
- * decrypt the data is not in the user's keyring.
- *
- * @throws Crypt_GPG_NoDataException if specified data does not contain
- * GPG encrypted data.
- *
- * @throws Crypt_GPG_BadPassphraseException if a required passphrase is
- * incorrect or if a required passphrase is not specified. See
- * {@link Crypt_GPG::addDecryptKey()}.
- *
- * @throws Crypt_GPG_FileException if the output file is not writeable or
- * if the input file is not readable.
- *
- * @throws Crypt_GPG_Exception if an unknown or unexpected error occurs.
- * Use the <kbd>debug</kbd> option and file a bug report if these
- * exceptions occur.
- */
- protected function _decrypt($data, $isFile, $outputFile)
- {
- if ($isFile) {
- $input = @fopen($data, 'rb');
- if ($input === false) {
- throw new Crypt_GPG_FileException(
- 'Could not open input file "' . $data .
- '" for decryption.',
- 0,
- $data
- );
- }
- } else {
- $input = strval($data);
- if ($input == '') {
- throw new Crypt_GPG_NoDataException(
- 'Cannot decrypt data. No PGP encrypted data was found in '.
- 'the provided data.',
- self::ERROR_NO_DATA
- );
- }
- }
-
- if ($outputFile === null) {
- $output = '';
- } else {
- $output = @fopen($outputFile, 'wb');
- if ($output === false) {
- if ($isFile) {
- fclose($input);
- }
- throw new Crypt_GPG_FileException(
- 'Could not open output file "' . $outputFile .
- '" for storing decrypted data.',
- 0,
- $outputFile
- );
- }
- }
-
- $handler = new Crypt_GPG_DecryptStatusHandler(
- $this->engine,
- $this->decryptKeys
- );
-
- // If using gpg-agent, set the decrypt pins used by the pinentry
- $this->_setPinEntryEnv($this->decryptKeys);
-
- $this->engine->reset();
- $this->engine->addStatusHandler(array($handler, 'handle'));
- $this->engine->setOperation('--decrypt');
- $this->engine->setInput($input);
- $this->engine->setOutput($output);
- $this->engine->run();
-
- if ($isFile) {
- fclose($input);
- }
-
- if ($outputFile !== null) {
- fclose($output);
- }
-
- // if there was any problem decrypting the data, the handler will
- // deal with it here.
- $handler->throwException();
-
- if ($outputFile === null) {
- return $output;
- }
- }
-
- // }}}
- // {{{ _sign()
-
- /**
- * Signs data
- *
- * @param string $data the data to be signed.
- * @param boolean $isFile whether or not the data is a filename.
- * @param string $outputFile the name of the file in which the signed data
- * should be stored. If null, the signed data is
- * returned as a string.
- * @param boolean $mode the data signing mode to use. Should be one of
- * {@link Crypt_GPG::SIGN_MODE_NORMAL},
- * {@link Crypt_GPG::SIGN_MODE_CLEAR} or
- * {@link Crypt_GPG::SIGN_MODE_DETACHED}.
- * @param boolean $armor if true, ASCII armored data is returned;
- * otherwise, binary data is returned. This has
- * no effect if the mode
- * <kbd>Crypt_GPG::SIGN_MODE_CLEAR</kbd> is
- * used.
- * @param boolean $textmode if true, line-breaks in signed data be
- * normalized. Use this option when signing
- * e-mail, or for greater compatibility between
- * systems with different line-break formats.
- * Defaults to false. This has no effect if the
- * mode <kbd>Crypt_GPG::SIGN_MODE_CLEAR</kbd> is
- * used as clear-signing always uses textmode.
- *
- * @return void|string if the <kbd>$outputFile</kbd> parameter is null, a
- * string containing the signed data (or the signature
- * data if a detached signature is requested) is
- * returned.
- *
- * @throws Crypt_GPG_KeyNotFoundException if no signing key is specified.
- * See {@link Crypt_GPG::addSignKey()}.
- *
- * @throws Crypt_GPG_BadPassphraseException if a specified passphrase is
- * incorrect or if a required passphrase is not specified.
- *
- * @throws Crypt_GPG_FileException if the output file is not writeable or
- * if the input file is not readable.
- *
- * @throws Crypt_GPG_Exception if an unknown or unexpected error occurs.
- * Use the <kbd>debug</kbd> option and file a bug report if these
- * exceptions occur.
- */
- protected function _sign($data, $isFile, $outputFile, $mode, $armor,
- $textmode
- ) {
- $this->lastSignatureInfo = null;
- if (!$this->hasSignKeys()) {
- throw new Crypt_GPG_KeyNotFoundException(
- 'No signing keys specified.'
- );
- }
-
- if ($isFile) {
- $input = @fopen($data, 'rb');
- if ($input === false) {
- throw new Crypt_GPG_FileException(
- 'Could not open input file "' . $data . '" for signing.',
- 0,
- $data
- );
- }
- } else {
- $input = strval($data);
- }
-
- if ($outputFile === null) {
- $output = '';
- } else {
- $output = @fopen($outputFile, 'wb');
- if ($output === false) {
- if ($isFile) {
- fclose($input);
- }
- throw new Crypt_GPG_FileException(
- 'Could not open output file "' . $outputFile .
- '" for storing signed data.',
- 0,
- $outputFile
- );
- }
- }
-
- switch ($mode) {
- case self::SIGN_MODE_DETACHED:
- $operation = '--detach-sign';
- break;
- case self::SIGN_MODE_CLEAR:
- $operation = '--clearsign';
- break;
- case self::SIGN_MODE_NORMAL:
- default:
- $operation = '--sign';
- break;
- }
-
- $arguments = array();
-
- if ($armor) {
- $arguments[] = '--armor';
- }
- if ($textmode) {
- $arguments[] = '--textmode';
- }
-
- foreach ($this->signKeys as $key) {
- $arguments[] = '--local-user ' .
- escapeshellarg($key['fingerprint']);
- }
-
- // If using gpg-agent, set the sign pins used by the pinentry
- $this->_setPinEntryEnv($this->signKeys);
-
- $this->engine->reset();
- $this->engine->addStatusHandler(array($this, 'handleSignStatus'));
- $this->engine->setInput($input);
- $this->engine->setOutput($output);
- $this->engine->setOperation($operation, $arguments);
- $this->engine->run();
-
- if ($isFile) {
- fclose($input);
- }
-
- if ($outputFile !== null) {
- fclose($output);
- }
-
- $code = $this->engine->getErrorCode();
-
- switch ($code) {
- case self::ERROR_NONE:
- break;
- case self::ERROR_KEY_NOT_FOUND:
- throw new Crypt_GPG_KeyNotFoundException(
- 'Cannot sign data. Private key not found. Import the '.
- 'private key before trying to sign data.',
- $code,
- $this->engine->getErrorKeyId()
- );
- case self::ERROR_BAD_PASSPHRASE:
- throw new Crypt_GPG_BadPassphraseException(
- 'Cannot sign data. Incorrect passphrase provided.',
- $code
- );
- case self::ERROR_MISSING_PASSPHRASE:
- throw new Crypt_GPG_BadPassphraseException(
- 'Cannot sign data. No passphrase provided.',
- $code
- );
- default:
- throw new Crypt_GPG_Exception(
- 'Unknown error signing data. Please use the \'debug\' option ' .
- 'when creating the Crypt_GPG object, and file a bug report ' .
- 'at ' . self::BUG_URI,
- $code
- );
- }
-
- if ($outputFile === null) {
- return $output;
- }
- }
-
- // }}}
- // {{{ _encryptAndSign()
-
- /**
- * Encrypts and signs data
- *
- * @param string $data the data to be encrypted and signed.
- * @param boolean $isFile whether or not the data is a filename.
- * @param string $outputFile the name of the file in which the encrypted,
- * signed data should be stored. If null, the
- * encrypted, signed data is returned as a
- * string.
- * @param boolean $armor if true, ASCII armored data is returned;
- * otherwise, binary data is returned.
- *
- * @return void|string if the <kbd>$outputFile</kbd> parameter is null, a
- * string containing the encrypted, signed data is
- * returned.
- *
- * @throws Crypt_GPG_KeyNotFoundException if no encryption key is specified
- * or if no signing key is specified. See
- * {@link Crypt_GPG::addEncryptKey()} and
- * {@link Crypt_GPG::addSignKey()}.
- *
- * @throws Crypt_GPG_BadPassphraseException if a specified passphrase is
- * incorrect or if a required passphrase is not specified.
- *
- * @throws Crypt_GPG_FileException if the output file is not writeable or
- * if the input file is not readable.
- *
- * @throws Crypt_GPG_Exception if an unknown or unexpected error occurs.
- * Use the <kbd>debug</kbd> option and file a bug report if these
- * exceptions occur.
- */
- protected function _encryptAndSign($data, $isFile, $outputFile, $armor)
- {
- if (!$this->hasSignKeys()) {
- throw new Crypt_GPG_KeyNotFoundException(
- 'No signing keys specified.'
- );
- }
-
- if (!$this->hasEncryptKeys()) {
- throw new Crypt_GPG_KeyNotFoundException(
- 'No encryption keys specified.'
- );
- }
-
-
- if ($isFile) {
- $input = @fopen($data, 'rb');
- if ($input === false) {
- throw new Crypt_GPG_FileException(
- 'Could not open input file "' . $data .
- '" for encrypting and signing.',
- 0,
- $data
- );
- }
- } else {
- $input = strval($data);
- }
-
- if ($outputFile === null) {
- $output = '';
- } else {
- $output = @fopen($outputFile, 'wb');
- if ($output === false) {
- if ($isFile) {
- fclose($input);
- }
- throw new Crypt_GPG_FileException(
- 'Could not open output file "' . $outputFile .
- '" for storing encrypted, signed data.',
- 0,
- $outputFile
- );
- }
- }
-
- $arguments = ($armor) ? array('--armor') : array();
-
- foreach ($this->signKeys as $key) {
- $arguments[] = '--local-user ' .
- escapeshellarg($key['fingerprint']);
- }
-
- // If using gpg-agent, set the sign pins used by the pinentry
- $this->_setPinEntryEnv($this->signKeys);
-
- foreach ($this->encryptKeys as $key) {
- $arguments[] = '--recipient ' . escapeshellarg($key['fingerprint']);
- }
-
- $this->engine->reset();
- $this->engine->addStatusHandler(array($this, 'handleSignStatus'));
- $this->engine->setInput($input);
- $this->engine->setOutput($output);
- $this->engine->setOperation('--encrypt --sign', $arguments);
- $this->engine->run();
-
- if ($isFile) {
- fclose($input);
- }
-
- if ($outputFile !== null) {
- fclose($output);
- }
-
- $code = $this->engine->getErrorCode();
-
- switch ($code) {
- case self::ERROR_NONE:
- break;
- case self::ERROR_KEY_NOT_FOUND:
- throw new Crypt_GPG_KeyNotFoundException(
- 'Cannot sign encrypted data. Private key not found. Import '.
- 'the private key before trying to sign the encrypted data.',
- $code,
- $this->engine->getErrorKeyId()
- );
- case self::ERROR_BAD_PASSPHRASE:
- throw new Crypt_GPG_BadPassphraseException(
- 'Cannot sign encrypted data. Incorrect passphrase provided.',
- $code
- );
- case self::ERROR_MISSING_PASSPHRASE:
- throw new Crypt_GPG_BadPassphraseException(
- 'Cannot sign encrypted data. No passphrase provided.',
- $code
- );
- default:
- throw new Crypt_GPG_Exception(
- 'Unknown error encrypting and signing data. Please use the ' .
- '\'debug\' option when creating the Crypt_GPG object, and ' .
- 'file a bug report at ' . self::BUG_URI,
- $code
- );
- }
-
- if ($outputFile === null) {
- return $output;
- }
- }
-
- // }}}
- // {{{ _verify()
-
- /**
- * Verifies data
- *
- * @param string $data the signed data to be verified.
- * @param boolean $isFile whether or not the data is a filename.
- * @param string $signature if verifying a file signed using a detached
- * signature, this must be the detached signature
- * data. Otherwise, specify ''.
- *
- * @return array an array of {@link Crypt_GPG_Signature} objects for the
- * signed data.
- *
- * @throws Crypt_GPG_NoDataException if the provided data is not signed
- * data.
- *
- * @throws Crypt_GPG_FileException if the input file is not readable.
- *
- * @throws Crypt_GPG_Exception if an unknown or unexpected error occurs.
- * Use the <kbd>debug</kbd> option and file a bug report if these
- * exceptions occur.
- *
- * @see Crypt_GPG_Signature
- */
- protected function _verify($data, $isFile, $signature)
- {
- if ($signature == '') {
- $operation = '--verify';
- $arguments = array();
- } else {
- // Signed data goes in FD_MESSAGE, detached signature data goes in
- // FD_INPUT.
- $operation = '--verify - "-&' . Crypt_GPG_Engine::FD_MESSAGE. '"';
- $arguments = array('--enable-special-filenames');
- }
-
- $handler = new Crypt_GPG_VerifyStatusHandler();
-
- if ($isFile) {
- $input = @fopen($data, 'rb');
- if ($input === false) {
- throw new Crypt_GPG_FileException(
- 'Could not open input file "' . $data . '" for verifying.',
- 0,
- $data
- );
- }
- } else {
- $input = strval($data);
- if ($input == '') {
- throw new Crypt_GPG_NoDataException(
- 'No valid signature data found.',
- self::ERROR_NO_DATA
- );
- }
- }
-
- $this->engine->reset();
- $this->engine->addStatusHandler(array($handler, 'handle'));
-
- if ($signature == '') {
- // signed or clearsigned data
- $this->engine->setInput($input);
- } else {
- // detached signature
- $this->engine->setInput($signature);
- $this->engine->setMessage($input);
- }
-
- $this->engine->setOperation($operation, $arguments);
- $this->engine->run();
-
- if ($isFile) {
- fclose($input);
- }
-
- $code = $this->engine->getErrorCode();
-
- switch ($code) {
- case self::ERROR_NONE:
- case self::ERROR_BAD_SIGNATURE:
- break;
- case self::ERROR_NO_DATA:
- throw new Crypt_GPG_NoDataException(
- 'No valid signature data found.',
- $code
- );
- case self::ERROR_KEY_NOT_FOUND:
- throw new Crypt_GPG_KeyNotFoundException(
- 'Public key required for data verification not in keyring.',
- $code,
- $this->engine->getErrorKeyId()
- );
- default:
- throw new Crypt_GPG_Exception(
- 'Unknown error validating signature details. Please use the ' .
- '\'debug\' option when creating the Crypt_GPG object, and ' .
- 'file a bug report at ' . self::BUG_URI,
- $code
- );
- }
-
- return $handler->getSignatures();
- }
-
- // }}}
- // {{{ _decryptAndVerify()
-
- /**
- * Decrypts and verifies encrypted, signed data
- *
- * @param string $data the encrypted signed data to be decrypted and
- * verified.
- * @param boolean $isFile whether or not the data is a filename.
- * @param string $outputFile the name of the file to which the decrypted
- * data should be written. If null, the decrypted
- * data is returned in the results array.
- *
- * @return array two element array. The array has an element 'data'
- * containing the decrypted data and an element
- * 'signatures' containing an array of
- * {@link Crypt_GPG_Signature} objects for the signed data.
- * If the decrypted data is written to a file, the 'data'
- * element is null.
- *
- * @throws Crypt_GPG_KeyNotFoundException if the private key needed to
- * decrypt the data is not in the user's keyring or it the public
- * key needed for verification is not in the user's keyring.
- *
- * @throws Crypt_GPG_NoDataException if specified data does not contain
- * GPG signed, encrypted data.
- *
- * @throws Crypt_GPG_BadPassphraseException if a required passphrase is
- * incorrect or if a required passphrase is not specified. See
- * {@link Crypt_GPG::addDecryptKey()}.
- *
- * @throws Crypt_GPG_FileException if the output file is not writeable or
- * if the input file is not readable.
- *
- * @throws Crypt_GPG_Exception if an unknown or unexpected error occurs.
- * Use the <kbd>debug</kbd> option and file a bug report if these
- * exceptions occur.
- *
- * @see Crypt_GPG_Signature
- */
- protected function _decryptAndVerify($data, $isFile, $outputFile)
- {
- if ($isFile) {
- $input = @fopen($data, 'rb');
- if ($input === false) {
- throw new Crypt_GPG_FileException(
- 'Could not open input file "' . $data .
- '" for decrypting and verifying.',
- 0,
- $data
- );
- }
- } else {
- $input = strval($data);
- if ($input == '') {
- throw new Crypt_GPG_NoDataException(
- 'No valid encrypted signed data found.',
- self::ERROR_NO_DATA
- );
- }
- }
-
- if ($outputFile === null) {
- $output = '';
- } else {
- $output = @fopen($outputFile, 'wb');
- if ($output === false) {
- if ($isFile) {
- fclose($input);
- }
- throw new Crypt_GPG_FileException(
- 'Could not open output file "' . $outputFile .
- '" for storing decrypted data.',
- 0,
- $outputFile
- );
- }
- }
-
- $verifyHandler = new Crypt_GPG_VerifyStatusHandler();
-
- $decryptHandler = new Crypt_GPG_DecryptStatusHandler(
- $this->engine,
- $this->decryptKeys
- );
-
- // If using gpg-agent, set the decrypt pins used by the pinentry
- $this->_setPinEntryEnv($this->decryptKeys);
-
- $this->engine->reset();
- $this->engine->addStatusHandler(array($verifyHandler, 'handle'));
- $this->engine->addStatusHandler(array($decryptHandler, 'handle'));
- $this->engine->setInput($input);
- $this->engine->setOutput($output);
- $this->engine->setOperation('--decrypt');
- $this->engine->run();
-
- if ($isFile) {
- fclose($input);
- }
-
- if ($outputFile !== null) {
- fclose($output);
- }
-
- $return = array(
- 'data' => null,
- 'signatures' => $verifyHandler->getSignatures()
- );
-
- // if there was any problem decrypting the data, the handler will
- // deal with it here.
- try {
- $decryptHandler->throwException();
- } catch (Exception $e) {
- if ($e instanceof Crypt_GPG_KeyNotFoundException) {
- throw new Crypt_GPG_KeyNotFoundException(
- 'Public key required for data verification not in ',
- 'the keyring. Either no suitable private decryption key ' .
- 'is in the keyring or the public key required for data ' .
- 'verification is not in the keyring. Import a suitable ' .
- 'key before trying to decrypt and verify this data.',
- self::ERROR_KEY_NOT_FOUND,
- $this->engine->getErrorKeyId()
- );
- }
-
- if ($e instanceof Crypt_GPG_NoDataException) {
- throw new Crypt_GPG_NoDataException(
- 'Cannot decrypt and verify data. No PGP encrypted data ' .
- 'was found in the provided data.',
- self::ERROR_NO_DATA
- );
- }
-
- throw $e;
- }
-
- if ($outputFile === null) {
- $return['data'] = $output;
- }
-
- return $return;
- }
-
- // }}}
- }
-
- // }}}
-
- ?>
|