X-Git-Url: https://git.m6w6.name/?a=blobdiff_plain;f=src%2Fpharext%2FOpenssl%2FPrivateKey.php;h=481fd86aa85a8c6b90628dc1b8f3adb7322a1488;hb=588c266f29af65ea5706c9251c1ec2f92fc30880;hp=1d3aed1e6d3d2a035ce2a7e1933e0d1590a88f7d;hpb=50e5714c543ed50557a1b644c6df27b8d298b6e1;p=pharext%2Fpharext diff --git a/src/pharext/Openssl/PrivateKey.php b/src/pharext/Openssl/PrivateKey.php index 1d3aed1..481fd86 100644 --- a/src/pharext/Openssl/PrivateKey.php +++ b/src/pharext/Openssl/PrivateKey.php @@ -2,26 +2,57 @@ namespace pharext\Openssl; +use pharext\Exception; + class PrivateKey { + /** + * Private key + * @var string + */ private $key; + /** + * Public key + * @var string + */ + private $pub; + + /** + * Read a private key + * @param string $file + * @param string $password + * @throws \pharext\Exception + */ function __construct($file, $password) { - $this->key = openssl_pkey_get_private("file://$file", $password); - if (!is_resource($this->key)) { - throw new \Exception("Could not load private key"); + /* there appears to be a bug with refcount handling of this + * resource; when the resource is stored as property, it cannot be + * "coerced to a private key" on openssl_sign() later in another method + */ + $key = openssl_pkey_get_private("file://$file", $password); + if (!is_resource($key)) { + throw new Exception("Could not load private key"); } + openssl_pkey_export($key, $this->key); + $this->pub = openssl_pkey_get_details($key)["key"]; } - + + /** + * Sign the PHAR + * @param \Phar $package + */ function sign(\Phar $package) { $package->setSignatureAlgorithm(\Phar::OPENSSL, $this->key); } - + + /** + * Export the public key to a file + * @param string $file + * @throws \pharext\Exception + */ function exportPublicKey($file) { - if (!file_put_contents("$file.tmp", openssl_pkey_get_details($this->key)["key"]) - || !rename("$file.tmp", $file) - ) { - throw new \Exception(error_get_last()["message"]); + if (!file_put_contents("$file.tmp", $this->pub) || !rename("$file.tmp", $file)) { + throw new Exception; } } }