/** * Generate a signature of the given data using a private key and an algorithm. * * @param string $data * @param PrivateKey $privateKey * @param int $algorithm * * @return string */ public function signData($data, PrivateKey $privateKey, $algorithm = OPENSSL_ALGO_SHA256) { if (!openssl_sign($data, $signature, $privateKey->getResource(), $algorithm)) { throw new DataSigningException(sprintf('OpenSSL data signing failed with error: %s', openssl_error_string())); } return $signature; }
function getSignedURL($resource, $timeout) { //This comes from key pair you generated for cloudfront $keyPairId = $this->config->item('cloudfront_keyPairId'); $key = $this->config->item('cloudfront_key'); //IMPORTANT: Keep private and not in a web-accessible location //Set privateKey location based on web url (dev or production) $privateKey = $this->config->item('cloudfront_keyLocation') . $key; $expires = time() + $timeout; //Time out in seconds $json = '{"Statement":[{"Resource":"' . $resource . '","Condition":{"DateLessThan":{"AWS:EpochTime":' . $expires . '}}}]}'; //Read Cloudfront Private Key Pair $fp = fopen($privateKey, "r"); $priv_key = fread($fp, 8192); fclose($fp); //Create the private key $key = openssl_get_privatekey($priv_key); if (!$key) { echo "<p>Failed to load private key!</p>"; return; } //Sign the policy with the private key if (!openssl_sign($json, $signed_policy, $key, OPENSSL_ALGO_SHA1)) { echo '<p>Failed to sign policy: ' . openssl_error_string() . '</p>'; return; } //Create url safe signed policy $base64_signed_policy = base64_encode($signed_policy); $signature = str_replace(array('+', '=', '/'), array('-', '_', '~'), $base64_signed_policy); //Construct the URL $url = $resource . '?Expires=' . $expires . '&Signature=' . $signature . '&Key-Pair-Id=' . $keyPairId; return $url; }
/** * @param string $securedInput * @param string $key * * @return string */ public function sign($securedInput, $key) { if (false === openssl_sign($securedInput, $signature, $key, $this->signatureAlgorithm)) { throw new JoseJwtException('Unable to sign data: ' . openssl_error_string()); } return $signature; }
/** * Generates a new key pair with the given length in bits. * * @api * @param int $bits length of the key * @return KeyPair generated key pair */ public function generate($bits = 2048) { if (!is_int($bits)) { throw new \InvalidArgumentException(sprintf("\$bits must be of type int, %s given", gettype($bits))); } if ($bits < 2048) { throw new \InvalidArgumentException("Keys with fewer than 2048 bits are not allowed!"); } $configFile = $defaultConfigFile = __DIR__ . "/../res/openssl.cnf"; if (class_exists("Phar") && !empty(Phar::running(true))) { $configContent = file_get_contents($configFile); $configFile = tempnam(sys_get_temp_dir(), "acme_openssl_"); file_put_contents($configFile, $configContent); register_shutdown_function(function () use($configFile) { @unlink($configFile); }); } $res = openssl_pkey_new(["private_key_type" => OPENSSL_KEYTYPE_RSA, "private_key_bits" => $bits, "config" => $configFile]); $success = openssl_pkey_export($res, $privateKey, null, ["config" => $configFile]); if ($configFile !== $defaultConfigFile) { @unlink($configFile); } if (!$success) { openssl_pkey_free($res); throw new \RuntimeException("Key export failed!"); } $publicKey = openssl_pkey_get_details($res)["key"]; openssl_pkey_free($res); // clear error buffer, because of minimalistic openssl.cnf while (openssl_error_string() !== false) { } return new KeyPair($privateKey, $publicKey); }
public function __construct($message, $code = 0, Exception $previous = null) { while (($error = openssl_error_string()) !== false) { $message .= "\n {$error}"; } parent::__construct($message, $code, $previous); }
function decryptMessage($crypttext, $priv_key, $passphrase = 'passphrase') { $crypttext = base64_decode($crypttext); $res = openssl_pkey_get_private($priv_key, $passphrase); if ($res != false) { if (openssl_private_decrypt($crypttext, $text, $res)) { return $text; } else { $error = ""; while ($msg = openssl_error_string()) { $error .= $msg . "<br />\n"; } $error = __(DECRYPT_ERROR) . (DEBUG && $error != "" ? " : " . $error : ""); throw new NewException($error, 0, false); } } else { $error = ""; while ($msg = openssl_error_string()) { $error .= $msg . "<br />\n"; } $error = "Error parsing private key" . ($error != "" ? " : " . $error : ""); throw new NewException($error, 0, getDebugBacktrace(1)); } return ""; }
function getSignedURL($resource, $timeout) { //This comes from key pair you generated for cloudfront $keyPairId = "APKAIA3QRQOKVKEQDHZA"; $expires = time() + $timeout; //Time out in seconds $json = '{"Statement":[{"Resource":"' . $resource . '","Condition":{"DateLessThan":{"AWS:EpochTime":' . $expires . '}}}]}'; //Read Cloudfront Private Key Pair $fp = fopen("private_key.pem", "r"); $priv_key = fread($fp, 8192); fclose($fp); //Create the private key //$key = openssl_get_privatekey($priv_key); $key = openssl_get_privatekey("file://private_key.pem"); if (!$key) { echo "<p>Failed to load private key!</p>"; return; } //Sign the policy with the private key if (!openssl_sign($json, $signed_policy, $key, OPENSSL_ALGO_SHA1)) { echo '<p>Failed to sign policy: ' . openssl_error_string() . '</p>'; return; } //Create url safe signed policy $base64_signed_policy = base64_encode($signed_policy); $signature = str_replace(array('+', '=', '/'), array('-', '_', '~'), $base64_signed_policy); //Construct the URL $url = $resource . '?Expires=' . $expires . '&Signature=' . $signature . '&Key-Pair-Id=' . $keyPairId; return $url; }
/** * Parse the certificate. * * @param Certificate $certificate * * @return ParsedCertificate */ public function parse(Certificate $certificate) { $rawData = openssl_x509_parse($certificate->getPEM()); if (!is_array($rawData)) { throw new CertificateParsingException(sprintf('Fail to parse certificate with error: %s', openssl_error_string())); } if (!isset($rawData['subject']['CN'])) { throw new CertificateParsingException('Missing expected key "subject.cn" in certificate'); } if (!isset($rawData['issuer']['CN'])) { throw new CertificateParsingException('Missing expected key "issuer.cn" in certificate'); } if (!isset($rawData['serialNumber'])) { throw new CertificateParsingException('Missing expected key "serialNumber" in certificate'); } if (!isset($rawData['validFrom_time_t'])) { throw new CertificateParsingException('Missing expected key "validFrom_time_t" in certificate'); } if (!isset($rawData['validTo_time_t'])) { throw new CertificateParsingException('Missing expected key "validTo_time_t" in certificate'); } $subjectAlternativeName = []; if (isset($rawData['extensions']['subjectAltName'])) { $subjectAlternativeName = array_map(function ($item) { return explode(':', trim($item), 2)[1]; }, array_filter(explode(',', $rawData['extensions']['subjectAltName']), function ($item) { return false !== strpos($item, ':'); })); } return new ParsedCertificate($certificate, $rawData['subject']['CN'], $rawData['issuer']['CN'], $rawData['subject'] === $rawData['issuer'], new \DateTime('@' . $rawData['validFrom_time_t']), new \DateTime('@' . $rawData['validTo_time_t']), $rawData['serialNumber'], $subjectAlternativeName); }
/** * Generate a CSR object with SANs from the given distinguishedName and keyPair. * * @param CertificateRequest $certificateRequest * * @return mixed */ protected function createCsrWithSANsObject(CertificateRequest $certificateRequest) { $sslConfigTemplate = <<<'EOL' [ req ] distinguished_name = req_distinguished_name req_extensions = v3_req [ req_distinguished_name ] [ v3_req ] basicConstraints = CA:FALSE keyUsage = nonRepudiation, digitalSignature, keyEncipherment subjectAltName = @req_subject_alt_name [ req_subject_alt_name ] %s EOL; $sslConfigDomains = []; $distinguishedName = $certificateRequest->getDistinguishedName(); $domains = array_merge([$distinguishedName->getCommonName()], $distinguishedName->getSubjectAlternativeNames()); foreach (array_values($domains) as $index => $domain) { $sslConfigDomains[] = 'DNS.' . ($index + 1) . ' = ' . $domain; } $sslConfigContent = sprintf($sslConfigTemplate, implode("\n", $sslConfigDomains)); $sslConfigFile = tempnam(sys_get_temp_dir(), 'acmephp_'); try { file_put_contents($sslConfigFile, $sslConfigContent); $resource = $certificateRequest->getKeyPair()->getPrivateKey()->getResource(); $csr = openssl_csr_new($this->getCSRPayload($distinguishedName), $resource, ['digest_alg' => 'sha256', 'config' => $sslConfigFile]); if (!$csr) { throw new CSRSigningException(sprintf('OpenSSL CSR signing failed with error: %s', openssl_error_string())); } return $csr; } finally { unlink($sslConfigFile); } }
/** * {@inheritdoc} */ public function getResource() { if (!($resource = openssl_pkey_get_public($this->keyPEM))) { throw new KeyFormatException(sprintf('Fail to convert key into resource: %s', openssl_error_string())); } return $resource; }
public function __construct($p12, $password) { if (!function_exists('openssl_x509_read')) { throw new Google_Exception('The Google PHP API library needs the openssl PHP extension'); } // If the private key is provided directly, then this isn't in the p12 // format. Different versions of openssl support different p12 formats // and the key from google wasn't being accepted by the version available // at the time. if (!$password && strpos($p12, "-----BEGIN RSA PRIVATE KEY-----") !== false) { $this->privateKey = openssl_pkey_get_private($p12); } elseif ($password === 'notasecret' && strpos($p12, "-----BEGIN PRIVATE KEY-----") !== false) { $this->privateKey = openssl_pkey_get_private($p12); } else { // This throws on error $certs = array(); if (!openssl_pkcs12_read($p12, $certs, $password)) { throw new Google_Auth_Exception("Unable to parse the p12 file. " . "Is this a .p12 file? Is the password correct? OpenSSL error: " . openssl_error_string()); } // TODO(beaton): is this part of the contract for the openssl_pkcs12_read // method? What happens if there are multiple private keys? Do we care? if (!array_key_exists("pkey", $certs) || !$certs["pkey"]) { throw new Google_Auth_Exception("No private key found in p12 file."); } $this->privateKey = openssl_pkey_get_private($certs['pkey']); } if (!$this->privateKey) { throw new Google_Auth_Exception("Unable to load private key"); } }
/** * Parse the key. * * @param Key $key * * @return ParsedKey */ public function parse(Key $key) { try { $resource = $key->getResource(); } catch (KeyFormatException $e) { throw new KeyParsingException('Fail to load resource for key', 0, $e); } $rawData = openssl_pkey_get_details($resource); if (!is_array($rawData)) { throw new KeyParsingException(sprintf('Fail to parse key with error: %s', openssl_error_string())); } foreach (['type', 'key', 'bits'] as $requiredKey) { if (!isset($rawData[$requiredKey])) { throw new KeyParsingException(sprintf('Missing expected key "%s" in OpenSSL key', $requiredKey)); } } $details = []; if ($rawData['type'] === OPENSSL_KEYTYPE_RSA) { $details = $rawData['rsa']; } elseif ($rawData['type'] === OPENSSL_KEYTYPE_DSA) { $details = $rawData['dsa']; } elseif ($rawData['type'] === OPENSSL_KEYTYPE_DH) { $details = $rawData['dh']; } return new ParsedKey($key, $rawData['key'], $rawData['bits'], $rawData['type'], $details); }
public function seal($data) { $key = $this->_getKeyResource(); if (openssl_seal($data, $sealed, $ekeys, array($key)) === false) { throw new Relax_Openssl_Exception("Error sealing: " . openssl_error_string()); } return array($sealed, $ekeys[0]); }
/** * Retrieve errors * * @return string[] error */ public static function getErrors() { $e = []; while ($msg = openssl_error_string()) { $e[] = $msg; } return $e; }
/** * Static "constructor" - creates a Key object from a private key string. * * @param string $keyString * @param string $passPhrase * @return \OpenSslCrypt\Key */ public static function fromPrivateKeyString($keyString, $passPhrase = '') { $key = openssl_pkey_get_private($keyString, $passPhrase); if ($key === FALSE) { throw new \Exception(sprintf("Error extracting private key: %s", openssl_error_string())); } return new self($key); }
public function sign($data, $algorithm = OPENSSL_ALGO_SHA1) { $key = $this->_getKeyResource(); if (!openssl_sign($data, $hash, $key, $algorithm)) { throw new Relax_Openssl_Exception("Error signing data: " . openssl_error_string()); } return $hash; }
/** * @param string $sealed encrypted value, base64 encoded * @param string $shareKey share key, base64 encoded * @param PrivateKey $private * @return null|string */ public function unseal($sealed, $shareKey, PrivateKey $private) { $unsealed = null; if (openssl_open($this->decode($sealed), $unsealed, $this->decode($shareKey), $private->getResource())) { return $unsealed; } throw new \RuntimeException('Cannot unseal: ' . openssl_error_string()); }
/** * @return array */ public static function getErrors() : array { $messages = []; while ($message = openssl_error_string()) { $messages[] = $message; } return $messages; }
private static function getOpensslErrors() { $errors = array(); while ($error = openssl_error_string()) { $errors[] = $error; } return $errors; }
/** * Get latest OpenSSL error message. * * @return string */ protected static function _getLastOpenSSLError() { $msg = null; while (false !== ($err = openssl_error_string())) { $msg = $err; } return $msg; }
/** * Static "constructor" - creates a Key object from a certificate string. * * @param string $certString * @throws \Exception * @return Pub */ public static function fromCertificateString($certString) { $key = openssl_pkey_get_public($certString); if ($key === FALSE) { throw new \Exception(sprintf("Error extracting public key from certificate: %s", openssl_error_string())); } return new self($key); }
/** * @param resource $private_or_public_key_resource * @return bool * @throws \Cyh\Jose\Encryption\Exception\UnexpectedValueException */ protected function validateKey($private_or_public_key_resource) { $details = openssl_pkey_get_details($private_or_public_key_resource); if (!is_array($details) || !isset($details['type']) || OPENSSL_KEYTYPE_RSA !== $details['type']) { throw new UnexpectedValueException('Invalid key. : ' . openssl_error_string()); } return true; }
/** * @return array */ private function getSslErrors() { $messages = []; while ($msg = openssl_error_string()) { $messages[] = $msg; } return $messages; }
public function __construct($message, $code = 0, \Exception $previous = null) { parent::__construct($message, $code, $previous); if ($openSSlErrorMessage = openssl_error_string()) { // openSSL has something to say! Let us add it to the message. $this->message = sprintf('%s%sUnderlying openSSL message : %s', parent::getMessage(), PHP_EOL, $openSSlErrorMessage); } }
/** * Decrypts data stored in an EncryptedData object (data + key). * * @param EncryptedData $encryptedData * @param Priv $key * @throws \Exception * @return string */ public function decrypt(EncryptedData $encryptedData, Priv $key) { $decData = ''; if (!openssl_open($encryptedData->getData(), $decData, $encryptedData->getKey(), $key->asResource())) { throw new \Exception(sprintf("Error decrypting data with private key: %s", openssl_error_string())); } return $decData; }
/** * Verifies the signature on data. * * Returns true if the signature is valid, false otherwise. * @param $data * @param $signature * @throws Google_AuthException * @return bool */ function verify($data, $signature) { $status = openssl_verify($data, $signature, $this->publicKey, "sha256"); if ($status === -1) { throw new Google_AuthException('Signature verification error: ' . openssl_error_string()); } return $status === 1; }
/** * Get last OpenSSL error message. * * @return string|null */ protected function _getLastError() { // pump error message queue $msg = null; while (false !== ($err = openssl_error_string())) { $msg = $err; } return $msg; }
/** * Verifies the signature on data. * * Returns true if the signature is valid, false otherwise. * @param $data * @param $signature * @throws IWP_google_Auth_Exception * @return bool */ public function verify($data, $signature) { $hash = defined("OPENSSL_ALGO_SHA256") ? OPENSSL_ALGO_SHA256 : "sha256"; $status = openssl_verify($data, $signature, $this->publicKey, $hash); if ($status === -1) { throw new IWP_google_Auth_Exception('Signature verification error: ' . openssl_error_string()); } return $status === 1; }
/** * @param $publicKey * @param $cypher * @return string * @throws \Exception */ public function rsaEncrypter($publicKey, $cypher) { $publicKey = base64_decode($publicKey); if (!$publicKey) { throw new \Exception(openssl_error_string()); } openssl_public_encrypt(substr($cypher, 0, 21), $crypttext, $publicKey); return base64_encode($crypttext); }
/** * Clears the error buffer, preventing unassociated error messages from * being used by the lastError() method. This is required for lsatError() * to function properly. If the clearing loop continues beyond a certain * number, a warning will be triggered before the loop is broken. * * @param integer $count The maximum number of rounds. */ public static function reset($count = 100) { $counter = 0; while (openssl_error_string()) { if ($count < ++$counter) { trigger_error("The OpenSSL error clearing loop has exceeded {$count} rounds.", E_USER_WARNING); break; } } }