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