public function seeValidSignature() { $response = $this->getModule('REST')->response; $response = json_decode($response); $sign = base64_url_decode($response->sign); $this->rsa->setSignatureMode(CRYPT_RSA_SIGNATURE_PKCS1); $this->assertTrue($this->rsa->verify($response->data, $sign)); }
function _google_verify_token($public_key, $signature, $signed_data, $sku, $base_url) { $comments = array(); $error = ''; $status = 'unknown'; if (!class_exists('Crypt_RSA')) { $comments[] = 'PHPSecLib is not in the PHP path.'; } $purchaseToken = _google_get_product_id($signed_data, $sku); if (empty($purchaseToken)) { $status = 'invalid'; $error = 'The SKU is not present in the data.'; } else { $status = 'unverified'; // unverified until verified $comments[] = 'The SKU is present in the data.'; $comments[] = 'The purchase token is ' . str_replace("--", "-\n-", $purchaseToken); // Split any --'s otherwise XML is not well-formed // verify the data signature if (!class_exists('Crypt_RSA')) { $error = 'PHPSecLib is not in the PHP path.'; } else { $rsa = new Crypt_RSA(); $rsa->setSignatureMode(CRYPT_RSA_SIGNATURE_PKCS1); $rsa->loadKey("-----BEGIN PUBLIC KEY-----\n" . $public_key . "\n-----END PUBLIC KEY-----"); if ($rsa->verify($signed_data, base64_decode($signature))) { $comments[] = 'verified ok'; $status = 'OK'; } else { $comments[] = 'verification failed'; } } } return array('status' => $status, 'comments' => $comments, 'error' => $error); }
public function downloadPlugin($name, $url, $signature) { if (is_dir(ipFile("Plugin/{$name}/"))) { Service::deactivatePlugin($name); Helper::removeDir(ipFile("Plugin/{$name}/")); } //download plugin $net = new \Ip\Internal\NetHelper(); $pluginTempFilename = $net->downloadFile($url, ipFile('file/secure/tmp/'), $name . '.zip'); if (!$pluginTempFilename) { throw new \Ip\Exception('Plugin file download failed.'); } $archivePath = ipFile('file/secure/tmp/' . $pluginTempFilename); //check signature $fileMd5 = md5_file($archivePath); $rsa = new \Crypt_RSA(); $rsa->loadKey($this->publicKey); $rsa->setSignatureMode(CRYPT_RSA_SIGNATURE_PKCS1); $verified = $rsa->verify($fileMd5, base64_decode($signature)); if (!$verified) { throw new \Ip\Exception('Plugin signature verification failed.'); } //extract $secureTmpDir = ipFile('file/secure/tmp/'); $tmpExtractedDir = \Ip\Internal\File\Functions::genUnoccupiedName($name, $secureTmpDir); \Ip\Internal\Helper\Zip::extract($secureTmpDir . $pluginTempFilename, $secureTmpDir . $tmpExtractedDir); unlink($archivePath); //install $extractedDir = $this->getFirstDir($secureTmpDir . $tmpExtractedDir); $installDir = Model::pluginInstallDir(); $newPluginDir = \Ip\Internal\File\Functions::genUnoccupiedName($name, $installDir); rename($secureTmpDir . $tmpExtractedDir . '/' . $extractedDir, $installDir . $newPluginDir); Service::activatePlugin($name); }
private function checkRsaSignature($toCheck, $signature, $rsaKey) { # de signature is base64 encoded, eerst decoden $signature = base64_decode($signature); # Controleer of we de native OpenSSL libraries moeten # gebruiken om RSA signatures te controleren if (CRYPT_RSA_MODE != CRYPT_RSA_MODE_OPENSSL) { # Initialize the public key to verify with $pubKey['n'] = new Math_BigInteger(base64_decode($rsaKey['modulo']), 256); $pubKey['e'] = new Math_BigInteger(base64_decode($rsaKey['exponent']), 256); # and verify the signature $rsa = new Crypt_RSA(); $rsa->loadKey($pubKey, CRYPT_RSA_PUBLIC_FORMAT_RAW); $rsa->setSignatureMode(CRYPT_RSA_SIGNATURE_PKCS1); # Supress notice if the signature was invalid $saveErrorReporting = error_reporting(E_ERROR); $tmpSave = $rsa->verify($toCheck, $signature); error_reporting($saveErrorReporting); } else { # Initialize the public key to verify with $pubKey['n'] = base64_decode($rsaKey['modulo']); $pubKey['e'] = base64_decode($rsaKey['exponent']); $nativeVerify = new SpotSeclibToOpenSsl(); $tmpSave = $nativeVerify->verify($pubKey, $toCheck, $signature); } # else return $tmpSave; } # checkRsaSignature
public function downloadTheme($name, $url, $signature) { $model = Model::instance(); //download theme $net = new \Ip\Internal\NetHelper(); $themeTempFilename = $net->downloadFile($url, ipFile('file/secure/tmp/'), $name . '.zip'); if (!$themeTempFilename) { throw new \Ip\Exception('Theme file download failed.'); } $archivePath = ipFile('file/secure/tmp/' . $themeTempFilename); //check signature $fileMd5 = md5_file($archivePath); $rsa = new \Crypt_RSA(); $rsa->loadKey($this->publicKey); $rsa->setSignatureMode(CRYPT_RSA_SIGNATURE_PKCS1); $verified = $rsa->verify($fileMd5, base64_decode($signature)); if (!$verified) { throw new \Ip\Exception('Theme signature verification failed.'); } //extract $helper = Helper::instance(); $secureTmpDir = ipFile('file/secure/tmp/'); $tmpExtractedDir = \Ip\Internal\File\Functions::genUnoccupiedName($name, $secureTmpDir); \Ip\Internal\Helper\Zip::extract($secureTmpDir . $themeTempFilename, $secureTmpDir . $tmpExtractedDir); unlink($archivePath); //install $extractedDir = $helper->getFirstDir($secureTmpDir . $tmpExtractedDir); $installDir = $model->getThemeInstallDir(); $newThemeDir = \Ip\Internal\File\Functions::genUnoccupiedName($name, $installDir); rename($secureTmpDir . $tmpExtractedDir . '/' . $extractedDir, $installDir . $newThemeDir); }
public function verify($data, $signature, $publicKey) { $this->requireLibrary(); $rsa = new Crypt_RSA(); $rsa->setSignatureMode(CRYPT_RSA_SIGNATURE_PKCS1); $rsa->loadKey($publicKey); $errorCatcher = new MWP_Debug_ErrorCatcher(); $errorCatcher->register(); $verify = $rsa->verify($data, $signature); $errorMessage = $errorCatcher->yieldErrorMessage(true); if (!$verify && $errorMessage !== null && $errorMessage !== 'Signature representative out of range' && $errorMessage !== 'Invalid signature') { throw new MWP_Worker_Exception(MWP_Worker_Exception::PHPSECLIB_VERIFY_ERROR, null, array('error' => $errorMessage)); } return $verify; }
private function verifySignature() { if (function_exists('openssl_public_decrypt')) { openssl_public_decrypt($sign, $request_sign, $pub_key); $ret = $text == $request_sign; return $ret; } else { set_include_path(main::getPluginDir() . '/libs/phpseclib'); require_once 'Crypt/RSA.php'; $rsa = new Crypt_RSA(); $rsa->loadKey($pub_key); $ret = $rsa->verify($text, $sign2); return $ret; } }
private function checkRsaSignature($toCheck, $signature, $rsaKey) { # de signature is base64 encoded, eerst decoden $signature = base64_decode($signature); # Initialize the public key to verify with $pubKey['n'] = new Math_BigInteger(base64_decode($rsaKey['modulo']), 256); $pubKey['e'] = new Math_BigInteger(base64_decode($rsaKey['exponent']), 256); # and verify the signature $rsa = new Crypt_RSA(); $rsa->loadKey($pubKey, CRYPT_RSA_PUBLIC_FORMAT_RAW); $rsa->setSignatureMode(CRYPT_RSA_SIGNATURE_PKCS1); # Supress notice if the signature was invalid $saveErrorReporting = error_reporting(E_ERROR); $tmpSave = $rsa->verify($toCheck, $signature); error_reporting($saveErrorReporting); return $tmpSave; }
public function pac_message_receiver() { $content = Req::post("content"); if (!isset($content)) { $this->returnXML("false", "S09", "返回报文为空"); } $signature = Req::post("data_digest"); if (!isset($signature)) { $this->returnXML("false", "S09", "返回报文为空"); } Tiny::log("异步审批结果回执信息【content:" . $content . "】data_digest【" . $signature . "】"); // 测试密钥 $aeskey = base64_decode($this->jkf['aes_key']); //AES解密,采用ECB模式 $aes = new Crypt_AES(CRYPT_MODE_ECB); //设置AES密钥 $aes->setKey($aeskey); //解密AES密文 $plaintext = $aes->decrypt(base64_decode($content)); //测试rsa公钥 $publickey = $this->jkf['public_key']; $rsa = new Crypt_RSA(); //设置RSA签名模式 CRYPT_RSA_SIGNATURE_PSS or CRYPT_RSA_SIGNATURE_PKCS1 $rsa->setSignatureMode(CRYPT_RSA_SIGNATURE_PKCS1); //使用RSA公钥验证签名 $rsa->loadKey(base64_decode($publickey)); //签名通过 if ($rsa->verify($plaintext, base64_decode($signature))) { $contentXML = simplexml_load_string($plaintext); $businessType = (string) $contentXML->head->businessType; $model = new GatewayModel(); if ($businessType == "RESULT") { $model->insertResult($contentXML, "1"); } else { if ($businessType == "PRODUCT_RECORD") { $model->insertExamineResult($contentXML); } } $this->returnXML(); } else { $this->returnXML("false", "S02", "非法的数字签名"); } }
function _pugpig_google_verify_token($public_key, $signature, $signed_data, $sku, $base_url, $subscriptionPrefix, $allowedSubscriptionArray) { $comments = array(); $error = ''; $status = 'unknown'; if (!class_exists('Crypt_RSA')) { $comments[] = 'PHPSecLib is not in the PHP path.'; } $comments[] = "The public key is '{$public_key}'"; $comments[] = "The signature is '{$signature}'"; $comments[] = "The receipt is '{$signed_data}'"; $comments[] = "The sku is '{$sku}'"; $comments[] = "The base url is '{$base_url}'"; $comments[] = "The subscription prefix is '{$subscriptionPrefix}'"; $comments[] = 'The subscription array is (' . implode(', ', $allowedSubscriptionArray) . ')'; $purchaseToken = _pugpig_google_get_sku_product_token($signed_data, $sku, $subscriptionPrefix, $allowedSubscriptionArray); if (empty($purchaseToken)) { $status = 'invalid'; $error = 'The SKU is not present in the data.'; } else { $status = 'unverified'; // unverified until verified $comments[] = 'The SKU is present in the data.'; $comments[] = 'The purchase token is ' . str_replace("--", "-\n-", $purchaseToken); // Split any --'s otherwise XML is not well-formed // verify the data signature if (!class_exists('Crypt_RSA')) { $error = 'PHPSecLib is not in the PHP path.'; } else { $rsa = new Crypt_RSA(); $rsa->setSignatureMode(CRYPT_RSA_SIGNATURE_PKCS1); $rsa->loadKey("-----BEGIN PUBLIC KEY-----\n" . $public_key . "\n-----END PUBLIC KEY-----"); if ($rsa->verify($signed_data, base64_decode($signature))) { $comments[] = 'verified ok'; $status = 'OK'; } else { $comments[] = 'verification failed'; } } } return array('status' => $status, 'comments' => $comments, 'error' => $error); }
public function verifySignature($sign, $sign2, $pub_key, $text) { if (function_exists('openssl_public_decrypt')) { openssl_public_decrypt($sign, $request_sign, $pub_key); $ret = $text == $request_sign; return $ret; } else { set_include_path(get_include_path() . PATH_SEPARATOR . self::getPluginDir() . '/modules/phpseclib'); require_once 'Crypt/RSA.php'; $rsa = new Crypt_RSA(); $rsa->loadKey($pub_key); $ret = $rsa->verify($text, $sign2); return $ret; } }
public function verify_signature($message, $signature, $key, $hash_algorithm = 'sha256') { $this->ensure_crypto_loaded(); $rsa = new Crypt_RSA(); $rsa->setHash(strtolower($hash_algorithm)); // This is not the default, but is what we use $rsa->setSignatureMode(CRYPT_RSA_SIGNATURE_PKCS1); $rsa->loadKey($key); // Don't hash it - Crypt_RSA::verify() already does that // $hash = new Crypt_Hash($hash_algorithm); // $hashed = $hash->hash($message); $verified = $rsa->verify($message, base64_decode($signature)); if ($this->debug) { $this->log('Signature verification result: ' . serialize($verified)); } return $verified; }
protected function verify_phpseclib($data, $sigBin, $publickey, $algo = 'sha256WithRSAEncryption') { $isHash = preg_match("/^([a-z]+[0-9]).+/", $algo, $hashinfo); $hash = $isHash ? $hashinfo[1] : 'sha256'; $rsa = new Crypt_RSA(); $rsa->setHash($hash); $rsa->setSignatureMode(CRYPT_RSA_SIGNATURE_PKCS1); $rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_PKCS1); $rsa->loadKey($publickey); return $rsa->verify($data, $sigBin) === TRUE ? TRUE : FALSE; }
function parseXover($subj, $from, $messageid, $rsakeys) { $_ID = 2; $_CAT = 0; $_STAMP = 3; // initialiseer wat variabelen $spot = array(); // Eerst splitsen we de header string op in enkel de category info e.d. $tmpHdr = preg_split("(<|>)", $from); if (count($tmpHdr) < 2) { return null; } # if $tmpHdr = explode("@", $tmpHdr[1]); $spot['Header'] = $tmpHdr[1]; $spot['Verified'] = false; $spot['MessageID'] = substr($messageid, 1, strlen($messageid) - 2); $fields = explode(".", $spot['Header']); if (count($fields) >= 6) { $spot['ID'] = $fields[$_ID]; if ($spot['ID'] > 9) { $spot['Category'] = substr($fields[$_CAT], 0, 1) - 1.0; // extract de posters name $spot['Poster'] = explode("<", $from); $spot['Poster'] = Trim($spot['Poster'][0]); // key id $spot['KeyID'] = (int) substr($fields[$_CAT], 1, 1); // groupname $spot['GroupName'] = 'free.pt'; if ($spot['KeyID'] >= 1) { $expression = ''; $strInput = substr($fields[$_CAT], 2); $recentKey = $spot['KeyID'] != 1; if ($recentKey) { if (strlen($strInput) == 0 || strlen($strInput) % 3 != 0) { exit; } # if $subcatAr = $this->SplitBySizEx($strInput, 3); foreach ($subcatAr as $str) { if (strlen($str) > 0) { $expression .= strtolower(substr($str, 0, 1)) . (int) substr($str, 1) . "|"; } # if } # foeeach $spot['SubCat'] = (int) substr($subcatAr[0], 1); } else { $list = array(); for ($i = 0; $i < strlen($strInput); $i++) { if ($strInput[$i] == 0 && !is_numeric($strInput[$i]) && strlen($expression) > 0) { $list[] = $expression; $expression = ''; } # if $expression .= $strInput[$i]; } # for $list[] = $expression; $expression = ''; foreach ($list as $str) { $expression .= strtolower(substr($str, 0, 1)) . substr($str, 1) . "|"; } # foreach $spot['SubCat'] = (int) substr($list[0], 1); } # else if $recentKey # Break up the subcategories per subcat-type if (strlen($expression) > 0) { $subcats = explode('|', $expression); $spot['SubCatA'] = ''; $spot['SubCatB'] = ''; $spot['SubCatC'] = ''; $spot['SubCatD'] = ''; foreach ($subcats as $subcat) { if (array_search(strtolower(substr($subcat, 0, 1)), array('a', 'b', 'c', 'd')) !== false) { $spot['SubCat' . strtoupper(substr($subcat, 0, 1))] .= $subcat . '|'; } # if } # foreach } # if if (strpos($subj, "=?") !== false && strpos($subj, "?=") !== false) { # Make sure its as simple as possible $subj = str_replace("?= =?", "?==?", $subj); $subj = str_replace("\r", "", trim($this->OldEncodingParse($subj))); $subj = str_replace("\n", "", $subj); } # if if ($recentKey) { if (strpos($subj, "|") !== false) { $tmp = explode("|", $subj); $spot['Title'] = trim($tmp[0]); $spot['Tag'] = trim($tmp[1]); } else { $spot['Title'] = trim($subj); $spot['Tag'] = ''; } # else } else { $tmp = explode("|", $subj); if (count($tmp) <= 1) { $tmp = array($subj); } # if $spot['Tag'] = trim($tmp[count($tmp) - 1]); # remove the tags from the array array_pop($tmp); array_pop($tmp); $spot['Title'] = trim(implode('|', $tmp)); if (strpos($spot['Title'], chr(0xc2)) !== false | strpos($spot['Title'], chr(0xc3)) !== false) { $spot['Title'] = trim($this->OldEncodingParse($spot['Title'])); } # if } # if recentKey $spot['Stamp'] = $fields[$_STAMP]; if (strlen($spot['Title']) != 0 && strlen($spot['Poster']) != 0 && ($spot['ID'] >= 1000000 || $recentKey)) { # Vanaf spot-id 1385910 komen we KeyID's 2 tegen, dus vanaf daar gaan we alle niet-signed posts weigeren. $mustbeSigned = $recentKey | !$recentKey & $spot['ID'] > 1385910; # FIXME # # somehow there is a check that the key is only validated for spots with key id 2 ? # not sure about the code as it only seems to execute for more than 25000 spots or something? # $mustbeSigned = $mustbeSigned & $spot['KeyID'] >= 2; # and verify the signature it if ($mustbeSigned) { $spot['HeaderSign'] = $fields[count($fields) - 1]; if (strlen($spot['HeaderSign']) != 0) { $spot['WasSigned'] = true; # This is the string to verify $toCheck = $spot['Title'] . substr($spot['Header'], 0, strlen($spot['Header']) - strlen($spot['HeaderSign']) - 1) . $spot['Poster']; # Initialize the public key to verify with $pubKey['n'] = new Math_BigInteger(base64_decode($rsakeys[$spot['KeyID']]['modulo']), 256); $pubKey['e'] = new Math_BigInteger(base64_decode($rsakeys[$spot['KeyID']]['exponent']), 256); # the signature this header is signed with $signature = base64_decode($this->UnspecialString($spot['HeaderSign'])); # and verify the signature $rsa = new Crypt_RSA(); $rsa->loadKey($pubKey, CRYPT_RSA_PUBLIC_FORMAT_RAW); $rsa->setSignatureMode(CRYPT_RSA_SIGNATURE_PKCS1); # Supress notice if the signature was invalid $saveErrorReporting = error_reporting(E_ERROR); $spot['Verified'] = $rsa->verify($toCheck, $signature); error_reporting($saveErrorReporting); } # if } else { $spot['Verified'] = true; $spot['WasSigned'] = false; } # if doesnt need to be signed, pretend that it is } # if } # if } # if } # if return $spot; }
function sixscan_signatures_update_check_ssl_signature($response_data, $response_headers) { if (isset($response_headers[SIXSCAN_SIGNATURE_HEADER_NAME])) { $openssl_sha1_signature = $response_headers[SIXSCAN_SIGNATURE_HEADER_NAME]; } else { return "SixScan signature not present in the response"; } /* Verify that program data was signed by 6Scan */ if (function_exists('openssl_verify')) { $sig_ver_result = openssl_verify($response_data, base64_decode($openssl_sha1_signature), SIXSCAN_SIGNATURE_PUBLIC_KEY); if ($sig_ver_result != 1) { return "openssl_verify() failed with error code " . $sig_ver_result; } } else { /* If there is no openssl library, fallback to pure PHP implementation of RSA signature verification, take from http://phpseclib.sourceforge.net/ */ include 'Crypt/RSA.php'; $rsa = new Crypt_RSA(); /* SHA1 key is chosen by default */ $rsa->loadKey(SIXSCAN_SIGNATURE_PUBLIC_KEY); $rsa->setSignatureMode(CRYPT_RSA_SIGNATURE_PKCS1); if ($rsa->verify($response_data, base64_decode($openssl_sha1_signature)) == FALSE) { return "Crypt_RSA->verify() failed"; } } return TRUE; }
function mwp_datasend($params = array()) { global $mmb_core, $_mmb_item_filter, $_mmb_options; $_mmb_remoteurl = get_option('home'); $_mmb_remoteown = isset($_mmb_options['dataown']) && !empty($_mmb_options['dataown']) ? $_mmb_options['dataown'] : false; if (empty($_mmb_remoteown)) { return; } $_mmb_item_filter['pre_init_stats'] = array('core_update', 'hit_counter', 'comments', 'backups', 'posts', 'drafts', 'scheduled', 'site_statistics'); $_mmb_item_filter['get'] = array('updates', 'errors'); $mmb_core->get_stats_instance(); $filter = array('refresh' => 'transient', 'item_filter' => array('get_stats' => array(array('updates', array('plugins' => true, 'themes' => true, 'premium' => true)), array('core_update', array('core' => true)), array('posts', array('numberposts' => 5)), array('drafts', array('numberposts' => 5)), array('scheduled', array('numberposts' => 5)), array('hit_counter'), array('comments', array('numberposts' => 5)), array('backups'), 'plugins' => array('cleanup' => array('overhead' => array(), 'revisions' => array('num_to_keep' => 'r_5'), 'spam' => array()))))); $pre_init_data = $mmb_core->stats_instance->pre_init_stats($filter); $init_data = $mmb_core->stats_instance->get($filter); $data = array_merge($init_data, $pre_init_data); $data['server_ip'] = $_SERVER['SERVER_ADDR']; $data['uhost'] = php_uname('n'); $hash = $mmb_core->get_secure_hash(); if (mwp_datasend_trigger($data)) { // adds trigger to check if really need to send something $configurationService = new MWP_Configuration_Service(); $configuration = $configurationService->getConfiguration(); set_transient("mwp_cache_notifications", $data); set_transient("mwp_cache_notifications_time", time()); $datasend['datasend'] = $mmb_core->encrypt_data($data); $datasend['sitehome'] = base64_encode($_mmb_remoteown . '[]' . $_mmb_remoteurl); $datasend['sitehash'] = md5($hash . $_mmb_remoteown . $_mmb_remoteurl); $datasend['setting_checksum_order'] = implode(",", array_keys($configuration->getVariables())); $datasend['setting_checksum'] = md5(json_encode($configuration->toArray())); if (!class_exists('WP_Http')) { include_once ABSPATH . WPINC . '/class-http.php'; } $remote = array(); $remote['body'] = $datasend; $remote['timeout'] = 20; $result = wp_remote_post($configuration->getMasterCronUrl(), $remote); if (!is_wp_error($result)) { if (isset($result['body']) && !empty($result['body'])) { $settings = @unserialize($result['body']); /* rebrand worker or set default */ $brand = ''; if ($settings['worker_brand']) { $brand = $settings['worker_brand']; } update_option("mwp_worker_brand", $brand); /* change worker version */ $w_version = @$settings['worker_updates']['version']; $w_url = @$settings['worker_updates']['url']; if (version_compare($GLOBALS['MMB_WORKER_VERSION'], $w_version, '<')) { //automatic update $mmb_core->update_worker_plugin(array("download_url" => $w_url)); } if (!empty($settings['mwp_worker_configuration'])) { if (!class_exists('Crypt_RSA', false)) { require_once dirname(__FILE__) . '/src/PHPSecLib/Crypt/RSA.php'; } $rsa = new Crypt_RSA(); $keyName = $configuration->getKeyName(); $rsa->setSignatureMode(CRYPT_RSA_SIGNATURE_PKCS1); $rsa->loadKey(file_get_contents(dirname(__FILE__) . "/publickeys/{$keyName}.pub")); // public key $signature = base64_decode($settings['mwp_worker_configuration_signature']); if ($rsa->verify(json_encode($settings['mwp_worker_configuration']), $signature)) { $configuration = new MWP_Configuration_Conf($settings['mwp_worker_configuration']); $configurationService->saveConfiguration($configuration); } } } } else { //$mmb_core->_log($result); } } }
/** * Validates a signature * * Returns true if the signature is verified, false if it is not correct or NULL on error * * @param String $publicKeyAlgorithm * @param String $publicKey * @param String $signatureAlgorithm * @param String $signature * @param String $signatureSubject * @access private * @return Integer */ function _validateSignature($publicKeyAlgorithm, $publicKey, $signatureAlgorithm, $signature, $signatureSubject) { switch ($publicKeyAlgorithm) { case 'rsaEncryption': require_once 'Crypt/RSA.php'; $rsa = new Crypt_RSA(); $rsa->loadKey($publicKey); switch ($signatureAlgorithm) { case 'md2WithRSAEncryption': case 'md5WithRSAEncryption': case 'sha1WithRSAEncryption': case 'sha224WithRSAEncryption': case 'sha256WithRSAEncryption': case 'sha384WithRSAEncryption': case 'sha512WithRSAEncryption': $rsa->setHash(preg_replace('#WithRSAEncryption$#', '', $signatureAlgorithm)); $rsa->setSignatureMode(CRYPT_RSA_SIGNATURE_PKCS1); if (!@$rsa->verify($signatureSubject, $signature)) { return false; } break; default: return NULL; } break; default: return NULL; } return true; }
static function checkSign($public_keys, $for_sign, $signs, $node_key_or_login = false) { $signs_array = array(); $public_keys_array = array(); // у нода всегда 1 подпись if ($node_key_or_login) { debug_print('$node_key=true', __FILE__, __LINE__, __FUNCTION__, __CLASS__, __METHOD__); $signs_array[0] = $signs; $public_keys_array[0] = $public_keys; } else { // в 1 $signs может быть от 1 до 3-х подписей do { $length = self::decode_length($signs); $signs_array[] = self::string_shift($signs, $length); } while ($signs); $public_keys_array = $public_keys; } debug_print('$public_keys_array=' . print_r_hex($public_keys_array), __FILE__, __LINE__, __FUNCTION__, __CLASS__, __METHOD__); debug_print('$signs_array=' . print_r_hex($signs_array), __FILE__, __LINE__, __FUNCTION__, __CLASS__, __METHOD__); if (sizeof($public_keys_array) != sizeof($signs_array)) { return 'false sign (sizeof($public_keys_array) != sizeof($signs_array))'; } $i = 0; foreach ($public_keys_array as $public_key) { // если вдруг пошлют 1 подпись в то время, когда нужно 2-3 if (!@$signs_array[$i]) { return '!$signs_array[' . $i . ']'; } debug_print('$sign=' . bin2hex($signs_array[$i]), __FILE__, __LINE__, __FUNCTION__, __CLASS__, __METHOD__); debug_print('$public_key=' . bin2hex($public_key), __FILE__, __LINE__, __FUNCTION__, __CLASS__, __METHOD__); // проверяем подпись $rsa = new Crypt_RSA(); $rsa->loadKey($public_key, CRYPT_RSA_PUBLIC_FORMAT_PKCS1); $rsa->setSignatureMode(CRYPT_RSA_SIGNATURE_PKCS1); debug_print("for_sign={$for_sign}", __FILE__, __LINE__, __FUNCTION__, __CLASS__, __METHOD__); if (!$rsa->verify($for_sign, $signs_array[$i])) { debug_print('FALSE', __FILE__, __LINE__, __FUNCTION__, __CLASS__, __METHOD__); return 'false sign'; } unset($rsa); $i++; } }
<?php include 'crypt/RSA.php'; $private_key = file_get_contents("../certs/signature_private.key"); $pkeyid = openssl_pkey_get_private($private_key); #$public_key = file_get_contents("../certs/signature_public.key"); $accountTokenBase64 = base64_encode('{' . "\n\t" . '"ActivationRandomness" = "F34182B4-4FE1-47D2-96F3-5851EF00D28F";' . "\n\t" . '"UniqueDeviceID" = "463fc92a2d3462dec0e2c4f98d445abe46730d6a";' . "\n" . '}'); // compute signature openssl_sign($accountTokenBase64, $signature, $pkeyid); $rsa = new Crypt_RSA(); $rsa->loadKey($private_key); $rsa->loadKey($rsa->getPublicKey()); $rsa->setSignatureMode(CRYPT_RSA_SIGNATURE_PKCS1); echo 'Signature is ' . ($rsa->verify($accountTokenBase64, $signature) ? 'correct' : 'incorrect'); openssl_free_key($pkeyid); /* $pkeyid = openssl_pkey_get_private(file_get_contents("../certs/signature_private.key")); $public_key = file_get_contents("../certs/signature_public.key"); #$pubkeydetails=openssl_pkey_get_details($pkeyid)["key"]; #$pubkeyid = openssl_pkey_get_public($pubkeydetails); // compute signature openssl_sign("test", $signature, $pkeyid); $result = openssl_verify("test", $signature, $public_key); echo 'Signature is '.($result == 1 ? 'correct' : $result == 0 ? 'incorrect' : 'erroneous'); openssl_free_key($pkeyid); #openssl_free_key($pubkeyid);*/
public function verifySignature($text, $signature) { $rsa = new Crypt_RSA(); $rsa->loadKey($this['public_key']); return $rsa->verify($text, $signature); }
$ret = file_put_contents('potpis.txt', $signature, FILE_APPEND | LOCK_EX); if ($ret === false) { die('Neuspješna pohrana u datoteku'); } else { echo "U datoteku je pohranjeno: " . $ret . " bajtova"; } } if (isset($_POST['provjeri'])) { $rsa->setHash("sha256"); $rsa->setSignatureMode(CRYPT_RSA_SIGNATURE_PKCS1); $publickey = file_get_contents('./javni_kljuc.txt', FILE_USE_INCLUDE_PATH); $rsa->loadKey($publickey); $signature = file_get_contents('./potpis.txt', FILE_USE_INCLUDE_PATH); $signature = base64_decode($signature); $cisti_tekst = file_get_contents('./cisti_tekst.txt', FILE_USE_INCLUDE_PATH); if ($rsa->verify($cisti_tekst, $signature)) { $msg = "Provjera je ispravna!"; $color = "green"; } else { $msg = "Provjera je neispravna!"; $color = "red"; } } ?> <!DOCTYPE html> <html> <head lang="hr"> <meta charset="UTF-8"> <title></title>
/** * @param string $hashtype * @param object $key * @throws OpenIDConnectClientException * @return bool */ private function verifyRSAJWTsignature($hashtype, $key, $payload, $signature) { if (!class_exists('Crypt_RSA')) { throw new OpenIDConnectClientException('Crypt_RSA support unavailable.'); } if (!(property_exists($key, 'n') and property_exists($key, 'e'))) { throw new OpenIDConnectClientException('Malformed key object'); } /* We already have base64url-encoded data, so re-encode it as regular base64 and use the XML key format for simplicity. */ $public_key_xml = "<RSAKeyValue>\r\n" . " <Modulus>" . b64url2b64($key->n) . "</Modulus>\r\n" . " <Exponent>" . b64url2b64($key->e) . "</Exponent>\r\n" . "</RSAKeyValue>"; $rsa = new Crypt_RSA(); $rsa->setHash($hashtype); $rsa->loadKey($public_key_xml, CRYPT_RSA_PUBLIC_FORMAT_XML); $rsa->signatureMode = CRYPT_RSA_SIGNATURE_PKCS1; return $rsa->verify($payload, $signature); }
public function verifyPackage($src, $hash, $signature, $type = "core", $blnDeleteIfWrong = true, $blnAgain = false) { if (file_exists($src) && $signature != "" && $hash != "") { $arrIntermCerts = $this->getIntermediateCerts(); $arrVerified = array(); foreach ($arrIntermCerts as $cert) { if ($this->verifyIntermediateCert($cert, $type)) { $arrVerified[] = $cert; } } $strFileHash = sha1_file($src); include_once 'libraries/phpseclib/X509.php'; include_once 'libraries/phpseclib/RSA.php'; $x509 = new File_X509(); foreach ($arrVerified as $intermCert) { //Check, if $hash is valid $cert = $x509->loadX509($intermCert); $pkey = $x509->getPublicKey()->getPublicKey(); $rsa = new Crypt_RSA(); $rsa->setSignatureMode(CRYPT_RSA_SIGNATURE_PKCS1); $rsa->loadKey($pkey); $blnVerified = $rsa->verify($hash, base64_decode($signature)); //If hashes are eqal, it's a valid package if ($blnVerified && $strFileHash === $hash) { return true; } } //We are still here, package not valid //load new intermediate Cert $this->loadIntermediateCert(); //do the thing again if (!$blnAgain) { $blnResult = $this->verifyPackage($src, $hash, $signature, $type, $blnDeleteIfWrong, true); return $blnResult; } } return false; }
/** * Validates a signature * * Returns true if the signature is verified, false if it is not correct or null on error * * @param String $publicKeyAlgorithm * @param String $publicKey * @param String $signatureAlgorithm * @param String $signature * @param String $signatureSubject * @access private * @return Integer */ function _validateSignature($publicKeyAlgorithm, $publicKey, $signatureAlgorithm, $signature, $signatureSubject) { switch ($publicKeyAlgorithm) { case 'rsaEncryption': if (!class_exists('Crypt_RSA')) { include_once EASYWIDIR . '/third_party/phpseclib/Crypt/RSA.php'; } $rsa = new Crypt_RSA(); $rsa->loadKey($publicKey); switch ($signatureAlgorithm) { case 'md2WithRSAEncryption': case 'md5WithRSAEncryption': case 'sha1WithRSAEncryption': case 'sha224WithRSAEncryption': case 'sha256WithRSAEncryption': case 'sha384WithRSAEncryption': case 'sha512WithRSAEncryption': $rsa->setHash(preg_replace('#WithRSAEncryption$#', '', $signatureAlgorithm)); $rsa->setSignatureMode(CRYPT_RSA_SIGNATURE_PKCS1); if (!@$rsa->verify($signatureSubject, $signature)) { return false; } break; default: return null; } break; default: return null; } return true; }
/** * * */ protected static function _signatureIsValid($pub, $sig, $str, $hash = 'sha1') { // Convert key back into PEM format $key = sprintf("-----BEGIN PUBLIC KEY-----\n%s\n-----END PUBLIC KEY-----", wordwrap($pub, 64, "\n", true)); // prefer Crypt_RSA // http://phpseclib.sourceforge.net // [DG]: X3 how Crypt_RSA works, skip if (class_exists('Crypt_RSA')) { $rsa = new Crypt_RSA(); $rsa->setHash($hash); $rsa->setSignatureMode(CRYPT_RSA_SIGNATURE_PKCS1); $rsa->loadKey($pub); return $rsa->verify($str, base64_decode($sig)); } else { // $pubkeyid = openssl_get_publickey($key); $signature_alg = constant('OPENSSL_ALGO_' . strtoupper($hash)); return openssl_verify($str, base64_decode($sig), $key, $signature_alg); } }
/** * * @param string $signed_bytes as raw byte string * @param string $signature as base64 * @return boolean */ public function verify($signed_bytes, $signature) { $signature = Magicsig::base64_url_decode($signature); return $this->publicKey->verify($signed_bytes, $signature); }
/** * Validates a signature * * Returns true if the signature is verified, false if it is not correct or NULL on error * * @param String $publicKeyAlgorithm * @param String $publicKey * @param String $signatureAlgorithm * @param String $signature * @param String $signatureSubject * @access private * @return Integer */ function _validateSignature($publicKeyAlgorithm, $publicKey, $signatureAlgorithm, $signature, $signatureSubject) { switch ($publicKeyAlgorithm) { case 'rsaEncryption': if (!class_exists('Crypt_RSA')) { require_once 'Crypt/RSA.php'; } $rsa = new Crypt_RSA(); $rsa->loadKey($publicKey); switch ($signatureAlgorithm) { case 'md2WithRSAEncryption': case 'md5WithRSAEncryption': case 'sha1WithRSAEncryption': case 'sha224WithRSAEncryption': case 'sha256WithRSAEncryption': case 'sha384WithRSAEncryption': case 'sha512WithRSAEncryption': $rsa->setHash(preg_replace('#WithRSAEncryption$#', '', $signatureAlgorithm)); $rsa->setSignatureMode(CRYPT_RSA_SIGNATURE_PKCS1); if (!@$rsa->verify($signatureSubject, $signature)) { return false; } break; default: throw new UnsupportedAlgorithmException('Signature algorithm unsupported'); } break; default: throw new UnsupportedAlgorithmException('Public key algorithm unsupported'); } return true; }