You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

GPG.php 87KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516
  1. <?php
  2. /* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
  3. /**
  4. * Crypt_GPG is a package to use GPG from PHP
  5. *
  6. * This package provides an object oriented interface to GNU Privacy
  7. * Guard (GPG). It requires the GPG executable to be on the system.
  8. *
  9. * Though GPG can support symmetric-key cryptography, this package is intended
  10. * only to facilitate public-key cryptography.
  11. *
  12. * This file contains the main GPG class. The class in this file lets you
  13. * encrypt, decrypt, sign and verify data; import and delete keys; and perform
  14. * other useful GPG tasks.
  15. *
  16. * Example usage:
  17. * <code>
  18. * <?php
  19. * // encrypt some data
  20. * $gpg = new Crypt_GPG();
  21. * $gpg->addEncryptKey($mySecretKeyId);
  22. * $encryptedData = $gpg->encrypt($data);
  23. * ?>
  24. * </code>
  25. *
  26. * PHP version 5
  27. *
  28. * LICENSE:
  29. *
  30. * This library is free software; you can redistribute it and/or modify
  31. * it under the terms of the GNU Lesser General Public License as
  32. * published by the Free Software Foundation; either version 2.1 of the
  33. * License, or (at your option) any later version.
  34. *
  35. * This library is distributed in the hope that it will be useful,
  36. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  37. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  38. * Lesser General Public License for more details.
  39. *
  40. * You should have received a copy of the GNU Lesser General Public
  41. * License along with this library; if not, see
  42. * <http://www.gnu.org/licenses/>
  43. *
  44. * @category Encryption
  45. * @package Crypt_GPG
  46. * @author Nathan Fredrickson <nathan@silverorange.com>
  47. * @author Michael Gauthier <mike@silverorange.com>
  48. * @copyright 2005-2013 silverorange
  49. * @license http://www.gnu.org/copyleft/lesser.html LGPL License 2.1
  50. * @version CVS: $Id$
  51. * @link http://pear.php.net/package/Crypt_GPG
  52. * @link http://pear.php.net/manual/en/package.encryption.crypt-gpg.php
  53. * @link http://www.gnupg.org/
  54. */
  55. /**
  56. * Base class for GPG methods
  57. */
  58. require_once 'Crypt/GPGAbstract.php';
  59. /**
  60. * Signature handler class
  61. */
  62. require_once 'Crypt/GPG/VerifyStatusHandler.php';
  63. /**
  64. * Decryption handler class
  65. */
  66. require_once 'Crypt/GPG/DecryptStatusHandler.php';
  67. /**
  68. * Information about a created signature
  69. */
  70. require_once 'Crypt/GPG/SignatureCreationInfo.php';
  71. // {{{ class Crypt_GPG
  72. /**
  73. * A class to use GPG from PHP
  74. *
  75. * This class provides an object oriented interface to GNU Privacy Guard (GPG).
  76. *
  77. * Though GPG can support symmetric-key cryptography, this class is intended
  78. * only to facilitate public-key cryptography.
  79. *
  80. * @category Encryption
  81. * @package Crypt_GPG
  82. * @author Nathan Fredrickson <nathan@silverorange.com>
  83. * @author Michael Gauthier <mike@silverorange.com>
  84. * @copyright 2005-2013 silverorange
  85. * @license http://www.gnu.org/copyleft/lesser.html LGPL License 2.1
  86. * @link http://pear.php.net/package/Crypt_GPG
  87. * @link http://www.gnupg.org/
  88. */
  89. class Crypt_GPG extends Crypt_GPGAbstract
  90. {
  91. // {{{ class constants for data signing modes
  92. /**
  93. * Signing mode for normal signing of data. The signed message will not
  94. * be readable without special software.
  95. *
  96. * This is the default signing mode.
  97. *
  98. * @see Crypt_GPG::sign()
  99. * @see Crypt_GPG::signFile()
  100. */
  101. const SIGN_MODE_NORMAL = 1;
  102. /**
  103. * Signing mode for clearsigning data. Clearsigned signatures are ASCII
  104. * armored data and are readable without special software. If the signed
  105. * message is unencrypted, the message will still be readable. The message
  106. * text will be in the original encoding.
  107. *
  108. * @see Crypt_GPG::sign()
  109. * @see Crypt_GPG::signFile()
  110. */
  111. const SIGN_MODE_CLEAR = 2;
  112. /**
  113. * Signing mode for creating a detached signature. When using detached
  114. * signatures, only the signature data is returned. The original message
  115. * text may be distributed separately from the signature data. This is
  116. * useful for miltipart/signed email messages as per
  117. * {@link http://www.ietf.org/rfc/rfc3156.txt RFC 3156}.
  118. *
  119. * @see Crypt_GPG::sign()
  120. * @see Crypt_GPG::signFile()
  121. */
  122. const SIGN_MODE_DETACHED = 3;
  123. // }}}
  124. // {{{ class constants for fingerprint formats
  125. /**
  126. * No formatting is performed.
  127. *
  128. * Example: C3BC615AD9C766E5A85C1F2716D27458B1BBA1C4
  129. *
  130. * @see Crypt_GPG::getFingerprint()
  131. */
  132. const FORMAT_NONE = 1;
  133. /**
  134. * Fingerprint is formatted in the format used by the GnuPG gpg command's
  135. * default output.
  136. *
  137. * Example: C3BC 615A D9C7 66E5 A85C 1F27 16D2 7458 B1BB A1C4
  138. *
  139. * @see Crypt_GPG::getFingerprint()
  140. */
  141. const FORMAT_CANONICAL = 2;
  142. /**
  143. * Fingerprint is formatted in the format used when displaying X.509
  144. * certificates
  145. *
  146. * Example: C3:BC:61:5A:D9:C7:66:E5:A8:5C:1F:27:16:D2:74:58:B1:BB:A1:C4
  147. *
  148. * @see Crypt_GPG::getFingerprint()
  149. */
  150. const FORMAT_X509 = 3;
  151. // }}}
  152. // {{{ class constants for boolean options
  153. /**
  154. * Use to specify ASCII armored mode for returned data
  155. */
  156. const ARMOR_ASCII = true;
  157. /**
  158. * Use to specify binary mode for returned data
  159. */
  160. const ARMOR_BINARY = false;
  161. /**
  162. * Use to specify that line breaks in signed text should be normalized
  163. */
  164. const TEXT_NORMALIZED = true;
  165. /**
  166. * Use to specify that line breaks in signed text should not be normalized
  167. */
  168. const TEXT_RAW = false;
  169. // }}}
  170. // {{{ protected class properties
  171. /**
  172. * Engine used to control the GPG subprocess
  173. *
  174. * @var Crypt_GPG_Engine
  175. *
  176. * @see Crypt_GPG::setEngine()
  177. */
  178. protected $engine = null;
  179. /**
  180. * Keys used to encrypt
  181. *
  182. * The array is of the form:
  183. * <code>
  184. * array(
  185. * $key_id => array(
  186. * 'fingerprint' => $fingerprint,
  187. * 'passphrase' => null
  188. * )
  189. * );
  190. * </code>
  191. *
  192. * @var array
  193. * @see Crypt_GPG::addEncryptKey()
  194. * @see Crypt_GPG::clearEncryptKeys()
  195. */
  196. protected $encryptKeys = array();
  197. /**
  198. * Keys used to decrypt
  199. *
  200. * The array is of the form:
  201. * <code>
  202. * array(
  203. * $key_id => array(
  204. * 'fingerprint' => $fingerprint,
  205. * 'passphrase' => $passphrase
  206. * )
  207. * );
  208. * </code>
  209. *
  210. * @var array
  211. * @see Crypt_GPG::addSignKey()
  212. * @see Crypt_GPG::clearSignKeys()
  213. */
  214. protected $signKeys = array();
  215. /**
  216. * Keys used to sign
  217. *
  218. * The array is of the form:
  219. * <code>
  220. * array(
  221. * $key_id => array(
  222. * 'fingerprint' => $fingerprint,
  223. * 'passphrase' => $passphrase
  224. * )
  225. * );
  226. * </code>
  227. *
  228. * @var array
  229. * @see Crypt_GPG::addDecryptKey()
  230. * @see Crypt_GPG::clearDecryptKeys()
  231. */
  232. protected $decryptKeys = array();
  233. /**
  234. * Information about the last signature that was generated.
  235. * A string (line) beginning with "SIG_CREATED "
  236. *
  237. * @see handleSignStatus()
  238. * @var string
  239. */
  240. protected $lastSignatureInfo = null;
  241. // }}}
  242. // {{{ importKey()
  243. /**
  244. * Imports a public or private key into the keyring
  245. *
  246. * Keys may be removed from the keyring using
  247. * {@link Crypt_GPG::deletePublicKey()} or
  248. * {@link Crypt_GPG::deletePrivateKey()}.
  249. *
  250. * @param string $data the key data to be imported.
  251. *
  252. * @return array an associative array containing the following elements:
  253. * - <kbd>fingerprint</kbd> - the fingerprint of the
  254. * imported key,
  255. * - <kbd>public_imported</kbd> - the number of public
  256. * keys imported,
  257. * - <kbd>public_unchanged</kbd> - the number of unchanged
  258. * public keys,
  259. * - <kbd>private_imported</kbd> - the number of private
  260. * keys imported,
  261. * - <kbd>private_unchanged</kbd> - the number of unchanged
  262. * private keys.
  263. *
  264. * @throws Crypt_GPG_NoDataException if the key data is missing or if the
  265. * data is is not valid key data.
  266. *
  267. * @throws Crypt_GPG_Exception if an unknown or unexpected error occurs.
  268. * Use the <kbd>debug</kbd> option and file a bug report if these
  269. * exceptions occur.
  270. */
  271. public function importKey($data)
  272. {
  273. return $this->_importKey($data, false);
  274. }
  275. // }}}
  276. // {{{ importKeyFile()
  277. /**
  278. * Imports a public or private key file into the keyring
  279. *
  280. * Keys may be removed from the keyring using
  281. * {@link Crypt_GPG::deletePublicKey()} or
  282. * {@link Crypt_GPG::deletePrivateKey()}.
  283. *
  284. * @param string $filename the key file to be imported.
  285. *
  286. * @return array an associative array containing the following elements:
  287. * - <kbd>fingerprint</kbd> - the fingerprint of the
  288. * imported key,
  289. * - <kbd>public_imported</kbd> - the number of public
  290. * keys imported,
  291. * - <kbd>public_unchanged</kbd> - the number of unchanged
  292. * public keys,
  293. * - <kbd>private_imported</kbd> - the number of private
  294. * keys imported,
  295. * - <kbd>private_unchanged</kbd> - the number of unchanged
  296. * private keys.
  297. * private keys.
  298. *
  299. * @throws Crypt_GPG_NoDataException if the key data is missing or if the
  300. * data is is not valid key data.
  301. *
  302. * @throws Crypt_GPG_FileException if the key file is not readable.
  303. *
  304. * @throws Crypt_GPG_Exception if an unknown or unexpected error occurs.
  305. * Use the <kbd>debug</kbd> option and file a bug report if these
  306. * exceptions occur.
  307. */
  308. public function importKeyFile($filename)
  309. {
  310. return $this->_importKey($filename, true);
  311. }
  312. // }}}
  313. // {{{ exportPrivateKey()
  314. /**
  315. * Exports a private key from the keyring
  316. *
  317. * The exported key remains on the keyring. To delete the key, use
  318. * {@link Crypt_GPG::deletePrivateKey()}.
  319. *
  320. * If more than one key fingerprint is available for the specified
  321. * <kbd>$keyId</kbd> (for example, if you use a non-unique uid) only the
  322. * first private key is exported.
  323. *
  324. * @param string $keyId either the full uid of the private key, the email
  325. * part of the uid of the private key or the key id of
  326. * the private key. For example,
  327. * "Test User (example) <test@example.com>",
  328. * "test@example.com" or a hexadecimal string.
  329. * @param boolean $armor optional. If true, ASCII armored data is returned;
  330. * otherwise, binary data is returned. Defaults to
  331. * true.
  332. *
  333. * @return string the private key data.
  334. *
  335. * @throws Crypt_GPG_KeyNotFoundException if a private key with the given
  336. * <kbd>$keyId</kbd> is not found.
  337. *
  338. * @throws Crypt_GPG_Exception if an unknown or unexpected error occurs.
  339. * Use the <kbd>debug</kbd> option and file a bug report if these
  340. * exceptions occur.
  341. */
  342. public function exportPrivateKey($keyId, $armor = true)
  343. {
  344. return $this->_exportKey($keyId, $armor, true);
  345. }
  346. // }}}
  347. // {{{ exportPublicKey()
  348. /**
  349. * Exports a public key from the keyring
  350. *
  351. * The exported key remains on the keyring. To delete the public key, use
  352. * {@link Crypt_GPG::deletePublicKey()}.
  353. *
  354. * If more than one key fingerprint is available for the specified
  355. * <kbd>$keyId</kbd> (for example, if you use a non-unique uid) only the
  356. * first public key is exported.
  357. *
  358. * @param string $keyId either the full uid of the public key, the email
  359. * part of the uid of the public key or the key id of
  360. * the public key. For example,
  361. * "Test User (example) <test@example.com>",
  362. * "test@example.com" or a hexadecimal string.
  363. * @param boolean $armor optional. If true, ASCII armored data is returned;
  364. * otherwise, binary data is returned. Defaults to
  365. * true.
  366. *
  367. * @return string the public key data.
  368. *
  369. * @throws Crypt_GPG_KeyNotFoundException if a public key with the given
  370. * <kbd>$keyId</kbd> is not found.
  371. *
  372. * @throws Crypt_GPG_Exception if an unknown or unexpected error occurs.
  373. * Use the <kbd>debug</kbd> option and file a bug report if these
  374. * exceptions occur.
  375. */
  376. public function exportPublicKey($keyId, $armor = true)
  377. {
  378. return $this->_exportKey($keyId, $armor, false);
  379. }
  380. // }}}
  381. // {{{ deletePublicKey()
  382. /**
  383. * Deletes a public key from the keyring
  384. *
  385. * If more than one key fingerprint is available for the specified
  386. * <kbd>$keyId</kbd> (for example, if you use a non-unique uid) only the
  387. * first public key is deleted.
  388. *
  389. * The private key must be deleted first or an exception will be thrown.
  390. * See {@link Crypt_GPG::deletePrivateKey()}.
  391. *
  392. * @param string $keyId either the full uid of the public key, the email
  393. * part of the uid of the public key or the key id of
  394. * the public key. For example,
  395. * "Test User (example) <test@example.com>",
  396. * "test@example.com" or a hexadecimal string.
  397. *
  398. * @return void
  399. *
  400. * @throws Crypt_GPG_KeyNotFoundException if a public key with the given
  401. * <kbd>$keyId</kbd> is not found.
  402. *
  403. * @throws Crypt_GPG_DeletePrivateKeyException if the specified public key
  404. * has an associated private key on the keyring. The private key
  405. * must be deleted first.
  406. *
  407. * @throws Crypt_GPG_Exception if an unknown or unexpected error occurs.
  408. * Use the <kbd>debug</kbd> option and file a bug report if these
  409. * exceptions occur.
  410. */
  411. public function deletePublicKey($keyId)
  412. {
  413. $fingerprint = $this->getFingerprint($keyId);
  414. if ($fingerprint === null) {
  415. throw new Crypt_GPG_KeyNotFoundException(
  416. 'Public key not found: ' . $keyId,
  417. self::ERROR_KEY_NOT_FOUND,
  418. $keyId
  419. );
  420. }
  421. $operation = '--delete-key ' . escapeshellarg($fingerprint);
  422. $arguments = array(
  423. '--batch',
  424. '--yes'
  425. );
  426. $this->engine->reset();
  427. $this->engine->setOperation($operation, $arguments);
  428. $this->engine->run();
  429. $code = $this->engine->getErrorCode();
  430. switch ($code) {
  431. case self::ERROR_NONE:
  432. break;
  433. case self::ERROR_DELETE_PRIVATE_KEY:
  434. throw new Crypt_GPG_DeletePrivateKeyException(
  435. 'Private key must be deleted before public key can be ' .
  436. 'deleted.',
  437. $code,
  438. $keyId
  439. );
  440. default:
  441. throw new Crypt_GPG_Exception(
  442. 'Unknown error deleting public key. Please use the ' .
  443. '\'debug\' option when creating the Crypt_GPG object, and ' .
  444. 'file a bug report at ' . self::BUG_URI,
  445. $code
  446. );
  447. }
  448. }
  449. // }}}
  450. // {{{ deletePrivateKey()
  451. /**
  452. * Deletes a private key from the keyring
  453. *
  454. * If more than one key fingerprint is available for the specified
  455. * <kbd>$keyId</kbd> (for example, if you use a non-unique uid) only the
  456. * first private key is deleted.
  457. *
  458. * Calls GPG with the <kbd>--delete-secret-key</kbd> command.
  459. *
  460. * @param string $keyId either the full uid of the private key, the email
  461. * part of the uid of the private key or the key id of
  462. * the private key. For example,
  463. * "Test User (example) <test@example.com>",
  464. * "test@example.com" or a hexadecimal string.
  465. *
  466. * @return void
  467. *
  468. * @throws Crypt_GPG_KeyNotFoundException if a private key with the given
  469. * <kbd>$keyId</kbd> is not found.
  470. *
  471. * @throws Crypt_GPG_Exception if an unknown or unexpected error occurs.
  472. * Use the <kbd>debug</kbd> option and file a bug report if these
  473. * exceptions occur.
  474. */
  475. public function deletePrivateKey($keyId)
  476. {
  477. $fingerprint = $this->getFingerprint($keyId);
  478. if ($fingerprint === null) {
  479. throw new Crypt_GPG_KeyNotFoundException(
  480. 'Private key not found: ' . $keyId,
  481. self::ERROR_KEY_NOT_FOUND,
  482. $keyId
  483. );
  484. }
  485. $operation = '--delete-secret-key ' . escapeshellarg($fingerprint);
  486. $arguments = array(
  487. '--batch',
  488. '--yes'
  489. );
  490. $this->engine->reset();
  491. $this->engine->setOperation($operation, $arguments);
  492. $this->engine->run();
  493. $code = $this->engine->getErrorCode();
  494. switch ($code) {
  495. case self::ERROR_NONE:
  496. break;
  497. case self::ERROR_KEY_NOT_FOUND:
  498. throw new Crypt_GPG_KeyNotFoundException(
  499. 'Private key not found: ' . $keyId,
  500. $code,
  501. $keyId
  502. );
  503. default:
  504. throw new Crypt_GPG_Exception(
  505. 'Unknown error deleting private key. Please use the ' .
  506. '\'debug\' option when creating the Crypt_GPG object, and ' .
  507. 'file a bug report at ' . self::BUG_URI,
  508. $code
  509. );
  510. }
  511. }
  512. // }}}
  513. // {{{ getKeys()
  514. /**
  515. * Gets the available keys in the keyring
  516. *
  517. * Calls GPG with the <kbd>--list-keys</kbd> command and grabs keys. See
  518. * the first section of <b>doc/DETAILS</b> in the
  519. * {@link http://www.gnupg.org/download/ GPG package} for a detailed
  520. * description of how the GPG command output is parsed.
  521. *
  522. * @param string $keyId optional. Only keys with that match the specified
  523. * pattern are returned. The pattern may be part of
  524. * a user id, a key id or a key fingerprint. If not
  525. * specified, all keys are returned.
  526. *
  527. * @return array an array of {@link Crypt_GPG_Key} objects. If no keys
  528. * match the specified <kbd>$keyId</kbd> an empty array is
  529. * returned.
  530. *
  531. * @throws Crypt_GPG_Exception if an unknown or unexpected error occurs.
  532. * Use the <kbd>debug</kbd> option and file a bug report if these
  533. * exceptions occur.
  534. *
  535. * @see Crypt_GPG_Key
  536. */
  537. public function getKeys($keyId = '')
  538. {
  539. return parent::_getKeys($keyId);
  540. }
  541. // }}}
  542. // {{{ getFingerprint()
  543. /**
  544. * Gets a key fingerprint from the keyring
  545. *
  546. * If more than one key fingerprint is available (for example, if you use
  547. * a non-unique user id) only the first key fingerprint is returned.
  548. *
  549. * Calls the GPG <kbd>--list-keys</kbd> command with the
  550. * <kbd>--with-fingerprint</kbd> option to retrieve a public key
  551. * fingerprint.
  552. *
  553. * @param string $keyId either the full user id of the key, the email
  554. * part of the user id of the key, or the key id of
  555. * the key. For example,
  556. * "Test User (example) <test@example.com>",
  557. * "test@example.com" or a hexadecimal string.
  558. * @param integer $format optional. How the fingerprint should be formatted.
  559. * Use {@link Crypt_GPG::FORMAT_X509} for X.509
  560. * certificate format,
  561. * {@link Crypt_GPG::FORMAT_CANONICAL} for the format
  562. * used by GnuPG output and
  563. * {@link Crypt_GPG::FORMAT_NONE} for no formatting.
  564. * Defaults to <code>Crypt_GPG::FORMAT_NONE</code>.
  565. *
  566. * @return string the fingerprint of the key, or null if no fingerprint
  567. * is found for the given <kbd>$keyId</kbd>.
  568. *
  569. * @throws Crypt_GPG_Exception if an unknown or unexpected error occurs.
  570. * Use the <kbd>debug</kbd> option and file a bug report if these
  571. * exceptions occur.
  572. */
  573. public function getFingerprint($keyId, $format = self::FORMAT_NONE)
  574. {
  575. $output = '';
  576. $operation = '--list-keys ' . escapeshellarg($keyId);
  577. $arguments = array(
  578. '--with-colons',
  579. '--with-fingerprint'
  580. );
  581. $this->engine->reset();
  582. $this->engine->setOutput($output);
  583. $this->engine->setOperation($operation, $arguments);
  584. $this->engine->run();
  585. $code = $this->engine->getErrorCode();
  586. switch ($code) {
  587. case self::ERROR_NONE:
  588. case self::ERROR_KEY_NOT_FOUND:
  589. // ignore not found key errors
  590. break;
  591. default:
  592. throw new Crypt_GPG_Exception(
  593. 'Unknown error getting key fingerprint. Please use the ' .
  594. '\'debug\' option when creating the Crypt_GPG object, and ' .
  595. 'file a bug report at ' . self::BUG_URI,
  596. $code
  597. );
  598. }
  599. $fingerprint = null;
  600. $lines = explode(PHP_EOL, $output);
  601. foreach ($lines as $line) {
  602. if (substr($line, 0, 3) == 'fpr') {
  603. $lineExp = explode(':', $line);
  604. $fingerprint = $lineExp[9];
  605. switch ($format) {
  606. case self::FORMAT_CANONICAL:
  607. $fingerprintExp = str_split($fingerprint, 4);
  608. $format = '%s %s %s %s %s %s %s %s %s %s';
  609. $fingerprint = vsprintf($format, $fingerprintExp);
  610. break;
  611. case self::FORMAT_X509:
  612. $fingerprintExp = str_split($fingerprint, 2);
  613. $fingerprint = implode(':', $fingerprintExp);
  614. break;
  615. }
  616. break;
  617. }
  618. }
  619. return $fingerprint;
  620. }
  621. // }}}
  622. // {{{ getLastSignatureInfo()
  623. /**
  624. * Get information about the last signature that was created.
  625. *
  626. * @return Crypt_GPG_SignatureCreationInfo
  627. */
  628. public function getLastSignatureInfo()
  629. {
  630. if ($this->lastSignatureInfo === null) {
  631. return null;
  632. }
  633. return new Crypt_GPG_SignatureCreationInfo($this->lastSignatureInfo);
  634. }
  635. // }}}
  636. // {{{ encrypt()
  637. /**
  638. * Encrypts string data
  639. *
  640. * Data is ASCII armored by default but may optionally be returned as
  641. * binary.
  642. *
  643. * @param string $data the data to be encrypted.
  644. * @param boolean $armor optional. If true, ASCII armored data is returned;
  645. * otherwise, binary data is returned. Defaults to
  646. * true.
  647. *
  648. * @return string the encrypted data.
  649. *
  650. * @throws Crypt_GPG_KeyNotFoundException if no encryption key is specified.
  651. * See {@link Crypt_GPG::addEncryptKey()}.
  652. *
  653. * @throws Crypt_GPG_Exception if an unknown or unexpected error occurs.
  654. * Use the <kbd>debug</kbd> option and file a bug report if these
  655. * exceptions occur.
  656. *
  657. * @sensitive $data
  658. */
  659. public function encrypt($data, $armor = self::ARMOR_ASCII)
  660. {
  661. return $this->_encrypt($data, false, null, $armor);
  662. }
  663. // }}}
  664. // {{{ encryptFile()
  665. /**
  666. * Encrypts a file
  667. *
  668. * Encrypted data is ASCII armored by default but may optionally be saved
  669. * as binary.
  670. *
  671. * @param string $filename the filename of the file to encrypt.
  672. * @param string $encryptedFile optional. The filename of the file in
  673. * which to store the encrypted data. If null
  674. * or unspecified, the encrypted data is
  675. * returned as a string.
  676. * @param boolean $armor optional. If true, ASCII armored data is
  677. * returned; otherwise, binary data is
  678. * returned. Defaults to true.
  679. *
  680. * @return void|string if the <kbd>$encryptedFile</kbd> parameter is null,
  681. * a string containing the encrypted data is returned.
  682. *
  683. * @throws Crypt_GPG_KeyNotFoundException if no encryption key is specified.
  684. * See {@link Crypt_GPG::addEncryptKey()}.
  685. *
  686. * @throws Crypt_GPG_FileException if the output file is not writeable or
  687. * if the input file is not readable.
  688. *
  689. * @throws Crypt_GPG_Exception if an unknown or unexpected error occurs.
  690. * Use the <kbd>debug</kbd> option and file a bug report if these
  691. * exceptions occur.
  692. */
  693. public function encryptFile(
  694. $filename,
  695. $encryptedFile = null,
  696. $armor = self::ARMOR_ASCII
  697. ) {
  698. return $this->_encrypt($filename, true, $encryptedFile, $armor);
  699. }
  700. // }}}
  701. // {{{ encryptAndSign()
  702. /**
  703. * Encrypts and signs data
  704. *
  705. * Data is encrypted and signed in a single pass.
  706. *
  707. * NOTE: Until GnuPG version 1.4.10, it was not possible to verify
  708. * encrypted-signed data without decrypting it at the same time. If you try
  709. * to use {@link Crypt_GPG::verify()} method on encrypted-signed data with
  710. * earlier GnuPG versions, you will get an error. Please use
  711. * {@link Crypt_GPG::decryptAndVerify()} to verify encrypted-signed data.
  712. *
  713. * @param string $data the data to be encrypted and signed.
  714. * @param boolean $armor optional. If true, ASCII armored data is returned;
  715. * otherwise, binary data is returned. Defaults to
  716. * true.
  717. *
  718. * @return string the encrypted signed data.
  719. *
  720. * @throws Crypt_GPG_KeyNotFoundException if no encryption key is specified
  721. * or if no signing key is specified. See
  722. * {@link Crypt_GPG::addEncryptKey()} and
  723. * {@link Crypt_GPG::addSignKey()}.
  724. *
  725. * @throws Crypt_GPG_BadPassphraseException if a specified passphrase is
  726. * incorrect or if a required passphrase is not specified.
  727. *
  728. * @throws Crypt_GPG_Exception if an unknown or unexpected error occurs.
  729. * Use the <kbd>debug</kbd> option and file a bug report if these
  730. * exceptions occur.
  731. *
  732. * @see Crypt_GPG::decryptAndVerify()
  733. */
  734. public function encryptAndSign($data, $armor = self::ARMOR_ASCII)
  735. {
  736. return $this->_encryptAndSign($data, false, null, $armor);
  737. }
  738. // }}}
  739. // {{{ encryptAndSignFile()
  740. /**
  741. * Encrypts and signs a file
  742. *
  743. * The file is encrypted and signed in a single pass.
  744. *
  745. * NOTE: Until GnuPG version 1.4.10, it was not possible to verify
  746. * encrypted-signed files without decrypting them at the same time. If you
  747. * try to use {@link Crypt_GPG::verify()} method on encrypted-signed files
  748. * with earlier GnuPG versions, you will get an error. Please use
  749. * {@link Crypt_GPG::decryptAndVerifyFile()} to verify encrypted-signed
  750. * files.
  751. *
  752. * @param string $filename the name of the file containing the data to
  753. * be encrypted and signed.
  754. * @param string $signedFile optional. The name of the file in which the
  755. * encrypted, signed data should be stored. If
  756. * null or unspecified, the encrypted, signed
  757. * data is returned as a string.
  758. * @param boolean $armor optional. If true, ASCII armored data is
  759. * returned; otherwise, binary data is returned.
  760. * Defaults to true.
  761. *
  762. * @return void|string if the <kbd>$signedFile</kbd> parameter is null, a
  763. * string containing the encrypted, signed data is
  764. * returned.
  765. *
  766. * @throws Crypt_GPG_KeyNotFoundException if no encryption key is specified
  767. * or if no signing key is specified. See
  768. * {@link Crypt_GPG::addEncryptKey()} and
  769. * {@link Crypt_GPG::addSignKey()}.
  770. *
  771. * @throws Crypt_GPG_BadPassphraseException if a specified passphrase is
  772. * incorrect or if a required passphrase is not specified.
  773. *
  774. * @throws Crypt_GPG_FileException if the output file is not writeable or
  775. * if the input file is not readable.
  776. *
  777. * @throws Crypt_GPG_Exception if an unknown or unexpected error occurs.
  778. * Use the <kbd>debug</kbd> option and file a bug report if these
  779. * exceptions occur.
  780. *
  781. * @see Crypt_GPG::decryptAndVerifyFile()
  782. */
  783. public function encryptAndSignFile(
  784. $filename,
  785. $signedFile = null,
  786. $armor = self::ARMOR_ASCII
  787. ) {
  788. return $this->_encryptAndSign($filename, true, $signedFile, $armor);
  789. }
  790. // }}}
  791. // {{{ decrypt()
  792. /**
  793. * Decrypts string data
  794. *
  795. * This method assumes the required private key is available in the keyring
  796. * and throws an exception if the private key is not available. To add a
  797. * private key to the keyring, use the {@link Crypt_GPG::importKey()} or
  798. * {@link Crypt_GPG::importKeyFile()} methods.
  799. *
  800. * @param string $encryptedData the data to be decrypted.
  801. *
  802. * @return string the decrypted data.
  803. *
  804. * @throws Crypt_GPG_KeyNotFoundException if the private key needed to
  805. * decrypt the data is not in the user's keyring.
  806. *
  807. * @throws Crypt_GPG_NoDataException if specified data does not contain
  808. * GPG encrypted data.
  809. *
  810. * @throws Crypt_GPG_BadPassphraseException if a required passphrase is
  811. * incorrect or if a required passphrase is not specified. See
  812. * {@link Crypt_GPG::addDecryptKey()}.
  813. *
  814. * @throws Crypt_GPG_Exception if an unknown or unexpected error occurs.
  815. * Use the <kbd>debug</kbd> option and file a bug report if these
  816. * exceptions occur.
  817. */
  818. public function decrypt($encryptedData)
  819. {
  820. return $this->_decrypt($encryptedData, false, null);
  821. }
  822. // }}}
  823. // {{{ decryptFile()
  824. /**
  825. * Decrypts a file
  826. *
  827. * This method assumes the required private key is available in the keyring
  828. * and throws an exception if the private key is not available. To add a
  829. * private key to the keyring, use the {@link Crypt_GPG::importKey()} or
  830. * {@link Crypt_GPG::importKeyFile()} methods.
  831. *
  832. * @param string $encryptedFile the name of the encrypted file data to
  833. * decrypt.
  834. * @param string $decryptedFile optional. The name of the file to which the
  835. * decrypted data should be written. If null
  836. * or unspecified, the decrypted data is
  837. * returned as a string.
  838. *
  839. * @return void|string if the <kbd>$decryptedFile</kbd> parameter is null,
  840. * a string containing the decrypted data is returned.
  841. *
  842. * @throws Crypt_GPG_KeyNotFoundException if the private key needed to
  843. * decrypt the data is not in the user's keyring.
  844. *
  845. * @throws Crypt_GPG_NoDataException if specified data does not contain
  846. * GPG encrypted data.
  847. *
  848. * @throws Crypt_GPG_BadPassphraseException if a required passphrase is
  849. * incorrect or if a required passphrase is not specified. See
  850. * {@link Crypt_GPG::addDecryptKey()}.
  851. *
  852. * @throws Crypt_GPG_FileException if the output file is not writeable or
  853. * if the input file is not readable.
  854. *
  855. * @throws Crypt_GPG_Exception if an unknown or unexpected error occurs.
  856. * Use the <kbd>debug</kbd> option and file a bug report if these
  857. * exceptions occur.
  858. */
  859. public function decryptFile($encryptedFile, $decryptedFile = null)
  860. {
  861. return $this->_decrypt($encryptedFile, true, $decryptedFile);
  862. }
  863. // }}}
  864. // {{{ decryptAndVerify()
  865. /**
  866. * Decrypts and verifies string data
  867. *
  868. * This method assumes the required private key is available in the keyring
  869. * and throws an exception if the private key is not available. To add a
  870. * private key to the keyring, use the {@link Crypt_GPG::importKey()} or
  871. * {@link Crypt_GPG::importKeyFile()} methods.
  872. *
  873. * @param string $encryptedData the encrypted, signed data to be decrypted
  874. * and verified.
  875. *
  876. * @return array two element array. The array has an element 'data'
  877. * containing the decrypted data and an element
  878. * 'signatures' containing an array of
  879. * {@link Crypt_GPG_Signature} objects for the signed data.
  880. *
  881. * @throws Crypt_GPG_KeyNotFoundException if the private key needed to
  882. * decrypt the data is not in the user's keyring.
  883. *
  884. * @throws Crypt_GPG_NoDataException if specified data does not contain
  885. * GPG encrypted data.
  886. *
  887. * @throws Crypt_GPG_BadPassphraseException if a required passphrase is
  888. * incorrect or if a required passphrase is not specified. See
  889. * {@link Crypt_GPG::addDecryptKey()}.
  890. *
  891. * @throws Crypt_GPG_Exception if an unknown or unexpected error occurs.
  892. * Use the <kbd>debug</kbd> option and file a bug report if these
  893. * exceptions occur.
  894. */
  895. public function decryptAndVerify($encryptedData)
  896. {
  897. return $this->_decryptAndVerify($encryptedData, false, null);
  898. }
  899. // }}}
  900. // {{{ decryptAndVerifyFile()
  901. /**
  902. * Decrypts and verifies a signed, encrypted file
  903. *
  904. * This method assumes the required private key is available in the keyring
  905. * and throws an exception if the private key is not available. To add a
  906. * private key to the keyring, use the {@link Crypt_GPG::importKey()} or
  907. * {@link Crypt_GPG::importKeyFile()} methods.
  908. *
  909. * @param string $encryptedFile the name of the signed, encrypted file to
  910. * to decrypt and verify.
  911. * @param string $decryptedFile optional. The name of the file to which the
  912. * decrypted data should be written. If null
  913. * or unspecified, the decrypted data is
  914. * returned in the results array.
  915. *
  916. * @return array two element array. The array has an element 'data'
  917. * containing the decrypted data and an element
  918. * 'signatures' containing an array of
  919. * {@link Crypt_GPG_Signature} objects for the signed data.
  920. * If the decrypted data is written to a file, the 'data'
  921. * element is null.
  922. *
  923. * @throws Crypt_GPG_KeyNotFoundException if the private key needed to
  924. * decrypt the data is not in the user's keyring.
  925. *
  926. * @throws Crypt_GPG_NoDataException if specified data does not contain
  927. * GPG encrypted data.
  928. *
  929. * @throws Crypt_GPG_BadPassphraseException if a required passphrase is
  930. * incorrect or if a required passphrase is not specified. See
  931. * {@link Crypt_GPG::addDecryptKey()}.
  932. *
  933. * @throws Crypt_GPG_FileException if the output file is not writeable or
  934. * if the input file is not readable.
  935. *
  936. * @throws Crypt_GPG_Exception if an unknown or unexpected error occurs.
  937. * Use the <kbd>debug</kbd> option and file a bug report if these
  938. * exceptions occur.
  939. */
  940. public function decryptAndVerifyFile($encryptedFile, $decryptedFile = null)
  941. {
  942. return $this->_decryptAndVerify($encryptedFile, true, $decryptedFile);
  943. }
  944. // }}}
  945. // {{{ sign()
  946. /**
  947. * Signs data
  948. *
  949. * Data may be signed using any one of the three available signing modes:
  950. * - {@link Crypt_GPG::SIGN_MODE_NORMAL}
  951. * - {@link Crypt_GPG::SIGN_MODE_CLEAR}
  952. * - {@link Crypt_GPG::SIGN_MODE_DETACHED}
  953. *
  954. * @param string $data the data to be signed.
  955. * @param boolean $mode optional. The data signing mode to use. Should
  956. * be one of {@link Crypt_GPG::SIGN_MODE_NORMAL},
  957. * {@link Crypt_GPG::SIGN_MODE_CLEAR} or
  958. * {@link Crypt_GPG::SIGN_MODE_DETACHED}. If not
  959. * specified, defaults to
  960. * <kbd>Crypt_GPG::SIGN_MODE_NORMAL</kbd>.
  961. * @param boolean $armor optional. If true, ASCII armored data is
  962. * returned; otherwise, binary data is returned.
  963. * Defaults to true. This has no effect if the
  964. * mode <kbd>Crypt_GPG::SIGN_MODE_CLEAR</kbd> is
  965. * used.
  966. * @param boolean $textmode optional. If true, line-breaks in signed data
  967. * are normalized. Use this option when signing
  968. * e-mail, or for greater compatibility between
  969. * systems with different line-break formats.
  970. * Defaults to false. This has no effect if the
  971. * mode <kbd>Crypt_GPG::SIGN_MODE_CLEAR</kbd> is
  972. * used as clear-signing always uses textmode.
  973. *
  974. * @return string the signed data, or the signature data if a detached
  975. * signature is requested.
  976. *
  977. * @throws Crypt_GPG_KeyNotFoundException if no signing key is specified.
  978. * See {@link Crypt_GPG::addSignKey()}.
  979. *
  980. * @throws Crypt_GPG_BadPassphraseException if a specified passphrase is
  981. * incorrect or if a required passphrase is not specified.
  982. *
  983. * @throws Crypt_GPG_Exception if an unknown or unexpected error occurs.
  984. * Use the <kbd>debug</kbd> option and file a bug report if these
  985. * exceptions occur.
  986. */
  987. public function sign(
  988. $data,
  989. $mode = self::SIGN_MODE_NORMAL,
  990. $armor = self::ARMOR_ASCII,
  991. $textmode = self::TEXT_RAW
  992. ) {
  993. return $this->_sign($data, false, null, $mode, $armor, $textmode);
  994. }
  995. // }}}
  996. // {{{ signFile()
  997. /**
  998. * Signs a file
  999. *
  1000. * The file may be signed using any one of the three available signing
  1001. * modes:
  1002. * - {@link Crypt_GPG::SIGN_MODE_NORMAL}
  1003. * - {@link Crypt_GPG::SIGN_MODE_CLEAR}
  1004. * - {@link Crypt_GPG::SIGN_MODE_DETACHED}
  1005. *
  1006. * @param string $filename the name of the file containing the data to
  1007. * be signed.
  1008. * @param string $signedFile optional. The name of the file in which the
  1009. * signed data should be stored. If null or
  1010. * unspecified, the signed data is returned as a
  1011. * string.
  1012. * @param boolean $mode optional. The data signing mode to use. Should
  1013. * be one of {@link Crypt_GPG::SIGN_MODE_NORMAL},
  1014. * {@link Crypt_GPG::SIGN_MODE_CLEAR} or
  1015. * {@link Crypt_GPG::SIGN_MODE_DETACHED}. If not
  1016. * specified, defaults to
  1017. * <kbd>Crypt_GPG::SIGN_MODE_NORMAL</kbd>.
  1018. * @param boolean $armor optional. If true, ASCII armored data is
  1019. * returned; otherwise, binary data is returned.
  1020. * Defaults to true. This has no effect if the
  1021. * mode <kbd>Crypt_GPG::SIGN_MODE_CLEAR</kbd> is
  1022. * used.
  1023. * @param boolean $textmode optional. If true, line-breaks in signed data
  1024. * are normalized. Use this option when signing
  1025. * e-mail, or for greater compatibility between
  1026. * systems with different line-break formats.
  1027. * Defaults to false. This has no effect if the
  1028. * mode <kbd>Crypt_GPG::SIGN_MODE_CLEAR</kbd> is
  1029. * used as clear-signing always uses textmode.
  1030. *
  1031. * @return void|string if the <kbd>$signedFile</kbd> parameter is null, a
  1032. * string containing the signed data (or the signature
  1033. * data if a detached signature is requested) is
  1034. * returned.
  1035. *
  1036. * @throws Crypt_GPG_KeyNotFoundException if no signing key is specified.
  1037. * See {@link Crypt_GPG::addSignKey()}.
  1038. *
  1039. * @throws Crypt_GPG_BadPassphraseException if a specified passphrase is
  1040. * incorrect or if a required passphrase is not specified.
  1041. *
  1042. * @throws Crypt_GPG_FileException if the output file is not writeable or
  1043. * if the input file is not readable.
  1044. *
  1045. * @throws Crypt_GPG_Exception if an unknown or unexpected error occurs.
  1046. * Use the <kbd>debug</kbd> option and file a bug report if these
  1047. * exceptions occur.
  1048. */
  1049. public function signFile(
  1050. $filename,
  1051. $signedFile = null,
  1052. $mode = self::SIGN_MODE_NORMAL,
  1053. $armor = self::ARMOR_ASCII,
  1054. $textmode = self::TEXT_RAW
  1055. ) {
  1056. return $this->_sign(
  1057. $filename,
  1058. true,
  1059. $signedFile,
  1060. $mode,
  1061. $armor,
  1062. $textmode
  1063. );
  1064. }
  1065. // }}}
  1066. // {{{ verify()
  1067. /**
  1068. * Verifies signed data
  1069. *
  1070. * The {@link Crypt_GPG::decrypt()} method may be used to get the original
  1071. * message if the signed data is not clearsigned and does not use a
  1072. * detached signature.
  1073. *
  1074. * @param string $signedData the signed data to be verified.
  1075. * @param string $signature optional. If verifying data signed using a
  1076. * detached signature, this must be the detached
  1077. * signature data. The data that was signed is
  1078. * specified in <kbd>$signedData</kbd>.
  1079. *
  1080. * @return array an array of {@link Crypt_GPG_Signature} objects for the
  1081. * signed data. For each signature that is valid, the
  1082. * {@link Crypt_GPG_Signature::isValid()} will return true.
  1083. *
  1084. * @throws Crypt_GPG_NoDataException if the provided data is not signed
  1085. * data.
  1086. *
  1087. * @throws Crypt_GPG_Exception if an unknown or unexpected error occurs.
  1088. * Use the <kbd>debug</kbd> option and file a bug report if these
  1089. * exceptions occur.
  1090. *
  1091. * @see Crypt_GPG_Signature
  1092. */
  1093. public function verify($signedData, $signature = '')
  1094. {
  1095. return $this->_verify($signedData, false, $signature);
  1096. }
  1097. // }}}
  1098. // {{{ verifyFile()
  1099. /**
  1100. * Verifies a signed file
  1101. *
  1102. * The {@link Crypt_GPG::decryptFile()} method may be used to get the
  1103. * original message if the signed data is not clearsigned and does not use
  1104. * a detached signature.
  1105. *
  1106. * @param string $filename the signed file to be verified.
  1107. * @param string $signature optional. If verifying a file signed using a
  1108. * detached signature, this must be the detached
  1109. * signature data. The file that was signed is
  1110. * specified in <kbd>$filename</kbd>.
  1111. *
  1112. * @return array an array of {@link Crypt_GPG_Signature} objects for the
  1113. * signed data. For each signature that is valid, the
  1114. * {@link Crypt_GPG_Signature::isValid()} will return true.
  1115. *
  1116. * @throws Crypt_GPG_NoDataException if the provided data is not signed
  1117. * data.
  1118. *
  1119. * @throws Crypt_GPG_FileException if the input file is not readable.
  1120. *
  1121. * @throws Crypt_GPG_Exception if an unknown or unexpected error occurs.
  1122. * Use the <kbd>debug</kbd> option and file a bug report if these
  1123. * exceptions occur.
  1124. *
  1125. * @see Crypt_GPG_Signature
  1126. */
  1127. public function verifyFile($filename, $signature = '')
  1128. {
  1129. return $this->_verify($filename, true, $signature);
  1130. }
  1131. // }}}
  1132. // {{{ addDecryptKey()
  1133. /**
  1134. * Adds a key to use for decryption
  1135. *
  1136. * @param mixed $key the key to use. This may be a key identifier,
  1137. * user id, fingerprint, {@link Crypt_GPG_Key} or
  1138. * {@link Crypt_GPG_SubKey}. The key must be able
  1139. * to encrypt.
  1140. * @param string $passphrase optional. The passphrase of the key required
  1141. * for decryption.
  1142. *
  1143. * @return Crypt_GPG the current object, for fluent interface.
  1144. *
  1145. * @see Crypt_GPG::decrypt()
  1146. * @see Crypt_GPG::decryptFile()
  1147. * @see Crypt_GPG::clearDecryptKeys()
  1148. * @see Crypt_GPG::_addKey()
  1149. * @see Crypt_GPG_DecryptStatusHandler
  1150. *
  1151. * @sensitive $passphrase
  1152. */
  1153. public function addDecryptKey($key, $passphrase = null)
  1154. {
  1155. $this->_addKey($this->decryptKeys, false, false, $key, $passphrase);
  1156. return $this;
  1157. }
  1158. // }}}
  1159. // {{{ addEncryptKey()
  1160. /**
  1161. * Adds a key to use for encryption
  1162. *
  1163. * @param mixed $key the key to use. This may be a key identifier, user id
  1164. * user id, fingerprint, {@link Crypt_GPG_Key} or
  1165. * {@link Crypt_GPG_SubKey}. The key must be able to
  1166. * encrypt.
  1167. *
  1168. * @return Crypt_GPG the current object, for fluent interface.
  1169. *
  1170. * @see Crypt_GPG::encrypt()
  1171. * @see Crypt_GPG::encryptFile()
  1172. * @see Crypt_GPG::clearEncryptKeys()
  1173. * @see Crypt_GPG::_addKey()
  1174. */
  1175. public function addEncryptKey($key)
  1176. {
  1177. $this->_addKey($this->encryptKeys, true, false, $key);
  1178. return $this;
  1179. }
  1180. // }}}
  1181. // {{{ addSignKey()
  1182. /**
  1183. * Adds a key to use for signing
  1184. *
  1185. * @param mixed $key the key to use. This may be a key identifier,
  1186. * user id, fingerprint, {@link Crypt_GPG_Key} or
  1187. * {@link Crypt_GPG_SubKey}. The key must be able
  1188. * to sign.
  1189. * @param string $passphrase optional. The passphrase of the key required
  1190. * for signing.
  1191. *
  1192. * @return Crypt_GPG the current object, for fluent interface.
  1193. *
  1194. * @see Crypt_GPG::sign()
  1195. * @see Crypt_GPG::signFile()
  1196. * @see Crypt_GPG::clearSignKeys()
  1197. * @see Crypt_GPG::handleSignStatus()
  1198. * @see Crypt_GPG::_addKey()
  1199. *
  1200. * @sensitive $passphrase
  1201. */
  1202. public function addSignKey($key, $passphrase = null)
  1203. {
  1204. $this->_addKey($this->signKeys, false, true, $key, $passphrase);
  1205. return $this;
  1206. }
  1207. // }}}
  1208. // {{{ clearDecryptKeys()
  1209. /**
  1210. * Clears all decryption keys
  1211. *
  1212. * @return Crypt_GPG the current object, for fluent interface.
  1213. *
  1214. * @see Crypt_GPG::decrypt()
  1215. * @see Crypt_GPG::addDecryptKey()
  1216. */
  1217. public function clearDecryptKeys()
  1218. {
  1219. $this->decryptKeys = array();
  1220. return $this;
  1221. }
  1222. // }}}
  1223. // {{{ clearEncryptKeys()
  1224. /**
  1225. * Clears all encryption keys
  1226. *
  1227. * @return Crypt_GPG the current object, for fluent interface.
  1228. *
  1229. * @see Crypt_GPG::encrypt()
  1230. * @see Crypt_GPG::addEncryptKey()
  1231. */
  1232. public function clearEncryptKeys()
  1233. {
  1234. $this->encryptKeys = array();
  1235. return $this;
  1236. }
  1237. // }}}
  1238. // {{{ clearSignKeys()
  1239. /**
  1240. * Clears all signing keys
  1241. *
  1242. * @return Crypt_GPG the current object, for fluent interface.
  1243. *
  1244. * @see Crypt_GPG::sign()
  1245. * @see Crypt_GPG::addSignKey()
  1246. */
  1247. public function clearSignKeys()
  1248. {
  1249. $this->signKeys = array();
  1250. return $this;
  1251. }
  1252. // }}}
  1253. // {{{ handleSignStatus()
  1254. /**
  1255. * Handles the status output from GPG for the sign operation
  1256. *
  1257. * This method is responsible for sending the passphrase commands when
  1258. * required by the {@link Crypt_GPG::sign()} method. See <b>doc/DETAILS</b>
  1259. * in the {@link http://www.gnupg.org/download/ GPG distribution} for
  1260. * detailed information on GPG's status output.
  1261. *
  1262. * @param string $line the status line to handle.
  1263. *
  1264. * @return void
  1265. *
  1266. * @see Crypt_GPG::sign()
  1267. */
  1268. public function handleSignStatus($line)
  1269. {
  1270. $tokens = explode(' ', $line);
  1271. switch ($tokens[0]) {
  1272. case 'NEED_PASSPHRASE':
  1273. $subKeyId = $tokens[1];
  1274. if (array_key_exists($subKeyId, $this->signKeys)) {
  1275. $passphrase = $this->signKeys[$subKeyId]['passphrase'];
  1276. $this->engine->sendCommand($passphrase);
  1277. } else {
  1278. $this->engine->sendCommand('');
  1279. }
  1280. break;
  1281. case 'SIG_CREATED':
  1282. $this->lastSignatureInfo = $line;
  1283. break;
  1284. }
  1285. }
  1286. // }}}
  1287. // {{{ handleImportKeyStatus()
  1288. /**
  1289. * Handles the status output from GPG for the import operation
  1290. *
  1291. * This method is responsible for building the result array that is
  1292. * returned from the {@link Crypt_GPG::importKey()} method. See
  1293. * <b>doc/DETAILS</b> in the
  1294. * {@link http://www.gnupg.org/download/ GPG distribution} for detailed
  1295. * information on GPG's status output.
  1296. *
  1297. * @param string $line the status line to handle.
  1298. * @param array &$result the current result array being processed.
  1299. *
  1300. * @return void
  1301. *
  1302. * @see Crypt_GPG::importKey()
  1303. * @see Crypt_GPG::importKeyFile()
  1304. * @see Crypt_GPG_Engine::addStatusHandler()
  1305. */
  1306. public function handleImportKeyStatus($line, array &$result)
  1307. {
  1308. $tokens = explode(' ', $line);
  1309. switch ($tokens[0]) {
  1310. case 'IMPORT_OK':
  1311. $result['fingerprint'] = $tokens[2];
  1312. if (empty($result['fingerprints'])) {
  1313. $result['fingerprints'] = array($tokens[2]);
  1314. } else if (!in_array($tokens[2], $result['fingerprints'])) {
  1315. $result['fingerprints'][] = $tokens[2];
  1316. }
  1317. break;
  1318. case 'IMPORT_RES':
  1319. $result['public_imported'] = intval($tokens[3]);
  1320. $result['public_unchanged'] = intval($tokens[5]);
  1321. $result['private_imported'] = intval($tokens[11]);
  1322. $result['private_unchanged'] = intval($tokens[12]);
  1323. break;
  1324. }
  1325. }
  1326. // }}}
  1327. /**
  1328. * Tell if there are encryption keys registered
  1329. *
  1330. * @return boolean True if the data shall be encrypted
  1331. */
  1332. public function hasEncryptKeys()
  1333. {
  1334. return count($this->encryptKeys) > 0;
  1335. }
  1336. /**
  1337. * Tell if there are signing keys registered
  1338. *
  1339. * @return boolean True if the data shall be signed
  1340. */
  1341. public function hasSignKeys()
  1342. {
  1343. return count($this->signKeys) > 0;
  1344. }
  1345. // {{{ _addKey()
  1346. /**
  1347. * Adds a key to one of the internal key arrays
  1348. *
  1349. * This handles resolving full key objects from the provided
  1350. * <kbd>$key</kbd> value.
  1351. *
  1352. * @param array &$array the array to which the key should be added.
  1353. * @param boolean $encrypt whether or not the key must be able to
  1354. * encrypt.
  1355. * @param boolean $sign whether or not the key must be able to sign.
  1356. * @param mixed $key the key to add. This may be a key identifier,
  1357. * user id, fingerprint, {@link Crypt_GPG_Key} or
  1358. * {@link Crypt_GPG_SubKey}.
  1359. * @param string $passphrase optional. The passphrase associated with the
  1360. * key.
  1361. *
  1362. * @return void
  1363. *
  1364. * @sensitive $passphrase
  1365. */
  1366. protected function _addKey(array &$array, $encrypt, $sign, $key,
  1367. $passphrase = null
  1368. ) {
  1369. $subKeys = array();
  1370. if (is_scalar($key)) {
  1371. $keys = $this->getKeys($key);
  1372. if (count($keys) == 0) {
  1373. throw new Crypt_GPG_KeyNotFoundException(
  1374. 'Key "' . $key . '" not found.',
  1375. 0,
  1376. $key
  1377. );
  1378. }
  1379. $key = $keys[0];
  1380. }
  1381. if ($key instanceof Crypt_GPG_Key) {
  1382. if ($encrypt && !$key->canEncrypt()) {
  1383. throw new InvalidArgumentException(
  1384. 'Key "' . $key . '" cannot encrypt.'
  1385. );
  1386. }
  1387. if ($sign && !$key->canSign()) {
  1388. throw new InvalidArgumentException(
  1389. 'Key "' . $key . '" cannot sign.'
  1390. );
  1391. }
  1392. foreach ($key->getSubKeys() as $subKey) {
  1393. $canEncrypt = $subKey->canEncrypt();
  1394. $canSign = $subKey->canSign();
  1395. if ( ($encrypt && $sign && $canEncrypt && $canSign)
  1396. || ($encrypt && !$sign && $canEncrypt)
  1397. || (!$encrypt && $sign && $canSign)
  1398. || (!$encrypt && !$sign)
  1399. ) {
  1400. // We add all subkeys that meet the requirements because we
  1401. // were not told which subkey is required.
  1402. $subKeys[] = $subKey;
  1403. }
  1404. }
  1405. } elseif ($key instanceof Crypt_GPG_SubKey) {
  1406. $subKeys[] = $key;
  1407. }
  1408. if (count($subKeys) === 0) {
  1409. throw new InvalidArgumentException(
  1410. 'Key "' . $key . '" is not in a recognized format.'
  1411. );
  1412. }
  1413. foreach ($subKeys as $subKey) {
  1414. if ($encrypt && !$subKey->canEncrypt()) {
  1415. throw new InvalidArgumentException(
  1416. 'Key "' . $key . '" cannot encrypt.'
  1417. );
  1418. }
  1419. if ($sign && !$subKey->canSign()) {
  1420. throw new InvalidArgumentException(
  1421. 'Key "' . $key . '" cannot sign.'
  1422. );
  1423. }
  1424. $array[$subKey->getId()] = array(
  1425. 'fingerprint' => $subKey->getFingerprint(),
  1426. 'passphrase' => $passphrase
  1427. );
  1428. }
  1429. }
  1430. // }}}
  1431. // {{{ _setPinEntryEnv()
  1432. /**
  1433. * Sets the PINENTRY_USER_DATA environment variable with the currently
  1434. * added keys and passphrases
  1435. *
  1436. * Keys and pasphrases are stored as an indexed array of associative
  1437. * arrays that is JSON encoded to a flat string.
  1438. *
  1439. * For GnuPG 2.x this is how passphrases are passed. For GnuPG 1.x the
  1440. * environment variable is set but not used.
  1441. *
  1442. * @param array $keys the internal key array to use.
  1443. *
  1444. * @return void
  1445. */
  1446. protected function _setPinEntryEnv(array $keys)
  1447. {
  1448. $envKeys = array();
  1449. foreach ($keys as $id => $key) {
  1450. $envKeys[] = array(
  1451. 'keyId' => $id,
  1452. 'fingerprint' => $key['fingerprint'],
  1453. 'passphrase' => $key['passphrase']
  1454. );
  1455. }
  1456. $envKeys = json_encode($envKeys);
  1457. $_ENV['PINENTRY_USER_DATA'] = $envKeys;
  1458. }
  1459. // }}}
  1460. // {{{ _importKey()
  1461. /**
  1462. * Imports a public or private key into the keyring
  1463. *
  1464. * @param string $key the key to be imported.
  1465. * @param boolean $isFile whether or not the input is a filename.
  1466. *
  1467. * @return array an associative array containing the following elements:
  1468. * - <kbd>fingerprint</kbd> - the fingerprint of the
  1469. * imported key,
  1470. * - <kbd>public_imported</kbd> - the number of public
  1471. * keys imported,
  1472. * - <kbd>public_unchanged</kbd> - the number of unchanged
  1473. * public keys,
  1474. * - <kbd>private_imported</kbd> - the number of private
  1475. * keys imported,
  1476. * - <kbd>private_unchanged</kbd> - the number of unchanged
  1477. * private keys.
  1478. *
  1479. * @throws Crypt_GPG_NoDataException if the key data is missing or if the
  1480. * data is is not valid key data.
  1481. *
  1482. * @throws Crypt_GPG_FileException if the key file is not readable.
  1483. *
  1484. * @throws Crypt_GPG_Exception if an unknown or unexpected error occurs.
  1485. * Use the <kbd>debug</kbd> option and file a bug report if these
  1486. * exceptions occur.
  1487. */
  1488. protected function _importKey($key, $isFile)
  1489. {
  1490. $result = array();
  1491. if ($isFile) {
  1492. $input = @fopen($key, 'rb');
  1493. if ($input === false) {
  1494. throw new Crypt_GPG_FileException(
  1495. 'Could not open key file "' . $key . '" for importing.',
  1496. 0,
  1497. $key
  1498. );
  1499. }
  1500. } else {
  1501. $input = strval($key);
  1502. if ($input == '') {
  1503. throw new Crypt_GPG_NoDataException(
  1504. 'No valid GPG key data found.',
  1505. self::ERROR_NO_DATA
  1506. );
  1507. }
  1508. }
  1509. $arguments = array();
  1510. $version = $this->engine->getVersion();
  1511. if ( version_compare($version, '1.0.5', 'ge')
  1512. && version_compare($version, '1.0.7', 'lt')
  1513. ) {
  1514. $arguments[] = '--allow-secret-key-import';
  1515. }
  1516. $this->engine->reset();
  1517. $this->engine->addStatusHandler(
  1518. array($this, 'handleImportKeyStatus'),
  1519. array(&$result)
  1520. );
  1521. $this->engine->setOperation('--import', $arguments);
  1522. $this->engine->setInput($input);
  1523. $this->engine->run();
  1524. if ($isFile) {
  1525. fclose($input);
  1526. }
  1527. $code = $this->engine->getErrorCode();
  1528. switch ($code) {
  1529. case self::ERROR_DUPLICATE_KEY:
  1530. case self::ERROR_NONE:
  1531. // ignore duplicate key import errors
  1532. break;
  1533. case self::ERROR_NO_DATA:
  1534. throw new Crypt_GPG_NoDataException(
  1535. 'No valid GPG key data found.',
  1536. $code
  1537. );
  1538. default:
  1539. throw new Crypt_GPG_Exception(
  1540. 'Unknown error importing GPG key. Please use the \'debug\' ' .
  1541. 'option when creating the Crypt_GPG object, and file a bug ' .
  1542. 'report at ' . self::BUG_URI,
  1543. $code
  1544. );
  1545. }
  1546. return $result;
  1547. }
  1548. // }}}
  1549. // {{{ _exportKey()
  1550. /**
  1551. * Exports a private or public key from the keyring
  1552. *
  1553. * If more than one key fingerprint is available for the specified
  1554. * <kbd>$keyId</kbd> (for example, if you use a non-unique uid) only the
  1555. * first key is exported.
  1556. *
  1557. * @param string $keyId either the full uid of the key, the email
  1558. * part of the uid of the key or the key id.
  1559. * @param boolean $armor optional. If true, ASCII armored data is returned;
  1560. * otherwise, binary data is returned. Defaults to
  1561. * true.
  1562. * @param boolean $private return private instead of public key
  1563. *
  1564. * @return string the key data.
  1565. *
  1566. * @throws Crypt_GPG_KeyNotFoundException if a key with the given
  1567. * <kbd>$keyId</kbd> is not found.
  1568. *
  1569. * @throws Crypt_GPG_Exception if an unknown or unexpected error occurs.
  1570. * Use the <kbd>debug</kbd> option and file a bug report if these
  1571. * exceptions occur.
  1572. */
  1573. public function _exportKey($keyId, $armor = true, $private = false)
  1574. {
  1575. $fingerprint = $this->getFingerprint($keyId);
  1576. if ($fingerprint === null) {
  1577. throw new Crypt_GPG_KeyNotFoundException(
  1578. 'Key not found: ' . $keyId,
  1579. self::ERROR_KEY_NOT_FOUND,
  1580. $keyId
  1581. );
  1582. }
  1583. $keyData = '';
  1584. $operation = $private ? '--export-secret-keys' : '--export';
  1585. $operation .= ' ' . escapeshellarg($fingerprint);
  1586. $arguments = ($armor) ? array('--armor') : array();
  1587. $this->engine->reset();
  1588. $this->engine->setOutput($keyData);
  1589. $this->engine->setOperation($operation, $arguments);
  1590. $this->engine->run();
  1591. $code = $this->engine->getErrorCode();
  1592. if ($code !== self::ERROR_NONE) {
  1593. throw new Crypt_GPG_Exception(
  1594. 'Unknown error exporting a key. Please use the ' .
  1595. '\'debug\' option when creating the Crypt_GPG object, and ' .
  1596. 'file a bug report at ' . self::BUG_URI,
  1597. $code
  1598. );
  1599. }
  1600. return $keyData;
  1601. }
  1602. // }}}
  1603. // {{{ _encrypt()
  1604. /**
  1605. * Encrypts data
  1606. *
  1607. * @param string $data the data to encrypt.
  1608. * @param boolean $isFile whether or not the data is a filename.
  1609. * @param string $outputFile the filename of the file in which to store
  1610. * the encrypted data. If null, the encrypted
  1611. * data is returned as a string.
  1612. * @param boolean $armor if true, ASCII armored data is returned;
  1613. * otherwise, binary data is returned.
  1614. *
  1615. * @return void|string if the <kbd>$outputFile</kbd> parameter is null, a
  1616. * string containing the encrypted data is returned.
  1617. *
  1618. * @throws Crypt_GPG_KeyNotFoundException if no encryption key is specified.
  1619. * See {@link Crypt_GPG::addEncryptKey()}.
  1620. *
  1621. * @throws Crypt_GPG_FileException if the output file is not writeable or
  1622. * if the input file is not readable.
  1623. *
  1624. * @throws Crypt_GPG_Exception if an unknown or unexpected error occurs.
  1625. * Use the <kbd>debug</kbd> option and file a bug report if these
  1626. * exceptions occur.
  1627. */
  1628. protected function _encrypt($data, $isFile, $outputFile, $armor)
  1629. {
  1630. if (!$this->hasEncryptKeys()) {
  1631. throw new Crypt_GPG_KeyNotFoundException(
  1632. 'No encryption keys specified.'
  1633. );
  1634. }
  1635. if ($isFile) {
  1636. $input = @fopen($data, 'rb');
  1637. if ($input === false) {
  1638. throw new Crypt_GPG_FileException(
  1639. 'Could not open input file "' . $data .
  1640. '" for encryption.',
  1641. 0,
  1642. $data
  1643. );
  1644. }
  1645. } else {
  1646. $input = strval($data);
  1647. }
  1648. if ($outputFile === null) {
  1649. $output = '';
  1650. } else {
  1651. $output = @fopen($outputFile, 'wb');
  1652. if ($output === false) {
  1653. if ($isFile) {
  1654. fclose($input);
  1655. }
  1656. throw new Crypt_GPG_FileException(
  1657. 'Could not open output file "' . $outputFile .
  1658. '" for storing encrypted data.',
  1659. 0,
  1660. $outputFile
  1661. );
  1662. }
  1663. }
  1664. $arguments = ($armor) ? array('--armor') : array();
  1665. foreach ($this->encryptKeys as $key) {
  1666. $arguments[] = '--recipient ' . escapeshellarg($key['fingerprint']);
  1667. }
  1668. $this->engine->reset();
  1669. $this->engine->setInput($input);
  1670. $this->engine->setOutput($output);
  1671. $this->engine->setOperation('--encrypt', $arguments);
  1672. $this->engine->run();
  1673. if ($isFile) {
  1674. fclose($input);
  1675. }
  1676. if ($outputFile !== null) {
  1677. fclose($output);
  1678. }
  1679. $code = $this->engine->getErrorCode();
  1680. if ($code !== self::ERROR_NONE) {
  1681. throw new Crypt_GPG_Exception(
  1682. 'Unknown error encrypting data. Please use the \'debug\' ' .
  1683. 'option when creating the Crypt_GPG object, and file a bug ' .
  1684. 'report at ' . self::BUG_URI,
  1685. $code
  1686. );
  1687. }
  1688. if ($outputFile === null) {
  1689. return $output;
  1690. }
  1691. }
  1692. // }}}
  1693. // {{{ _decrypt()
  1694. /**
  1695. * Decrypts data
  1696. *
  1697. * @param string $data the data to be decrypted.
  1698. * @param boolean $isFile whether or not the data is a filename.
  1699. * @param string $outputFile the name of the file to which the decrypted
  1700. * data should be written. If null, the decrypted
  1701. * data is returned as a string.
  1702. *
  1703. * @return void|string if the <kbd>$outputFile</kbd> parameter is null, a
  1704. * string containing the decrypted data is returned.
  1705. *
  1706. * @throws Crypt_GPG_KeyNotFoundException if the private key needed to
  1707. * decrypt the data is not in the user's keyring.
  1708. *
  1709. * @throws Crypt_GPG_NoDataException if specified data does not contain
  1710. * GPG encrypted data.
  1711. *
  1712. * @throws Crypt_GPG_BadPassphraseException if a required passphrase is
  1713. * incorrect or if a required passphrase is not specified. See
  1714. * {@link Crypt_GPG::addDecryptKey()}.
  1715. *
  1716. * @throws Crypt_GPG_FileException if the output file is not writeable or
  1717. * if the input file is not readable.
  1718. *
  1719. * @throws Crypt_GPG_Exception if an unknown or unexpected error occurs.
  1720. * Use the <kbd>debug</kbd> option and file a bug report if these
  1721. * exceptions occur.
  1722. */
  1723. protected function _decrypt($data, $isFile, $outputFile)
  1724. {
  1725. if ($isFile) {
  1726. $input = @fopen($data, 'rb');
  1727. if ($input === false) {
  1728. throw new Crypt_GPG_FileException(
  1729. 'Could not open input file "' . $data .
  1730. '" for decryption.',
  1731. 0,
  1732. $data
  1733. );
  1734. }
  1735. } else {
  1736. $input = strval($data);
  1737. if ($input == '') {
  1738. throw new Crypt_GPG_NoDataException(
  1739. 'Cannot decrypt data. No PGP encrypted data was found in '.
  1740. 'the provided data.',
  1741. self::ERROR_NO_DATA
  1742. );
  1743. }
  1744. }
  1745. if ($outputFile === null) {
  1746. $output = '';
  1747. } else {
  1748. $output = @fopen($outputFile, 'wb');
  1749. if ($output === false) {
  1750. if ($isFile) {
  1751. fclose($input);
  1752. }
  1753. throw new Crypt_GPG_FileException(
  1754. 'Could not open output file "' . $outputFile .
  1755. '" for storing decrypted data.',
  1756. 0,
  1757. $outputFile
  1758. );
  1759. }
  1760. }
  1761. $handler = new Crypt_GPG_DecryptStatusHandler(
  1762. $this->engine,
  1763. $this->decryptKeys
  1764. );
  1765. // If using gpg-agent, set the decrypt pins used by the pinentry
  1766. $this->_setPinEntryEnv($this->decryptKeys);
  1767. $this->engine->reset();
  1768. $this->engine->addStatusHandler(array($handler, 'handle'));
  1769. $this->engine->setOperation('--decrypt');
  1770. $this->engine->setInput($input);
  1771. $this->engine->setOutput($output);
  1772. $this->engine->run();
  1773. if ($isFile) {
  1774. fclose($input);
  1775. }
  1776. if ($outputFile !== null) {
  1777. fclose($output);
  1778. }
  1779. // if there was any problem decrypting the data, the handler will
  1780. // deal with it here.
  1781. $handler->throwException();
  1782. if ($outputFile === null) {
  1783. return $output;
  1784. }
  1785. }
  1786. // }}}
  1787. // {{{ _sign()
  1788. /**
  1789. * Signs data
  1790. *
  1791. * @param string $data the data to be signed.
  1792. * @param boolean $isFile whether or not the data is a filename.
  1793. * @param string $outputFile the name of the file in which the signed data
  1794. * should be stored. If null, the signed data is
  1795. * returned as a string.
  1796. * @param boolean $mode the data signing mode to use. Should be one of
  1797. * {@link Crypt_GPG::SIGN_MODE_NORMAL},
  1798. * {@link Crypt_GPG::SIGN_MODE_CLEAR} or
  1799. * {@link Crypt_GPG::SIGN_MODE_DETACHED}.
  1800. * @param boolean $armor if true, ASCII armored data is returned;
  1801. * otherwise, binary data is returned. This has
  1802. * no effect if the mode
  1803. * <kbd>Crypt_GPG::SIGN_MODE_CLEAR</kbd> is
  1804. * used.
  1805. * @param boolean $textmode if true, line-breaks in signed data be
  1806. * normalized. Use this option when signing
  1807. * e-mail, or for greater compatibility between
  1808. * systems with different line-break formats.
  1809. * Defaults to false. This has no effect if the
  1810. * mode <kbd>Crypt_GPG::SIGN_MODE_CLEAR</kbd> is
  1811. * used as clear-signing always uses textmode.
  1812. *
  1813. * @return void|string if the <kbd>$outputFile</kbd> parameter is null, a
  1814. * string containing the signed data (or the signature
  1815. * data if a detached signature is requested) is
  1816. * returned.
  1817. *
  1818. * @throws Crypt_GPG_KeyNotFoundException if no signing key is specified.
  1819. * See {@link Crypt_GPG::addSignKey()}.
  1820. *
  1821. * @throws Crypt_GPG_BadPassphraseException if a specified passphrase is
  1822. * incorrect or if a required passphrase is not specified.
  1823. *
  1824. * @throws Crypt_GPG_FileException if the output file is not writeable or
  1825. * if the input file is not readable.
  1826. *
  1827. * @throws Crypt_GPG_Exception if an unknown or unexpected error occurs.
  1828. * Use the <kbd>debug</kbd> option and file a bug report if these
  1829. * exceptions occur.
  1830. */
  1831. protected function _sign($data, $isFile, $outputFile, $mode, $armor,
  1832. $textmode
  1833. ) {
  1834. $this->lastSignatureInfo = null;
  1835. if (!$this->hasSignKeys()) {
  1836. throw new Crypt_GPG_KeyNotFoundException(
  1837. 'No signing keys specified.'
  1838. );
  1839. }
  1840. if ($isFile) {
  1841. $input = @fopen($data, 'rb');
  1842. if ($input === false) {
  1843. throw new Crypt_GPG_FileException(
  1844. 'Could not open input file "' . $data . '" for signing.',
  1845. 0,
  1846. $data
  1847. );
  1848. }
  1849. } else {
  1850. $input = strval($data);
  1851. }
  1852. if ($outputFile === null) {
  1853. $output = '';
  1854. } else {
  1855. $output = @fopen($outputFile, 'wb');
  1856. if ($output === false) {
  1857. if ($isFile) {
  1858. fclose($input);
  1859. }
  1860. throw new Crypt_GPG_FileException(
  1861. 'Could not open output file "' . $outputFile .
  1862. '" for storing signed data.',
  1863. 0,
  1864. $outputFile
  1865. );
  1866. }
  1867. }
  1868. switch ($mode) {
  1869. case self::SIGN_MODE_DETACHED:
  1870. $operation = '--detach-sign';
  1871. break;
  1872. case self::SIGN_MODE_CLEAR:
  1873. $operation = '--clearsign';
  1874. break;
  1875. case self::SIGN_MODE_NORMAL:
  1876. default:
  1877. $operation = '--sign';
  1878. break;
  1879. }
  1880. $arguments = array();
  1881. if ($armor) {
  1882. $arguments[] = '--armor';
  1883. }
  1884. if ($textmode) {
  1885. $arguments[] = '--textmode';
  1886. }
  1887. foreach ($this->signKeys as $key) {
  1888. $arguments[] = '--local-user ' .
  1889. escapeshellarg($key['fingerprint']);
  1890. }
  1891. // If using gpg-agent, set the sign pins used by the pinentry
  1892. $this->_setPinEntryEnv($this->signKeys);
  1893. $this->engine->reset();
  1894. $this->engine->addStatusHandler(array($this, 'handleSignStatus'));
  1895. $this->engine->setInput($input);
  1896. $this->engine->setOutput($output);
  1897. $this->engine->setOperation($operation, $arguments);
  1898. $this->engine->run();
  1899. if ($isFile) {
  1900. fclose($input);
  1901. }
  1902. if ($outputFile !== null) {
  1903. fclose($output);
  1904. }
  1905. $code = $this->engine->getErrorCode();
  1906. switch ($code) {
  1907. case self::ERROR_NONE:
  1908. break;
  1909. case self::ERROR_KEY_NOT_FOUND:
  1910. throw new Crypt_GPG_KeyNotFoundException(
  1911. 'Cannot sign data. Private key not found. Import the '.
  1912. 'private key before trying to sign data.',
  1913. $code,
  1914. $this->engine->getErrorKeyId()
  1915. );
  1916. case self::ERROR_BAD_PASSPHRASE:
  1917. throw new Crypt_GPG_BadPassphraseException(
  1918. 'Cannot sign data. Incorrect passphrase provided.',
  1919. $code
  1920. );
  1921. case self::ERROR_MISSING_PASSPHRASE:
  1922. throw new Crypt_GPG_BadPassphraseException(
  1923. 'Cannot sign data. No passphrase provided.',
  1924. $code
  1925. );
  1926. default:
  1927. throw new Crypt_GPG_Exception(
  1928. 'Unknown error signing data. Please use the \'debug\' option ' .
  1929. 'when creating the Crypt_GPG object, and file a bug report ' .
  1930. 'at ' . self::BUG_URI,
  1931. $code
  1932. );
  1933. }
  1934. if ($outputFile === null) {
  1935. return $output;
  1936. }
  1937. }
  1938. // }}}
  1939. // {{{ _encryptAndSign()
  1940. /**
  1941. * Encrypts and signs data
  1942. *
  1943. * @param string $data the data to be encrypted and signed.
  1944. * @param boolean $isFile whether or not the data is a filename.
  1945. * @param string $outputFile the name of the file in which the encrypted,
  1946. * signed data should be stored. If null, the
  1947. * encrypted, signed data is returned as a
  1948. * string.
  1949. * @param boolean $armor if true, ASCII armored data is returned;
  1950. * otherwise, binary data is returned.
  1951. *
  1952. * @return void|string if the <kbd>$outputFile</kbd> parameter is null, a
  1953. * string containing the encrypted, signed data is
  1954. * returned.
  1955. *
  1956. * @throws Crypt_GPG_KeyNotFoundException if no encryption key is specified
  1957. * or if no signing key is specified. See
  1958. * {@link Crypt_GPG::addEncryptKey()} and
  1959. * {@link Crypt_GPG::addSignKey()}.
  1960. *
  1961. * @throws Crypt_GPG_BadPassphraseException if a specified passphrase is
  1962. * incorrect or if a required passphrase is not specified.
  1963. *
  1964. * @throws Crypt_GPG_FileException if the output file is not writeable or
  1965. * if the input file is not readable.
  1966. *
  1967. * @throws Crypt_GPG_Exception if an unknown or unexpected error occurs.
  1968. * Use the <kbd>debug</kbd> option and file a bug report if these
  1969. * exceptions occur.
  1970. */
  1971. protected function _encryptAndSign($data, $isFile, $outputFile, $armor)
  1972. {
  1973. if (!$this->hasSignKeys()) {
  1974. throw new Crypt_GPG_KeyNotFoundException(
  1975. 'No signing keys specified.'
  1976. );
  1977. }
  1978. if (!$this->hasEncryptKeys()) {
  1979. throw new Crypt_GPG_KeyNotFoundException(
  1980. 'No encryption keys specified.'
  1981. );
  1982. }
  1983. if ($isFile) {
  1984. $input = @fopen($data, 'rb');
  1985. if ($input === false) {
  1986. throw new Crypt_GPG_FileException(
  1987. 'Could not open input file "' . $data .
  1988. '" for encrypting and signing.',
  1989. 0,
  1990. $data
  1991. );
  1992. }
  1993. } else {
  1994. $input = strval($data);
  1995. }
  1996. if ($outputFile === null) {
  1997. $output = '';
  1998. } else {
  1999. $output = @fopen($outputFile, 'wb');
  2000. if ($output === false) {
  2001. if ($isFile) {
  2002. fclose($input);
  2003. }
  2004. throw new Crypt_GPG_FileException(
  2005. 'Could not open output file "' . $outputFile .
  2006. '" for storing encrypted, signed data.',
  2007. 0,
  2008. $outputFile
  2009. );
  2010. }
  2011. }
  2012. $arguments = ($armor) ? array('--armor') : array();
  2013. foreach ($this->signKeys as $key) {
  2014. $arguments[] = '--local-user ' .
  2015. escapeshellarg($key['fingerprint']);
  2016. }
  2017. // If using gpg-agent, set the sign pins used by the pinentry
  2018. $this->_setPinEntryEnv($this->signKeys);
  2019. foreach ($this->encryptKeys as $key) {
  2020. $arguments[] = '--recipient ' . escapeshellarg($key['fingerprint']);
  2021. }
  2022. $this->engine->reset();
  2023. $this->engine->addStatusHandler(array($this, 'handleSignStatus'));
  2024. $this->engine->setInput($input);
  2025. $this->engine->setOutput($output);
  2026. $this->engine->setOperation('--encrypt --sign', $arguments);
  2027. $this->engine->run();
  2028. if ($isFile) {
  2029. fclose($input);
  2030. }
  2031. if ($outputFile !== null) {
  2032. fclose($output);
  2033. }
  2034. $code = $this->engine->getErrorCode();
  2035. switch ($code) {
  2036. case self::ERROR_NONE:
  2037. break;
  2038. case self::ERROR_KEY_NOT_FOUND:
  2039. throw new Crypt_GPG_KeyNotFoundException(
  2040. 'Cannot sign encrypted data. Private key not found. Import '.
  2041. 'the private key before trying to sign the encrypted data.',
  2042. $code,
  2043. $this->engine->getErrorKeyId()
  2044. );
  2045. case self::ERROR_BAD_PASSPHRASE:
  2046. throw new Crypt_GPG_BadPassphraseException(
  2047. 'Cannot sign encrypted data. Incorrect passphrase provided.',
  2048. $code
  2049. );
  2050. case self::ERROR_MISSING_PASSPHRASE:
  2051. throw new Crypt_GPG_BadPassphraseException(
  2052. 'Cannot sign encrypted data. No passphrase provided.',
  2053. $code
  2054. );
  2055. default:
  2056. throw new Crypt_GPG_Exception(
  2057. 'Unknown error encrypting and signing data. Please use the ' .
  2058. '\'debug\' option when creating the Crypt_GPG object, and ' .
  2059. 'file a bug report at ' . self::BUG_URI,
  2060. $code
  2061. );
  2062. }
  2063. if ($outputFile === null) {
  2064. return $output;
  2065. }
  2066. }
  2067. // }}}
  2068. // {{{ _verify()
  2069. /**
  2070. * Verifies data
  2071. *
  2072. * @param string $data the signed data to be verified.
  2073. * @param boolean $isFile whether or not the data is a filename.
  2074. * @param string $signature if verifying a file signed using a detached
  2075. * signature, this must be the detached signature
  2076. * data. Otherwise, specify ''.
  2077. *
  2078. * @return array an array of {@link Crypt_GPG_Signature} objects for the
  2079. * signed data.
  2080. *
  2081. * @throws Crypt_GPG_NoDataException if the provided data is not signed
  2082. * data.
  2083. *
  2084. * @throws Crypt_GPG_FileException if the input file is not readable.
  2085. *
  2086. * @throws Crypt_GPG_Exception if an unknown or unexpected error occurs.
  2087. * Use the <kbd>debug</kbd> option and file a bug report if these
  2088. * exceptions occur.
  2089. *
  2090. * @see Crypt_GPG_Signature
  2091. */
  2092. protected function _verify($data, $isFile, $signature)
  2093. {
  2094. if ($signature == '') {
  2095. $operation = '--verify';
  2096. $arguments = array();
  2097. } else {
  2098. // Signed data goes in FD_MESSAGE, detached signature data goes in
  2099. // FD_INPUT.
  2100. $operation = '--verify - "-&' . Crypt_GPG_Engine::FD_MESSAGE. '"';
  2101. $arguments = array('--enable-special-filenames');
  2102. }
  2103. $handler = new Crypt_GPG_VerifyStatusHandler();
  2104. if ($isFile) {
  2105. $input = @fopen($data, 'rb');
  2106. if ($input === false) {
  2107. throw new Crypt_GPG_FileException(
  2108. 'Could not open input file "' . $data . '" for verifying.',
  2109. 0,
  2110. $data
  2111. );
  2112. }
  2113. } else {
  2114. $input = strval($data);
  2115. if ($input == '') {
  2116. throw new Crypt_GPG_NoDataException(
  2117. 'No valid signature data found.',
  2118. self::ERROR_NO_DATA
  2119. );
  2120. }
  2121. }
  2122. $this->engine->reset();
  2123. $this->engine->addStatusHandler(array($handler, 'handle'));
  2124. if ($signature == '') {
  2125. // signed or clearsigned data
  2126. $this->engine->setInput($input);
  2127. } else {
  2128. // detached signature
  2129. $this->engine->setInput($signature);
  2130. $this->engine->setMessage($input);
  2131. }
  2132. $this->engine->setOperation($operation, $arguments);
  2133. $this->engine->run();
  2134. if ($isFile) {
  2135. fclose($input);
  2136. }
  2137. $code = $this->engine->getErrorCode();
  2138. switch ($code) {
  2139. case self::ERROR_NONE:
  2140. case self::ERROR_BAD_SIGNATURE:
  2141. break;
  2142. case self::ERROR_NO_DATA:
  2143. throw new Crypt_GPG_NoDataException(
  2144. 'No valid signature data found.',
  2145. $code
  2146. );
  2147. case self::ERROR_KEY_NOT_FOUND:
  2148. throw new Crypt_GPG_KeyNotFoundException(
  2149. 'Public key required for data verification not in keyring.',
  2150. $code,
  2151. $this->engine->getErrorKeyId()
  2152. );
  2153. default:
  2154. throw new Crypt_GPG_Exception(
  2155. 'Unknown error validating signature details. Please use the ' .
  2156. '\'debug\' option when creating the Crypt_GPG object, and ' .
  2157. 'file a bug report at ' . self::BUG_URI,
  2158. $code
  2159. );
  2160. }
  2161. return $handler->getSignatures();
  2162. }
  2163. // }}}
  2164. // {{{ _decryptAndVerify()
  2165. /**
  2166. * Decrypts and verifies encrypted, signed data
  2167. *
  2168. * @param string $data the encrypted signed data to be decrypted and
  2169. * verified.
  2170. * @param boolean $isFile whether or not the data is a filename.
  2171. * @param string $outputFile the name of the file to which the decrypted
  2172. * data should be written. If null, the decrypted
  2173. * data is returned in the results array.
  2174. *
  2175. * @return array two element array. The array has an element 'data'
  2176. * containing the decrypted data and an element
  2177. * 'signatures' containing an array of
  2178. * {@link Crypt_GPG_Signature} objects for the signed data.
  2179. * If the decrypted data is written to a file, the 'data'
  2180. * element is null.
  2181. *
  2182. * @throws Crypt_GPG_KeyNotFoundException if the private key needed to
  2183. * decrypt the data is not in the user's keyring or it the public
  2184. * key needed for verification is not in the user's keyring.
  2185. *
  2186. * @throws Crypt_GPG_NoDataException if specified data does not contain
  2187. * GPG signed, encrypted data.
  2188. *
  2189. * @throws Crypt_GPG_BadPassphraseException if a required passphrase is
  2190. * incorrect or if a required passphrase is not specified. See
  2191. * {@link Crypt_GPG::addDecryptKey()}.
  2192. *
  2193. * @throws Crypt_GPG_FileException if the output file is not writeable or
  2194. * if the input file is not readable.
  2195. *
  2196. * @throws Crypt_GPG_Exception if an unknown or unexpected error occurs.
  2197. * Use the <kbd>debug</kbd> option and file a bug report if these
  2198. * exceptions occur.
  2199. *
  2200. * @see Crypt_GPG_Signature
  2201. */
  2202. protected function _decryptAndVerify($data, $isFile, $outputFile)
  2203. {
  2204. if ($isFile) {
  2205. $input = @fopen($data, 'rb');
  2206. if ($input === false) {
  2207. throw new Crypt_GPG_FileException(
  2208. 'Could not open input file "' . $data .
  2209. '" for decrypting and verifying.',
  2210. 0,
  2211. $data
  2212. );
  2213. }
  2214. } else {
  2215. $input = strval($data);
  2216. if ($input == '') {
  2217. throw new Crypt_GPG_NoDataException(
  2218. 'No valid encrypted signed data found.',
  2219. self::ERROR_NO_DATA
  2220. );
  2221. }
  2222. }
  2223. if ($outputFile === null) {
  2224. $output = '';
  2225. } else {
  2226. $output = @fopen($outputFile, 'wb');
  2227. if ($output === false) {
  2228. if ($isFile) {
  2229. fclose($input);
  2230. }
  2231. throw new Crypt_GPG_FileException(
  2232. 'Could not open output file "' . $outputFile .
  2233. '" for storing decrypted data.',
  2234. 0,
  2235. $outputFile
  2236. );
  2237. }
  2238. }
  2239. $verifyHandler = new Crypt_GPG_VerifyStatusHandler();
  2240. $decryptHandler = new Crypt_GPG_DecryptStatusHandler(
  2241. $this->engine,
  2242. $this->decryptKeys
  2243. );
  2244. // If using gpg-agent, set the decrypt pins used by the pinentry
  2245. $this->_setPinEntryEnv($this->decryptKeys);
  2246. $this->engine->reset();
  2247. $this->engine->addStatusHandler(array($verifyHandler, 'handle'));
  2248. $this->engine->addStatusHandler(array($decryptHandler, 'handle'));
  2249. $this->engine->setInput($input);
  2250. $this->engine->setOutput($output);
  2251. $this->engine->setOperation('--decrypt');
  2252. $this->engine->run();
  2253. if ($isFile) {
  2254. fclose($input);
  2255. }
  2256. if ($outputFile !== null) {
  2257. fclose($output);
  2258. }
  2259. $return = array(
  2260. 'data' => null,
  2261. 'signatures' => $verifyHandler->getSignatures()
  2262. );
  2263. // if there was any problem decrypting the data, the handler will
  2264. // deal with it here.
  2265. try {
  2266. $decryptHandler->throwException();
  2267. } catch (Exception $e) {
  2268. if ($e instanceof Crypt_GPG_KeyNotFoundException) {
  2269. throw new Crypt_GPG_KeyNotFoundException(
  2270. 'Public key required for data verification not in ',
  2271. 'the keyring. Either no suitable private decryption key ' .
  2272. 'is in the keyring or the public key required for data ' .
  2273. 'verification is not in the keyring. Import a suitable ' .
  2274. 'key before trying to decrypt and verify this data.',
  2275. self::ERROR_KEY_NOT_FOUND,
  2276. $this->engine->getErrorKeyId()
  2277. );
  2278. }
  2279. if ($e instanceof Crypt_GPG_NoDataException) {
  2280. throw new Crypt_GPG_NoDataException(
  2281. 'Cannot decrypt and verify data. No PGP encrypted data ' .
  2282. 'was found in the provided data.',
  2283. self::ERROR_NO_DATA
  2284. );
  2285. }
  2286. throw $e;
  2287. }
  2288. if ($outputFile === null) {
  2289. $return['data'] = $output;
  2290. }
  2291. return $return;
  2292. }
  2293. // }}}
  2294. }
  2295. // }}}
  2296. ?>