forked from dbeurive/gpg
/
Gpg.php
1545 lines (1350 loc) · 71.6 KB
/
Gpg.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
// Copyright (c) 2016 Denis BEURIVE
//
// This work is licensed under the Creative Common Attribution-NonCommercial 4.0 International (CC BY-NC 4.0).
/**
* This file implements a wrapper around the GPG's command line interface.
*
* Please note that the ambition of this wrapper is not to be "complete".
*
* This wrapper has been developed in order to automat the GPG processing of a large number of files.
*
* Therefore, the only the basic GPG functionalities have been wrapped (signing, encryption, decryption and signature verification).
*/
namespace dbeurive\Gpg;
/**
* Class Gpg
*
* This class is a wrapper around the GPG's command line interface.
* It implements the following functionalities.
* - Import a key, from a file, into the keyring.
* - Remove a key from the keyring.
* - Get the fingerprint of a given key, identified by its ID.
* - Test if a key, identified by it's fingerprint, is in the keyring.
* - Sign a document (file or string), using a private key.
* - Clear sign a document (file or string), using a private key.
* - Detach sign a document (file or string), using a private key.
* - Encrypt a document (file or string), using a private key.
* - Decrypt a signed document (file or string), using a public key.
* - Decrypt an encrypted document (file or string), using a private key (this may require a password).
* - Verify a signature.
*
* Conventions
* ===========
*
* Except when calling the methods that returns the fingerprints, the keys are identified by their fingerprints
* This ensures maximum security against "side effects" that may occur when specifying keys' IDs.
*
* Get the keys fingerprints:
*
* gpg --batch --list-keys --fingerprint --with-colon
**
* Please note that the following command can also be used:
*
* gpg --batch --list-keys --fingerprint
*
* However, while specifying fingerprints, no spaces should be used.
* Therefore, the former command (with the option --with-colon) is recommended.
*
* Get the keys' IDs is:
*
* gpg --list-keys --keyid-format=long
* gpg --list-keys --with-fingerprint --keyid-format=long
*
* Find out which key has been used to sign (or encrypt) a file:
*
* gpg --list-packets file_to_sign.sig
*
* All encrypted data is "armored". See GPG documentation for details.
*
* Notes
* =====
*
* To import the keys used within the examples:
*
* cd tests/data
* gpg --import open.prv; gpg --import open.pub; gpg --import protected.prv; gpg --import protected.pub
*
* To understand the content of the file generated while using the option --status-fd:
*
* http://git.gnupg.org/cgi-bin/gitweb.cgi?p=gnupg.git;a=blob_plain;f=doc/DETAILS
*
* Look for the string "Format of the --status-fd output"
*
* To encrypt using a private key is called "signing" in GPG lingo.
* That is, the use of the option "--sign" will actually encrypt a document using a private key.
* However, "signing" does not always mean that you will encrypt a document.
* Indeed, you can produce a detached signature of the document (which is not the encrypted content of the document).
* Or you can append a signature to a document (the appended signature is not the encrypted content of the document).
*
* Compatibility
* =============
*
* This wrapper has been tested against GPG version 1.4.20.
* It should work with other versions.
* However, this is not guaranteed, since it relies in the output of the "gpg" command.
* To test the wrapper against a specific version of GPG, you should run the unit tests.
*
* To do
* =====
*
* I did not test the verification of a signature in the following conditions:
*
* - The signature with the keyid is good, but the signature is expired (EXPSIG).
* - The signature with the keyid is good, but the signature was made by an expired key (EXPKEYSIG).
* - The signature with the keyid is good, but the signature was made by a revoked key (REVKEYSIG).
*
* The methods that verify signatures are designed to process these situations.
* However, the unit tests does note cover these situations.
*
* @package dbeurive\Gpg
*/
class Gpg
{
/** Path to GPG. */
const EXE_GPG = '/usr/bin/gpg';
/** This constant is used to signal an error. */
const STATUS_ERROR = 0;
/** This constant is used to signal the successful completion of a command. */
const STATUS_SUCCESS = 1;
/** This constant is used to signal that a key is present within a keyring. */
const STATUS_KEY_PRESENT = 2;
/** This constant is used to signal that a key is absent from a keyring. */
const STATUS_KEY_ABSENT = 3;
/** This constant is used to signal that a signature is valid. */
const STATUS_SIG_VALID = 4;
/** This constant is used to signal that a signature is "mathematically valid", but a warning must be reported. */
const STATUS_SIG_VALID_BUT_WARNING = 5;
/** This constant is used to signal that a signature is not valid. */
const STATUS_SIG_INVALID = 6;
/** This constant is used to signal that we cannot verify the signature (because of a technical problem). */
const STATUS_SIG_ERROR = 7;
/** @see Gpg::__getKeyFingerPrintData() */
const KEY_STATUS = 'status';
/** @see Gpg::__getKeyFingerPrintData() */
const KEY_DATA = 'data';
/** The command being executed. */
const KEY_COMMAND = 'command';
/** The value returned the the command (that is: $?). */
const KEY_COMMAND_RETURN_CODE = 'status code';
/** The text loaded from the file identified be the option "--status-fd." */
const KEY_COMMAND_STATUS_FILE = 'status file';
/** The text loaded from the file identified be the option "--output." */
const KEY_COMMAND_OUTPUT = 'output';
/** An array that contains the standard output of the command. */
const KEY_COMMAND_STDOUT = 'stdout';
/**
* Return the version of GPG.
* @return string The version of GPG.
* @note Command:
* gpg --version; echo $?
* @note The option '--status-fd' is not available for this command.
* => To decide whether the command was successful or not, we look at the status returned by the command.
* On success, its value should be 0.
* @note The option '--output' is not available for this command.
* @throws \Exception
*/
static public function version() {
$cmd = array(
'--version'
);
$result = self::__exec($cmd);
$output = $result[self::KEY_COMMAND_STDOUT];
if ($result[self::KEY_COMMAND_RETURN_CODE] != 0) {
throw new \Exception("Error while executing the following command: " . $result[self::KEY_COMMAND]);
}
if (! isset($output[0])) {
throw new \Exception("Error while executing the following command: " . $result[self::KEY_COMMAND]);
}
$line = $output[0];
$matches = array();
if (1 === preg_match('/^gpg \(GnuPG\) (.+)$/', $line, $matches)) {
return $matches[1];
}
throw new \Exception("Error while executing the following command: " . $result[self::KEY_COMMAND]);
}
/**
* Check the current version of GPG.
* @return bool If the current version has been tested, and is known to work with the wrapper, then the method returns the value true.
* Otherwise, it returns the value false.
* @note Please note that if the returned value is false, then it does not mean that the wrapper does not work with the current version of GPG.
* It just means that the wrapper has not been tested against the version.
* The procedure used to test the wrapper is pretty simple: just execute the unit tests.
*/
static public function checkVersion() {
$version = self::version();
return 0 === version_compare('1.4.20', $version);
}
/**
* Get the fingerprint of a public key, identified by its ID.
* @param string $inPublicKey The public key ID.
* @return null|false|string The method may return one of the following values:
* null: the key was not found.
* false: an error occurred.
* string: the key's fingerprint.
* @note Command:
* exec 3> /tmp/status; gpg --batch --yes --status-fd 3 --output /tmp/result --list-keys --fingerprint --with-colon "open key"; echo $?; exec 3>&-
* @note The option '--status-fd' is not available for this command.
* A specific method is assigned to explore the output of this command.
* It parses the standard output of the command, so it may not be 100% reliable.
* @note The option '--output' is not available for this command.
* @see Gpg::__getKeyFingerPrintData
*/
static public function getPublicKeyFingerPrint($inPublicKey) {
$cmd = array(
'--list-keys',
'--fingerprint',
'--with-colon',
escapeshellarg($inPublicKey)
);
$result = self::__exec($cmd);
$output = $result[self::KEY_COMMAND_STDOUT];
$data = self::__getKeyFingerPrintData($output);
if (self::STATUS_ERROR == $data[self::KEY_STATUS]) {
return false;
}
if (self::STATUS_KEY_ABSENT == $data[self::KEY_STATUS]) {
return null;
}
return $data[self::KEY_DATA];
}
/**
* Get the fingerprint of a private key, identified by its ID.
* @param string $inPrivateKey The private key ID.
* @return null|false|string The method may return one of the following values:
* null: the key was not found.
* false: an error occurred.
* string: the key's fingerprint.
* @note Command:
* exec 3> /tmp/status; gpg --batch --yes --status-fd 3 --output /tmp/result --list-secret-keys --fingerprint --with-colon "open key"; echo $?; exec 3>&-
* @note The option '--status-fd' is not available for this command.
* A specific method is assigned to explore the output of this command.
* It parses the standard output of the command, so it may not be 100% reliable.
* @note The option '--output' is not available for this command.
* @see Gpg::__getKeyFingerPrintData
*/
static public function getPrivateKeyFingerPrint($inPrivateKey) {
$cmd = array(
'--list-secret-keys',
'--fingerprint',
'--with-colon',
escapeshellarg($inPrivateKey)
);
$result = self::__exec($cmd);
$output = $result[self::KEY_COMMAND_STDOUT];
$data = self::__getKeyFingerPrintData($output);
if (self::STATUS_ERROR == $data[self::KEY_STATUS]) {
return false;
}
if (self::STATUS_KEY_ABSENT == $data[self::KEY_STATUS]) {
return null;
}
return $data[self::KEY_DATA];
}
/**
* Test if a private key, identified by its fingerprint, is present within the key ring.
* @param string $inPrivateKeyFingerPrint Fingerprint of the private key.
* @return bool If the key is present, then the method returns the value true.
* Otherwise, it returns the value false.
* @note Command:
* exec 3> /tmp/status; gpg --batch --yes --status-fd 3 --output /tmp/result --list-secret-keys "open key"; echo $?; exec 3>&-
* exec 3> /tmp/status; gpg --batch --yes --status-fd 3 --output /tmp/result --list-secret-keys --fingerprint --with-colon "open key"; echo $?; exec 3>&-
* @note The option '--status-fd' is not available for this command.
* If the value of the returned code is 0, then it means that the private key is in the keyring.
* If the value of the returned code is 2, then we must parse the output of the command in order to find out if the error means whether the key is absent or not.
* A specific method is assigned to explore the output of this command.
* It parses the standard output of the command, so it may not be 100% reliable.
* @note The option '--output' is not available for this command.
* @throws \Exception
* @see Gpg::__getListKeysStatus
*/
static public function isPrivateKeyPresent($inPrivateKeyFingerPrint) {
$cmd = array(
'--list-secret-keys',
escapeshellarg($inPrivateKeyFingerPrint)
);
$result = self::__exec($cmd);
$output = $result[self::KEY_COMMAND_STDOUT];
$status = $result[self::KEY_COMMAND_RETURN_CODE];
if (0 === $status) {
// This means that the key is in the keyring.
return true;
}
if (2 === $status) {
// The key should not be in the keyring... but let's make sure of this.
if (self::STATUS_KEY_ABSENT == self::__getListKeysStatus($output)) {
return false;
}
}
throw new \Exception("Error while executing the following command: " . $result[self::KEY_COMMAND]);
}
/**
* Test if a public key, identified by its fingerprint, is present within the key ring.
* @param string $inPublicKeyFingerPrint Fingerprint of the private key.
* @return bool If the key is present, then the method returns the value true.
* Otherwise, it returns the value false.
* @note Command:
* gpg --list-keys "open key"; echo $?
* gpg --list-keys --fingerprint --with-colon "open key"; echo $?
* @note The option '--status-fd' is not available for this command.
* If the value of the returned code is 0, then it means that the private key is in the keyring.
* If the value of the returned code is 2, then we must parse the output of the command in order to find out if the error means whether the key is absent or not.
* A specific method is assigned to explore the output of this command.
* It parses the standard output of the command, so it may not be 100% reliable.
* @note The option '--output' is not available for this command.
* @throws \Exception
* @see Gpg::__getListKeysStatus
*/
static public function isPublicKeyPresent($inPublicKeyFingerPrint) {
$cmd = array(
'--list-keys',
escapeshellarg($inPublicKeyFingerPrint)
);
$result = self::__exec($cmd);
$output = $result[self::KEY_COMMAND_STDOUT];
$status = $result[self::KEY_COMMAND_RETURN_CODE];
if (0 === $status) {
// This means that the key is in the keyring.
return true;
}
if (2 === $status) {
// The key should not be in the keyring... but let's make sure of this.
if (self::STATUS_KEY_ABSENT == self::__getListKeysStatus($output)) {
return false;
}
}
throw new \Exception("Error while executing the following command: " . $result[self::KEY_COMMAND]);
}
/**
* Remove a private key, identified by its fingerprint, from the keyring.
* @param string $inPrivateKeyFingerPrint Fingerprint of the private key to remove.
* @return bool Upon successful completion the method returns the value true.
* Otherwise, it returns the value false. This means that the key was not in the keyring. Hence, it could not be removed.
* @note Command:
* exec 3> /tmp/status; gpg --batch --yes --status-fd 3 --delete-secret-keys "881C41F8B8FD138E86E7230929A778386005B911"; echo $?; exec 3>&-
* SUCCESS: /tmp/status is empty.
* And the status returned by the command is 0.
* ERROR: /tmp/status contains:
* [GNUPG:] DELETE_PROBLEM 1
* And the status returned by the command is not 0.
*
* From "doc/DETAILS":
* *** DELETE_PROBLEM <reason_code>
* Deleting a key failed. Reason codes are:
* - 1 :: No such key
* - 2 :: Must delete secret key first
* - 3 :: Ambigious specification
* - 4 :: Key is stored on a smartcard.
*
* => To decide whether the command was successful or not, we look at the status returned by the command.
* On success, its value should be 0.
* => If the status returned by the command is not 0, then we look at the file "/tmp/status".
* @note The option '--output' is not available for this command.
* @throws \Exception
* @see Gpg::__getRemoveKeyStatus
*/
static public function removePrivateKey($inPrivateKeyFingerPrint) {
$cmd = array(
'--delete-secret-keys',
escapeshellarg($inPrivateKeyFingerPrint)
);
$result = self::__exec($cmd);
$status = $result[self::KEY_COMMAND_RETURN_CODE];
$error = 'Unexpected error';
if (0 === $status) {
// This means that the key was removed from the keyring.
return true;
}
if (2 === $status) {
$statusText = explode(PHP_EOL, $result[self::KEY_COMMAND_STATUS_FILE]);
// This should mean that the key was not in the keyring.
if (self::STATUS_SUCCESS == self::__getRemoveKeyStatus($statusText, $error)) {
return false;
}
}
throw new \Exception("Error while executing the following command: " . $result[self::KEY_COMMAND] . ' ' . $error);
}
/**
* Remove a public key, identified by its fingerprint, from the key ring.
* @param string $inPublicKeyFingerPrint Fingerprint of the public key to remove.
* @return bool Upon successful completion the method returns the value true.
* Otherwise, it returns the value false. This means that the key was not in the keyring. Hence, it could not be removed.
* @note Command:
* exec 3> /tmp/status; gpg --batch --yes --status-fd 3 --delete-keys "881C41F8B8FD138E86E7230929A778386005B911"; echo $?; exec 3>&-
* SUCCESS: /tmp/status is empty.
* And the status returned by the command is 0.
* ERROR: /tmp/status contains:
* [GNUPG:] DELETE_PROBLEM 1
* And the status returned by the command is not 0.
*
* From "doc/DETAILS":
* *** DELETE_PROBLEM <reason_code>
* Deleting a key failed. Reason codes are:
* - 1 :: No such key
* - 2 :: Must delete secret key first
* - 3 :: Ambigious specification
* - 4 :: Key is stored on a smartcard.
*
* => To decide whether the command was successful or not, we look at the status returned by the command.
* On success, its value should be 0.
* => If the status returned by the command is not 0, then we look at the file "/tmp/status".
* @note The option '--output' is not available for this command.
* @throws \Exception
* @see Gpg::__getRemoveKeyStatus
*/
static public function removePublicKey($inPublicKeyFingerPrint) {
$cmd = array(
'--delete-keys',
escapeshellarg($inPublicKeyFingerPrint)
);
$result = self::__exec($cmd);
$status = $result[self::KEY_COMMAND_RETURN_CODE];
if (0 === $status) {
// This means that the key was removed from the keyring.
return true;
}
if (2 === $status) {
$statusText = explode(PHP_EOL, $result[self::KEY_COMMAND_STATUS_FILE]);
// This should mean that the key was not in the keyring.
if (self::STATUS_SUCCESS == self::__getRemoveKeyStatus($statusText, $error)) {
return false;
}
}
throw new \Exception("Error while executing the following command: " . $result[self::KEY_COMMAND] . ' ');
}
/**
* Import a private key from a file.
* @param string $inPrivateKeyPath Path to the file that contains the private key to load.
* @return bool Upon successful completion the method returns the value true.
* Otherwise, it returns the value false. This means that the key was already in the keyring. Hence, the key was not imported.
* @see Gpg::__getImportPrivateKeyStatus
* @note Command:
* exec 3> /tmp/status; gpg --batch --yes --status-fd 3 --import open.prv; echo $?; exec 3>&-
* SUCCESS: /tmp/status contains:
* [GNUPG:] IMPORT_OK 16 03DEC874738344206A1A7D31E07D9D14954C8DC5
* [GNUPG:] IMPORT_RES 1 0 0 0 0 0 0 0 0 1 0 1 0 0
* However, the status code may be 0 or 2.
* ERROR: /tmp/status contains:
* [GNUPG:] IMPORT_RES 0 0 0 0 0 0 0 0 0 0 0 0 0 0
* And the status returned by the command is not 0.
*
* From "doc/DETAILS":
* *** IMPORT_OK <reason> [<fingerprint>]
* The key with the primary key's FINGERPRINT has been imported.
* REASON flags are:
* - 0 :: Not actually changed
* - 1 :: Entirely new key.
* - 2 :: New user IDs
* - 4 :: New signatures
* - 8 :: New subkeys
* - 16 :: Contains private key.
*
* => To decide whether the command was successful or not, we look at "IMPORT_OK" in the status file (regardless of the value of the status returned by the command).
* * if this pattern is found, then the operation was successful.
* * otherwise, an error occurred.
*
* @throws \Exception
*/
static public function importPrivateKey($inPrivateKeyPath) {
if (! file_exists($inPrivateKeyPath)) {
throw new \Exception("File \"$inPrivateKeyPath\" does not exist.");
}
$cmd = array(
'--import',
escapeshellarg($inPrivateKeyPath)
);
$result = self::__exec($cmd);
$status = $result[self::KEY_COMMAND_RETURN_CODE];
$statusText = explode(PHP_EOL, $result[self::KEY_COMMAND_STATUS_FILE]);
if ((0 == $status) || (2 == $status)) {
return self::__getImportPrivateKeyStatus($statusText);
}
throw new \Exception("Error while executing the following command: " . $result[self::KEY_COMMAND] . ' Status code was ' . $status);
}
/**
* Import a public key from a file.
* @param string $inPublicKeyPath Path to the file that contains the public key to load.
* @return true Upon successful completion the method returns the value true.
* @note Please note that, unlike when importing a private key, the return value could not be used to distinguish whether the key was already in the keyring or not, prior to its importation.
* Whether the key was already in the keyring or not, the method returns the value true.
* @note Command:
* exec 3> /tmp/status; gpg --batch --yes --status-fd 3 --import open.pub; echo $?; exec 3>&-
* SUCCESS: /tmp/status contains:
* [GNUPG:] IMPORT_OK 0 03DEC874738344206A1A7D31E07D9D14954C8DC5
* [GNUPG:] IMPORT_RES 1 0 0 0 1 0 0 0 0 0 0 0 0 0
* However, the status code may be 0 or 2.
* ERROR: /tmp/status contains:
* [GNUPG:] IMPORT_RES 0 0 0 0 0 0 0 0 0 0 0 0 0 0
* And the status returned by the command is not 0.
*
* From "doc/DETAILS":
* *** IMPORT_OK <reason> [<fingerprint>]
* The key with the primary key's FINGERPRINT has been imported.
* REASON flags are:
* - 0 :: Not actually changed
* - 1 :: Entirely new key.
* - 2 :: New user IDs
* - 4 :: New signatures
* - 8 :: New subkeys
* - 16 :: Contains private key.
*
* => To decide whether the command was successful or not, we look at "IMPORT_OK" in the status file (regardless of the value of the status returned by the command).
* * if this pattern is found, then the operation was successful.
* * otherwise, an error occurred.
*
* @throws \Exception
*/
static public function importPublicKey($inPublicKeyPath) {
if (! file_exists($inPublicKeyPath)) {
throw new \Exception("File \"$inPublicKeyPath\" does not exist.");
}
$cmd = array(
'--import',
escapeshellarg($inPublicKeyPath)
);
$result = self::__exec($cmd);
$status = $result[self::KEY_COMMAND_RETURN_CODE];
$statusText = explode(PHP_EOL, $result[self::KEY_COMMAND_STATUS_FILE]);
if ((0 == $status) || (2 == $status)) {
return self::__getImportPrivateKeyStatus($statusText);
}
throw new \Exception("Error while executing the following command: " . $result[self::KEY_COMMAND] . ' Status code was ' . $status);
}
/**
* Sign a given file, using a given private key.
* @param string $inAbsolutePath Absolute path to the file to sign.
* @param string $inPrivateKeyFingerPrint Fingerprint of the private key to use.
* @param string $inOptPassword Password associated to the private key.
* If no password is required, then you should set the value of this parameter to null.
* @param null|string $inOptSignaturePath Absolute path to the generated signature.
* If this parameter is not specified, then the method will return the signature as a string.
* @return true|string Upon successful completion:
* If a destination file has been specified, then the method returns the value true.
* Otherwise, the method returns a string that represents the signature.
* @throws \Exception
* @see Gpg::__getSignFileStatus
* @note Commands:
* gpg --list-secret-keys --fingerprint --with-colon
* exec 3> /tmp/status; gpg --batch --yes --status-fd 3 --armor -u 03DEC874738344206A1A7D31E07D9D14954C8DC5 --output file_to_sign.sig --sign file_to_sign.txt; echo $?; exec 3>&-
* exec 3> /tmp/status; gpg --batch --yes --status-fd 3 --armor -u 03DEC874738344206A1A7D31E07D9D14954C8DC5 --output - --sign file_to_sign.txt; echo $?; exec 3>&-
* exec 3> /tmp/status; echo 'password' | gpg --batch --yes --status-fd 3 --armor -u 881C41F8B8FD138E86E7230929A778386005B911 --passphrase-fd 0 --output file_to_sign.sig --sign file_to_sign.txt; echo $?; exec 3>&-
* exec 3> /tmp/status; echo 'password' | gpg --batch --yes --status-fd 3 --armor -u 881C41F8B8FD138E86E7230929A778386005B911 --passphrase-fd 0 --output - --sign file_to_sign.txt; echo $?; exec 3>&-
* SUCCESS: /tmp/status contains:
* [GNUPG:] GOOD_PASSPHRASE
* [GNUPG:] BEGIN_SIGNING
* [GNUPG:] SIG_CREATED S 1 2 00 1482578614 03DEC874738344206A1A7D31E07D9D14954C8DC5
* And the status returned by the command is 0.
* ERROR: /tmp/status may be empty or not.
* However, the pattern "SIG_CREATED" is absent.
* And the status returned by the command is not 0.
*
* *** SIG_CREATED <type> <pk_algo> <hash_algo> <class> <timestamp> <keyfpr>
* A signature has been created using these parameters.
* Values for type <type> are:
* - D :: detached
* - C :: cleartext
* - S :: standard
* (only the first character should be checked)
*
* => To decide whether the command was successful or not, we look at "SIG_CREATED" in the status file (regardless of the value of the status returned by the command).
* * if this pattern is found, then the operation was successful.
* * otherwise, an error occurred.
*/
static public function signFile($inAbsolutePath, $inPrivateKeyFingerPrint, $inOptPassword=null, $inOptSignaturePath=null) {
$inAbsolutePath = realpath($inAbsolutePath);
$inOptSignaturePath = is_null($inOptSignaturePath) ? null : $inOptSignaturePath;
if (! file_exists($inAbsolutePath)) {
throw new \Exception("File \"$inAbsolutePath\" does not exist.");
}
$cmd = array(
'--armor',
'-u',
escapeshellarg($inPrivateKeyFingerPrint),
'--sign',
escapeshellarg($inAbsolutePath)
);
$result = self::__exec($cmd, $inOptSignaturePath, $inOptPassword);
$statusText = explode(PHP_EOL, $result[self::KEY_COMMAND_STATUS_FILE]);
if (! self::__getSignFileStatus($statusText)) {
$status = $result[self::KEY_COMMAND_RETURN_CODE];
throw new \Exception("Error while executing the following command: " . $result[self::KEY_COMMAND] . ' Status code was ' . $status);
}
if (! is_null($inOptSignaturePath)) {
// This file exists (see method self::__exec).
return true;
}
return $result[self::KEY_COMMAND_OUTPUT];
}
/**
* Sign a given string, using a given private key.
* @param string $inString String to sign.
* @param string $inPrivateKeyFingerPrint Fingerprint of the private key to use.
* @param string $inPassword Password associated to the private key.
* If no password is required, then you should set the value of this parameter to null.
* @param null|string $inOptSignaturePath Absolute path to the generated signature.
* If this parameter is not specified, then the method will return the signature as a string.
* @return true|string Upon successful completion:
* If a destination file has been specified, then the method returns the value true.
* Otherwise, the method returns a string that represents the signature.
* @throws \Exception
* @note This method uses a temporary file.
*/
static function signString($inString, $inPrivateKeyFingerPrint, $inPassword=null, $inOptSignaturePath=null) {
$input = tempnam(sys_get_temp_dir(), 'Gpg::signString::');
if (false === file_put_contents($input, $inString)) {
throw new \Exception("Can not write data into temporary file \"$input\"");
}
$result = self::signFile($input, $inPrivateKeyFingerPrint, $inPassword, $inOptSignaturePath);
if (false === unlink($input)) {
throw new \Exception("Can not remove file \"$input\".");
}
return $result;
}
/**
* Clear sign a given file, using a given private key.
* @param string $inAbsolutePath Absolute path to the file to sign.
* @param string $inPrivateKeyFingerPrint Fingerprint of the private key to use.
* @param string $inOptPassword Password associated to the private key.
* If no password is required, then you should set the value of this parameter to null.
* @param null|string $inOptSignaturePath Absolute path to the generated signature.
* If this parameter is not specified, then the method will return the signature as a string.
* @return true|string Upon successful completion:
* If a destination file has been specified, then the method returns the value true.
* Otherwise, the method returns a string that represents the signature.
* @throws \Exception
* @note Commands:
* gpg --list-secret-keys --fingerprint --with-colon
* exec 3> /tmp/status; gpg --batch --yes --status-fd 3 --armor -u 03DEC874738344206A1A7D31E07D9D14954C8DC5 --output file_to_sign.sig --clearsign file_to_sign.txt; echo $?; exec 3>&-
* exec 3> /tmp/status; gpg --batch --yes --status-fd 3 --armor -u 03DEC874738344206A1A7D31E07D9D14954C8DC5 --output - --clearsign file_to_sign.txt; echo $?; exec 3>&-
* exec 3> /tmp/status; echo 'password' | gpg --batch --yes --status-fd 3 --armor -u 881C41F8B8FD138E86E7230929A778386005B911 --passphrase-fd 0 --output file_to_sign.sig --clearsign file_to_sign.txt; echo $?; exec 3>&-
* exec 3> /tmp/status; echo 'password' | gpg --batch --yes --status-fd 3 --armor -u 881C41F8B8FD138E86E7230929A778386005B911 --passphrase-fd 0 --output - --clearsign file_to_sign.txt; echo $?; exec 3>&-
* @see Gpg::__getSignFileStatus
* @see Gpg::signFile
*/
static public function clearSignFile($inAbsolutePath, $inPrivateKeyFingerPrint, $inOptPassword=null, $inOptSignaturePath=null)
{
$inAbsolutePath = realpath($inAbsolutePath);
$inOptSignaturePath = is_null($inOptSignaturePath) ? null : $inOptSignaturePath;
if (! file_exists($inAbsolutePath)) {
throw new \Exception("File \"$inAbsolutePath\" does not exist.");
}
$cmd = array(
'--armor',
'-u',
escapeshellarg($inPrivateKeyFingerPrint),
'--clearsign',
escapeshellarg($inAbsolutePath)
);
$result = self::__exec($cmd, $inOptSignaturePath, $inOptPassword);
$statusText = explode(PHP_EOL, $result[self::KEY_COMMAND_STATUS_FILE]);
if (! self::__getSignFileStatus($statusText)) {
$status = $result[self::KEY_COMMAND_RETURN_CODE];
throw new \Exception("Error while executing the following command: " . $result[self::KEY_COMMAND] . ' Status code was ' . $status);
}
if (! is_null($inOptSignaturePath)) {
// This file exists (see method self::__exec).
return true;
}
return $result[self::KEY_COMMAND_OUTPUT];
}
/**
* Clear sign a given string, using a given private key.
* @param string $inString String to sign.
* @param string $inPrivateKeyFingerPrint Fingerprint of the private key to use.
* @param string $inPassword Password associated to the private key.
* If no password is required, then you should set the value of this parameter to null.
* @param null|string $inOptSignaturePath Absolute path to the generated signature.
* If this parameter is not specified, then the method will return the signature as a string.
* @return true|string Upon successful completion:
* If a destination file has been specified, then the method returns the value true.
* Otherwise, the method returns a string that represents the signature.
* @throws \Exception
* @note This method uses a temporary file.
*/
static function clearSignString($inString, $inPrivateKeyFingerPrint, $inPassword=null, $inOptSignaturePath=null) {
$input = tempnam(sys_get_temp_dir(), 'Gpg::signString::');
if (false === file_put_contents($input, $inString)) {
throw new \Exception("Can not write data into temporary file \"$input\"");
}
$result = self::clearSignFile($input, $inPrivateKeyFingerPrint, $inPassword, $inOptSignaturePath);
if (false === unlink($input)) {
throw new \Exception("Can not remove file \"$input\".");
}
return $result;
}
/**
* Verify a signature embedded within the output of a clear signing process.
* @param string $inFilePath Path to the file that contains the signature (and the signed document).
* @param string $outWarning Reference to a string used to store a warning message.
* Warning messages may be reported for valid signatures (that is, when the returned value is true).
* @return bool If the signature is valid, then the method returns the value true.
* Otherwise, it returns the value false.
* Please note that if the returned value is true, indicating that the signature is valid, then you should look for warning messages.
* Indeed, although a signature may be "mathematically" valid, it may have been created with a revoked key (for example).
* In such a case, a warning message is reported, indicating than the key used to produce the signature has been revoked.
* @note Command:
* gpg --armor -u 03DEC874738344206A1A7D31E07D9D14954C8DC5 --output signature --clearsign file_to_sign
* exec 3> /tmp/status; gpg --batch --yes --status-fd 3 --verify signature; echo $?; exec 3>&-
* @note In order to verify the status of the execution:
*
* If the returned status code is not 0 or 1, then it means that an error occurred.
*
* If the returned status code is 0, then we look at the content of the file which file descriptor is specified by the option "--status-fd".
*
* Valid signatures:
* If we find one of the following tags, we consider that the signature is valid (the return value is true):
* VALIDSIG, GOODSIG, EXPSIG, EXPKEYSIG, or REVKEYSIG.
* Please note that the presence of the following tag will trigger a warning message:
* EXPSIG, EXPKEYSIG, or REVKEYSIG.
*
* Invalid signatures:
* If we find the tag BADSIG, then we consider that the signature is not valid (the return value is false).
*
* Errors:
* If we find the tag ERRSIG, then we raise an exception. It means that we can not verify the signature.
*
* @see http://git.gnupg.org/cgi-bin/gitweb.cgi?p=gnupg.git;a=blob_plain;f=doc/DETAILS
* @throws \Exception
*/
static public function verifyClearSignedFile($inFilePath, &$outWarning) {
$outWarning = null;
if (! file_exists($inFilePath)) {
throw new \Exception("File \"$inFilePath\" does not exist!");
}
$cmd = array(
'--verify',
escapeshellarg($inFilePath)
);
$result = self::__exec($cmd);
$statusCode = $result[self::KEY_COMMAND_RETURN_CODE];
if ((0 !== $statusCode) && (1 !== $statusCode)) {
throw new \Exception("Could not verify the signature from file \"$inFilePath\": return code is $statusCode.");
}
$statusText = explode(PHP_EOL, $result[self::KEY_COMMAND_STATUS_FILE]);
$status = self::__getVerifySignatureStatus($statusText, $outWarning);
switch ($status) {
case self::STATUS_SIG_VALID: return true;
case self::STATUS_SIG_VALID_BUT_WARNING: return true;
case self::STATUS_SIG_INVALID; return false;
}
throw new \Exception("Could not verify the signature from file \"$inFilePath\": $outWarning");
}
/**
* Verify a signature, stored within a given string, obtained by clear signing a document.
* @param string $inString String that contains the signature.
* @param string $outWarning Reference to a string used to report an error message.
* Warning messages may be reported for valid signatures (that is, when the returned value is true).
* @return bool If the signature is valid, then the method returns the value true.
* Otherwise, it returns the value false.
* Please note that if the returned value is true, indicating that the signature is valid, then you should look for warning messages.
* Indeed, although a signature may be "mathematically" valid, it may have been created with a revoked key (for example).
* In such a case, a warning message is reported, indicating than the key used to produce the signature has been revoked. * @throws \Exception
* @throws \Exception
* @see Gpg::verifyClearSignedFile()
*/
static public function verifyClearSignedString($inString, &$outWarning) {
$outWarning = null;
$input = tempnam(sys_get_temp_dir(), 'Gpg::signString::');
if (false === file_put_contents($input, $inString)) {
throw new \Exception("Can not write data into temporary file \"$input\"");
}
$result = self::verifyClearSignedFile($input, $outWarning);
if (false === unlink($input)) {
throw new \Exception("Can not remove file \"$input\".");
}
return $result;
}
/**
* Verify a detached signature against a given document.
* @param string $inSignatureFilePath Path to the file that contains the (detached) signature.
* @param string $inDocument Path to the document.
* @param string $outWarning Reference to a string used to store a warning message.
* Warning messages may be reported for valid signatures (that is, when the returned value is true).
* @return bool If the signature is valid, then the method returns the value true.
* Otherwise, it returns the value false.
* Please note that if the returned value is true, indicating that the signature is valid, then you should look for warning messages.
* Indeed, although a signature may be "mathematically" valid, it may have been created with a revoked key (for example).
* In such a case, a warning message is reported, indicating than the key used to produce the signature has been revoked.
* @note Command:
* gpg --armor -u 03DEC874738344206A1A7D31E07D9D14954C8DC5 --output signature --detach-sign file_to_sign
* exec 3> /tmp/status; gpg --batch --yes --status-fd 3 --verify signature file_to_sign; echo $?; exec 3>&-
* @note In order to verify the status of the execution:
*
* If the returned status code is not 0 or 1, then it means that an error occurred.
*
* If the returned status code is 0, then we look at the content of the file which file descriptor is specified by the option "--status-fd".
*
* Valid signatures:
* If we find one of the following tags, we consider that the signature is valid (the return value is true):
* VALIDSIG, GOODSIG, EXPSIG, EXPKEYSIG, or REVKEYSIG.
* Please note that the presence of the following tag will trigger a warning message:
* EXPSIG, EXPKEYSIG, or REVKEYSIG.
*
* Invalid signatures:
* If we find the tag BADSIG, then we consider that the signature is not valid (the return value is false).
*
* Errors:
* If we find the tag ERRSIG, then we raise an exception. It means that we can not verify the signature.
*
* @see http://git.gnupg.org/cgi-bin/gitweb.cgi?p=gnupg.git;a=blob_plain;f=doc/DETAILS
* @throws \Exception
*/
static public function verifyDetachedSignedFile($inSignatureFilePath, $inDocument, &$outWarning) {
$outWarning = null;
if (! file_exists($inSignatureFilePath)) {
throw new \Exception("File \"$inSignatureFilePath\" does not exist!");
}
if (! file_exists($inDocument)) {
throw new \Exception("File \"$inDocument\" does not exist!");
}
$cmd = array(
'--verify',
escapeshellarg($inSignatureFilePath),
escapeshellarg($inDocument)
);
$result = self::__exec($cmd);
$statusCode = $result[self::KEY_COMMAND_RETURN_CODE];
if ((0 !== $statusCode) && (1 !== $statusCode)) {
throw new \Exception("Could not verify the signature from file \"$inSignatureFilePath\": return code is $statusCode.");
}
$statusText = explode(PHP_EOL, $result[self::KEY_COMMAND_STATUS_FILE]);
$status = self::__getVerifySignatureStatus($statusText, $outWarning);
switch ($status) {
case self::STATUS_SIG_VALID: return true;
case self::STATUS_SIG_VALID_BUT_WARNING: return true;
case self::STATUS_SIG_INVALID; return false;
}
throw new \Exception("Could not verify the signature from file \"$inSignatureFilePath\": $outWarning");
}
/**
* Verify a detached signature, given as a string, against a given document.
* @param string $inSignature String that contains the (detached) signature.
* @param string $inDocument Path to the document.
* @param string $outWarning Reference to a string used to store a warning message.
* Warning messages may be reported for valid signatures (that is, when the returned value is true).
* @return bool If the signature is valid, then the method returns the value true.
* Otherwise, it returns the value false.
* Please note that if the returned value is true, indicating that the signature is valid, then you should look for warning messages.
* Indeed, although a signature may be "mathematically" valid, it may have been created with a revoked key (for example).
* In such a case, a warning message is reported, indicating than the key used to produce the signature has been revoked.
* @throws \Exception
* @see Gpg::verifyDetachedSignedFile()
*/
static public function verifyDetachedSignedString($inSignature, $inDocument, &$outWarning) {
if (! file_exists($inDocument)) {
throw new \Exception("File \"$inDocument\" does not exist!");
}
$outWarning = null;
$input = tempnam(sys_get_temp_dir(), 'Gpg::verifyDetachedSignedString::');
if (false === file_put_contents($input, $inSignature)) {
throw new \Exception("Can not write data into temporary file \"$input\"");
}
$result = self::verifyDetachedSignedFile($input, $inDocument, $outWarning);
if (false === unlink($input)) {
throw new \Exception("Can not remove file \"$input\".");
}
return $result;
}
/**
* Detach sign a given file, using a given private key.
* @param string $inAbsolutePath Absolute path to the file to sign.
* @param string $inPrivateKeyFingerPrint Fingerprint of the private key to use.
* @param string $inOptPassword Password associated to the private key.
* If no password is required, then you should set the value of this parameter to null.
* @param null|string $inOptSignaturePath Absolute path to the generated signature.
* If this parameter is not specified, then the method will return the signature as a string.
* @return true|string Upon successful completion:
* If a destination file has been specified, then the method returns the value true.
* Otherwise, the method returns a string that represents the signature.
* @throws \Exception
* @note Commands:
* gpg --list-secret-keys --fingerprint --with-colon
* exec 3> /tmp/status; gpg --batch --yes --status-fd 3 --armor -u 03DEC874738344206A1A7D31E07D9D14954C8DC5 --output file_to_sign.sig --detach-sign file_to_sign.txt; echo $?; exec 3>&-
* exec 3> /tmp/status; gpg --batch --yes --status-fd 3 --armor -u 03DEC874738344206A1A7D31E07D9D14954C8DC5 --output - --detach-sign file_to_sign.txt; echo $?; exec 3>&-
* exec 3> /tmp/status; echo 'password' | gpg --batch --yes --status-fd 3 --armor -u 881C41F8B8FD138E86E7230929A778386005B911 --passphrase-fd 0 --output file_to_sign.sig --detach-sign file_to_sign.txt; echo $?; exec 3>&-
* exec 3> /tmp/status; echo 'password' | gpg --batch --yes --status-fd 3 --armor -u 881C41F8B8FD138E86E7230929A778386005B911 --passphrase-fd 0 --output - --detach-sign file_to_sign.txt; echo $?; exec 3>&-
* @see Gpg::__getSignFileStatus
* @see Gpg::signFile
*/
static public function detachSignFile($inAbsolutePath, $inPrivateKeyFingerPrint, $inOptPassword=null, $inOptSignaturePath=null)
{
$inAbsolutePath = realpath($inAbsolutePath);
$inOptSignaturePath = is_null($inOptSignaturePath) ? null : $inOptSignaturePath;
if (! file_exists($inAbsolutePath)) {
throw new \Exception("File <$inAbsolutePath> does not exist.");
}
$cmd = array(
'--armor',
'-u',
escapeshellarg($inPrivateKeyFingerPrint),
'--detach-sign',
escapeshellarg($inAbsolutePath)
);
$result = self::__exec($cmd, $inOptSignaturePath, $inOptPassword);