major refactoring under the hood
[pharext/pharext] / src / pharext / Openssl / PrivateKey.php
1 <?php
2
3 namespace pharext\Openssl;
4
5 use pharext\Exception;
6
7 class PrivateKey
8 {
9 /**
10 * Private key
11 * @var string
12 */
13 private $key;
14
15 /**
16 * Public key
17 * @var string
18 */
19 private $pub;
20
21 /**
22 * Read a private key
23 * @param string $file
24 * @param string $password
25 * @throws \pharext\Exception
26 */
27 function __construct($file, $password) {
28 /* there appears to be a bug with refcount handling of this
29 * resource; when the resource is stored as property, it cannot be
30 * "coerced to a private key" on openssl_sign() later in another method
31 */
32 $key = openssl_pkey_get_private("file://$file", $password);
33 if (!is_resource($key)) {
34 throw new Exception("Could not load private key");
35 }
36 openssl_pkey_export($key, $this->key);
37 $this->pub = openssl_pkey_get_details($key)["key"];
38 }
39
40 /**
41 * Sign the PHAR
42 * @param \Phar $package
43 */
44 function sign(\Phar $package) {
45 $package->setSignatureAlgorithm(\Phar::OPENSSL, $this->key);
46 }
47
48 /**
49 * Export the public key to a file
50 * @param string $file
51 * @throws \pharext\Exception
52 */
53 function exportPublicKey($file) {
54 if (!file_put_contents("$file.tmp", $this->pub) || !rename("$file.tmp", $file)) {
55 throw new Exception;
56 }
57 }
58 }