470983da3972ccf8c21634c7602a7a3e9a000730
[pharext/pharext] / src / pharext / Openssl / PrivateKey.php
1 <?php
2
3 namespace pharext\Openssl;
4
5 class PrivateKey
6 {
7 /**
8 * OpenSSL pkey resource
9 * @var resource
10 */
11 private $key;
12
13 /**
14 * Read a private key
15 * @param string $file
16 * @param string $password
17 * @throws \Exception
18 */
19 function __construct($file, $password) {
20 $this->key = openssl_pkey_get_private("file://$file", $password);
21 if (!is_resource($this->key)) {
22 throw new \Exception("Could not load private key");
23 }
24 }
25
26 /**
27 * Sign the PHAR
28 * @param \Phar $package
29 */
30 function sign(\Phar $package) {
31 $package->setSignatureAlgorithm(\Phar::OPENSSL, $this->key);
32 }
33
34 /**
35 * Export the public key to a file
36 * @param string $file
37 * @throws \Exception
38 */
39 function exportPublicKey($file) {
40 if (!file_put_contents("$file.tmp", openssl_pkey_get_details($this->key)["key"])
41 || !rename("$file.tmp", $file)
42 ) {
43 throw new \Exception(error_get_last()["message"]);
44 }
45 }
46 }