public function post_id_new1_new2_handler() { global $FANNIE_PLUGIN_SETTINGS, $FANNIE_OP_DB; $dbc = FannieDB::get($FANNIE_PLUGIN_SETTINGS['GiveUsMoneyDB']); $ret = array('errors' => ''); $safe = $this->safetyCheck(); if ($safe !== true) { $ret['errors'] = $safe; } else { $keyfile = realpath(dirname(__FILE__) . '/keys/public.key'); $pubkey = openssl_pkey_get_public(file_get_contents($keyfile)); $try = openssl_public_encrypt($this->new1, $encrypted, $pubkey); if (!$try) { $ret['errors'] = 'Error occurred during encryption'; } else { if ($this->new1 !== $this->new2) { $ret['errors'] = 'New values do not match'; } else { $model = new GumTaxIdentifiersModel($dbc); $model->card_no($this->id); $model->encryptedTaxIdentifier($encrypted); $model->maskedTaxIdentifier(substr($this->new1, -4)); $model->save(); } } } echo json_encode($ret); return false; }
/** * {@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; }
/** * getPrivateKey * @return resource|FALSE * @see http://cn2.php.net/manual/en/function.openssl-get-publickey.php */ private function getKey() { if ($this->_keyInstance === false) { $this->_keyInstance = openssl_pkey_get_public($this->key); } return $this->_keyInstance; }
function ValidateGooglePlaySignature($receipt, $signature) { $publicGoogleKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAt+zLT00kiP/8iHZrvBwbAOIibC6qhGW9Mt6FHFHh+uJN5+wIYWKfsWS8cU9383iJ6Q0zL2Gk7UQtZvp9ug3yCzWkTADWzepO8rm0+gBuv7OcrIq5TF5qIS4qXrmTg1VkloJb0C4OP9IPqRpa9VKa1nWIa1VbLY2U4U7vgQIcLBIGL+5d2/qhjj4UeK3seWvY8XxHh9CElxMAmaOWU6aNUSon0G7r68gwx15hMOoVy4ICeKrGyn8XibTiruYwXHwBJ6JQNYzWRtJPEF1DL1TLev/DneVVoFgrc6ZnZMZGwlnYLKn0AolCTfq2c1GRUj/FI/wd3Rcm6lHeN3pbkmb1GwIDAQAB"; $receipt = trim($receipt); $signature = trim($signature); //Create an RSA key compatible with openssl_verify from our Google Play sig $key = "-----BEGIN PUBLIC KEY-----\n" . chunk_split($publicGoogleKey, 64, "\n") . '-----END PUBLIC KEY-----'; $key = openssl_pkey_get_public($key); //print $signature;print_r(openssl_pkey_get_details($key)); exit(); if ($key == false) { return $ret = 100; } //Signature should be in binary format, but it comes as BASE64. $signature = base64_decode($signature); //Verify the signature $result = openssl_verify($receipt, $signature, $key, OPENSSL_ALGO_SHA1); //print $result . ' / ' . $receipt . ' / ' . $signature . ' / ' . $key;exit(); if ($result == 1) { $ret = 1; } elseif ($result == 0) { $ret = 0; } else { $ret = 2; } return $ret; }
/** * @param $data * * @throws \Exception * @throws \FG\ASN1\Exception\ParserException * * @return array */ private function loadPEM($data) { $res = openssl_pkey_get_private($data); if (false === $res) { $res = openssl_pkey_get_public($data); } if (false === $res) { throw new \Exception('Unable to load the key'); } $details = openssl_pkey_get_details($res); if (!array_key_exists('rsa', $details)) { throw new \Exception('Unable to load the key'); } foreach ($details['rsa'] as $key => $value) { $value = Base64Url::encode($value); if ($key === 'dmp1') { $this->dp = $value; } elseif ($key === 'dmq1') { $this->dq = $value; } elseif ($key === 'iqmp') { $this->qi = $value; } else { $this->{$key} = $value; } } }
function publicKeyEncrypt($publicKey, $content) { $pKey = openssl_pkey_get_public($publicKey); $encrypted = ""; openssl_public_encrypt($content, $encrypted, $pKey); return base64_encode($encrypted); }
public function __construct($headers = null, $body = null) { $config = Payplug::getConfig(); if (is_null($config)) { throw new ParametersNotSetException(); } if (is_null($body)) { $body = file_get_contents("php://input"); } if (is_null($headers)) { $headers = getallheaders(); } $headers = array_change_key_case($headers, CASE_UPPER); $signature = base64_decode($headers['PAYPLUG-SIGNATURE']); $publicKey = openssl_pkey_get_public($config->payplugPublicKey); $isValid = openssl_verify($body, $signature, $publicKey, OPENSSL_ALGO_SHA1); if (!$isValid) { throw new InvalidSignatureException(); } $data = json_decode($body, true); $this->amount = $data['amount']; $this->customData = $data['custom_data']; $this->customer = $data['customer']; $this->email = $data['email']; $this->firstName = $data['first_name']; $this->idTransaction = $data['id_transaction']; $this->lastName = $data['last_name']; $this->order = $data['order']; $this->origin = $data['origin']; $this->state = $data['state']; }
public function __construct($certificate) { if (!extension_loaded('openssl')) { throw new OpenSSLExtensionNotLoadedException('The openssl module is not loaded.'); } $this->keyResource = openssl_pkey_get_public($certificate); }
/** * Fetches public key from the remote certificate * * @param $url * @return string|false */ protected function fetchPublicKey($url) { $cache = \Yii::$app->cache; $cacheKey = 'paypal-public-key-' . md5($url); $publicKey = $cache->get($cacheKey); if ($publicKey) { return $publicKey; } // trying to fetch certificate $cert = @file_get_contents($url); if (!$cert) { return false; } $key = openssl_pkey_get_public($cert); if (!$key) { return false; } $keyData = openssl_pkey_get_details($key); $result = ArrayHelper::getValue($keyData, 'key', false); if (!$result) { return false; } $cache->add($cacheKey, $result); return $result; }
/** * {@inheritdoc} */ public function encrypt($data, $key) { $publicKey = openssl_pkey_get_public($key); openssl_public_encrypt($data, $messageEncrypted, $publicKey); openssl_free_key($publicKey); return $messageEncrypted; }
function decryptPublic($path, $cText) { $fcontents = file_get_contents($path); $publicKey = openssl_pkey_get_public($fcontents); openssl_public_decrypt($cText, $decrypted, $publicKey); return $decrypted; }
/** * Converts a string representation of a key into an OpenSSL resource * * @param string|resource $key * @param string $password * @return resource OpenSSL key resource */ protected function getKeyResource($key, $password = null) { if (is_resource($key)) { return $key; } return openssl_pkey_get_public($key) ?: openssl_pkey_get_private($key, $password); }
function __construct($clientcrt, $clientkey, $clientpw = NULL, $logging = false) { if (is_bool($logging)) { $this->logging = $logging; } if (!openssl_pkey_get_private(is_file($clientkey) ? "file://" . $clientkey : $clientkey, $clientpw)) { $this->log("Invalid client private key.", true); } if (!openssl_pkey_get_public(is_file($clientcrt) ? "file://" . $clientcrt : $clientcrt)) { $this->log("Invalid client public key.", true); } $this->log("Certificate / key looks valid."); $handle = curl_init(); curl_setopt($handle, CURLOPT_RETURNTRANSFER, true); curl_setopt($handle, CURLOPT_HEADER, true); curl_setopt($handle, CURLOPT_USERAGENT, sprintf("StartSSL-PHP-API/%s", self::VERSION)); curl_setopt($handle, CURLOPT_URL, $this->authUrl); curl_setopt($handle, CURLOPT_SSLCERT, $clientcrt); curl_setopt($handle, CURLOPT_SSLKEY, $clientkey); if (!is_null($clientpw)) { curl_setopt($handle, CURLOPT_SSLKEYPASSWD, $clientpw); } $this->log("Authenticating..."); $result = curl_exec($handle); preg_match('/^Set-Cookie: (MyStartSSLCookie=.*)$/m', $result, $matches); if (isset($matches[1])) { $this->cookie = $matches[1]; $this->log("User authenticated."); } else { $this->log("Unable to authenticate. Check certificate/key.", true); } }
/** * @return resource */ protected function getPublicKey() { if (is_null($this->publicKey)) { throw new ParameterNotFoundException("'publicKey' in JWTEncoder"); } return openssl_pkey_get_public('file://' . $this->publicKey); }
/** * @Rest\Post("/users/auth") * @param unknown $request */ public function userAuthAction() { $data = $this->getRequest()->get("data"); $stringDecrypted = ""; openssl_private_decrypt(base64_decode($data), $stringDecrypted, openssl_pkey_get_private(file_get_contents(__DIR__ . "/keys/server/private_key_server.pem"))); $jsonDecrypted = json_decode($stringDecrypted); $entityManager = $this->container->get('fos_user.user_manager'); $user = $entityManager->findUserByUsername($jsonDecrypted->username); $encoder_service = $this->get('security.encoder_factory'); $encoder = $encoder_service->getEncoder($user); $encoded_pass = $encoder->isPasswordValid($user->getPassword(), $jsonDecrypted->password, $user->getSalt()); $token = 0; if ($encoded_pass) { $currentTime = time(); $tokenTime = $currentTime + 86400; // on day $user->setTokenExpiresAt($tokenTime); $clearToken = $user->getUsername() . '@' . $tokenTime; $shaToken = sha1($clearToken); $user->setToken($shaToken); $stringCrypted = ""; $json = "{'token':'" . $clearToken . "'}"; openssl_public_encrypt($json, $stringCrypted, openssl_pkey_get_public(file_get_contents(__DIR__ . "/keys/server/public_key_mobile.pem"))); $token = base64_encode($stringCrypted); return json_encode(["data" => $token]); } else { return false; } }
static public function get_keys($login,$full_name) { $CA_CERT = base_url()."data/key/CA_DOC.csr"; $CA_KEY = base_url()."data/key/CA_DOC_priv.key"; $config = array( "private_key_type"=>OPENSSL_KEYTYPE_RSA, "private_key_bits"=>512 ); $res = openssl_pkey_new($config); $privKey = ''; openssl_pkey_export($res,$privKey); $arr = array( "organizationName" => "Фізична особа", "organizationalUnitName" => "Фізична особа", "commonName" => $full_name, "UID" => $login, "countryName" => "UA" ); $csr = openssl_csr_new($arr,$privKey); $cert = openssl_csr_sign($csr,file_get_contents($CA_CERT),file_get_contents($CA_KEY),730); openssl_x509_export($cert,$str_cert); $public_key = openssl_pkey_get_public($str_cert); $public_key_details = openssl_pkey_get_details($public_key); $public_key_string = $public_key_details['key']; return array('private'=>$privKey,'cert'=>$str_cert,'public'=>$public_key_string); }
function webid_claim() { $r = array('uri' => array()); if (isset($_SERVER['SSL_CLIENT_CERT'])) { $pem = $_SERVER['SSL_CLIENT_CERT']; if ($pem) { $x509 = openssl_x509_read($pem); $pubKey = openssl_pkey_get_public($x509); $keyData = openssl_pkey_get_details($pubKey); if (isset($keyData['rsa'])) { if (isset($keyData['rsa']['n'])) { $r['m'] = strtolower(array_pop(unpack("H*", $keyData['rsa']['n']))); } if (isset($keyData['rsa']['e'])) { $r['e'] = hexdec(array_shift(unpack("H*", $keyData['rsa']['e']))); } } $d = openssl_x509_parse($x509); if (isset($d['extensions']) && isset($d['extensions']['subjectAltName'])) { foreach (explode(', ', $d['extensions']['subjectAltName']) as $elt) { if (substr($elt, 0, 4) == 'URI:') { $r['uri'][] = substr($elt, 4); } } } } } return $r; }
/** * Store a newly created resource in storage. * * @param Request $request * @return Response */ public function store(Request $request) { // //Log::info('$request=<' . $request . '>'); if ($request->isMethod('post')) { $bodyContent = $request->getContent(); //Log::info('$bodyContent=<' . $bodyContent . '>'); $bodyJson = json_decode($bodyContent); $keyPath = $this->keyRoot_ . $bodyJson->token . '/pubKey.pem'; $fp = fopen($keyPath, 'r'); $pubKeyMem = fread($fp, 8192); fclose($fp); $pubkeyid = openssl_pkey_get_public($pubKeyMem); $token = $bodyJson->token; $sign = $bodyJson->sign; $ok = openssl_verify($token, hex2bin($sign), $pubkeyid, "sha256"); openssl_free_key($pubkeyid); if ($ok == 1) { $profilePath = $this->keyRoot_ . $bodyJson->token . '/profile'; //Log::info('$bodyJson->payload=<' . json_encode($bodyJson->payload) . '>'); file_put_contents($profilePath, json_encode($bodyJson->payload)); return response()->json(['status' => 'success']); } else { return response()->json(['status' => 'failure']); } } }
public static function publicKey($uri, $ts) { if (self::publicExists($uri, $ts)) { return openssl_pkey_get_public('file://' . self::_basePath() . '/' . md5($uri . $ts) . '.pub'); } return false; }
/** * 验签 * * @param string $data * @param string $sign * @param string $pem * @return bool 验签状态 */ private function verify($data, $sign) { $p = openssl_pkey_get_public(file_get_contents($this->chinaums_config['publickKey'])); $verify = openssl_verify($data, hex2bin($sign), $p); openssl_free_key($p); return $verify > 0; }
private function _getKeyResource() { if (!is_file($this->_path)) { throw new Relax_Openssl_Exception("Invalid public key: {$this->_path}"); } return openssl_pkey_get_public(file_get_contents($this->_path)); }
/** * Checks the signature of the given message. * * It is assumed that the signature is the last parameter of the urlencoded string, whatever its name. * * Messages need to be decoded in a very picky way, due to the inconsistent URL-encoding of Paybox. * This is why this method accepts the raw query string (GET) or message body (POST), * and not an already decoded array of key-value pairs. * * @param string $message The raw message to check. * @param bool $isPost True if the message comes from a POST request (return URL), false if it comes from a GET request (callback URL). * @param string $publicKeyFile The path to the public key file. Optional, defaults to Paybox's public key. * * @return bool True if the signature of the message is valid, false if it is invalid. * * @throws OpenSSLException If the certificate file is invalid, or an OpenSSL error occurs. */ public function checkSignature($message, $isPost, $publicKeyFile = OpenSSL::PAYBOX_PUBLIC_KEY) { // Dequeue errors than would have been ignored by other libraries. // These errors are persistent across HTTP calls, and could add confusion to our error messages. $this->handleErrors(); $publicKey = openssl_pkey_get_public('file://' . $publicKeyFile); $this->handleErrors($publicKey === false); $data = $this->parseMessage($message, $isPost); if (!$data) { return false; } $signature = end($data); $signatureKey = key($data); unset($data[$signatureKey]); $signedMessage = []; foreach ($data as $key => $value) { $signedMessage[] = $key . '=' . $value; } $signedMessage = implode('&', $signedMessage); if ($isPost) { // The data is double-URL-encoded in this case. $signature = rawurldecode($signature); } $signature = base64_decode($signature); $result = openssl_verify($signedMessage, $signature, $publicKey); $this->handleErrors($result == -1); return (bool) $result; }
/** * Returns a public key from file path or content * * @param string $certificate * * @return resource * * @throws InvalidArgumentException */ public function getPublicKey($certificate) { if ($publicKey = openssl_pkey_get_public($certificate)) { return $publicKey; } throw new InvalidArgumentException('You should provid a valid certificate'); }
public function __construct($accessKey, $secretKey, $encryptionMaterials, $endpoint = NULL) { parent::__construct($accessKey, $secretKey, $endpoint); if (is_array($encryptionMaterials)) { if (count($encryptionMaterials) == 2) { $pk = openssl_pkey_get_public($encryptionMaterials[0]); $sk = openssl_pkey_get_private($encryptionMaterials[1]); if (!$pk) { throw new Ks3ClientException("invalid RSA public key,you can generate key use openssl"); } if (!$sk) { throw new Ks3ClientException("invalid RSA private key,you can generate key use openssl"); } $encryptionMaterials = array($pk, $sk); } else { throw new Ks3ClientException("encryptionMaterials should be string or an array of size 2"); } } $ks3client = new Ks3Client($accessKey, $secretKey, $endpoint); $this->encryptionMaterials = $encryptionMaterials; if (ENCRYPTPTION_MODE == "EO") { $this->encryptionHandler = new EncryptionEO($ks3client, $encryptionMaterials); } elseif (ENCRYPTPTION_MODE == "AE") { throw new Ks3ClientException("Authenticated encryption will be supported in the futher"); } else { throw new Ks3ClientException("unsupported encryption mode :" . ENCRYPTPTION_MODE); } if (ENCRYPTPTION_STORAGE_MODE != "ObjectMetadata" && ENCRYPTPTION_STORAGE_MODE != "InstructionFile") { throw new Ks3ClientException("unsupported encryption storage mode :" . ENCRYPTPTION_STORAGE_MODE); } }
public function encrypt($data) { $pubres = openssl_pkey_get_public($this->pubkey); openssl_public_encrypt($data, $encrypted, $pubres); $encrypted = base64_encode($encrypted); return $encrypted; }
public function testNotSignedByKey() { $privateKey = openssl_pkey_new(); $details = openssl_pkey_get_details($privateKey); $publicKey = openssl_pkey_get_public($details['key']); $signature = new Signature('Hello, world!', 'foobar', 'sha1WithRSAEncryption'); $this->assertFalse($signature->isSignedByKey($publicKey)); }
/** * Create from certificate string representation. * * @param string string * @return security.crypto.PublicKey * @throws security.crypto.CryptoException if the operation fails */ public static function fromString($string) { if (!is_resource($_hdl = openssl_pkey_get_public($string))) { throw new CryptoException('Could not read public key', OpenSslUtil::getErrors()); } $pk = new PublicKey($_hdl); return $pk; }
private function setPublicKey($cert) { $publicKey = @openssl_pkey_get_public($cert); if (!$this->validateOpenSslKey($publicKey)) { throw new InvalidArgumentException('Unable to create public key' . ' from provided certificate. Certificate must be a valid x509' . ' certificate, a PEM encoded certificate, or a path to a file' . ' containing a PEM encoded certificate.'); } $this->publicKey = $publicKey; }
/** * 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); }
private function setPublicKey($cert) { $this->publicKey = @openssl_pkey_get_public($cert); if (!$this->validateOpenSslKey($this->publicKey)) { throw new IAE('Unable to create public key from provided' . ' certificate. Certificate must be a valid x509 certificate,' . ' a PEM encoded certificate, or a path to a file containing a' . ' PEM encoded certificate.'); } }