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)); }
public function createPrivateKey($sslCnfPath) { $rsa = new Crypt_RSA(); $rsa->setSignatureMode(CRYPT_RSA_SIGNATURE_PKCS1); $keyPair = $rsa->createKey(); return array('public' => $keyPair['publickey'], 'private' => $keyPair['privatekey']); }
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); }
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 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); }
function descriptografar($texto) { $rsa = new Crypt_RSA(); $rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_PKCS1); $rsa->setSignatureMode(CRYPT_RSA_SIGNATURE_PKCS1); $rsa->loadKey(file_get_contents('key/rsa_private.pem')); return $rsa->decrypt(base64_decode($texto)); }
public function createPrivateKey($sslCnfPath) { $rsa = new Crypt_RSA(); $rsa->setSignatureMode(CRYPT_RSA_SIGNATURE_PKCS1); $opensslPrivKey = openssl_pkey_new(array('private_key_bits' => 1024, 'config' => $sslCnfPath)); openssl_pkey_export($opensslPrivKey, $privateKey, null, array('config' => $sslCnfPath)); $publicKey = openssl_pkey_get_details($opensslPrivKey); $publicKey = $publicKey['key']; openssl_free_key($opensslPrivKey); return array('public' => $publicKey, 'private' => $privateKey); }
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; }
function activateKeyGen($key, $hwid, $privKey, $offline = false) { $rsa = new Crypt_RSA(); $rsa->loadKey($privKey); $rsa->setSignatureMode(CRYPT_RSA_SIGNATURE_PKCS1); $rsa->setHash('sha512'); $activateKey = $rsa->sign(sha1(base64_decode($key) . hash('sha512', $hwid, true))); if ($offline) { $license = '------BEGIN ACTIVATION KEY------' . "\r\n"; $license .= chunk_split(base64_encode($activateKey)); $license .= '------END ACTIVATION KEY------'; } else { $license = base64_encode($activateKey); } return $license; }
private function rsa($public_or_private_key, $padding_mode) { if ($public_or_private_key instanceof JOSE_JWK) { $rsa = $public_or_private_key->toKey(); } else { if ($public_or_private_key instanceof Crypt_RSA) { $rsa = $public_or_private_key; } else { $rsa = new Crypt_RSA(); $rsa->loadKey($public_or_private_key); } } $rsa->setHash($this->digest()); $rsa->setMGFHash($this->digest()); $rsa->setSignatureMode($padding_mode); return $rsa; }
public static function CreateLicense($licensee, $type) { // Gleiche Generalisierung wie am Client: $licenseeGen = self::GeneralizeDataString($licensee); $dataStr = $licenseeGen . (int) $type; // "ERIKAMUSTERMANN2" $rsa = new Crypt_RSA(); // Neue RSA-Klasse erstellen // Setzen der RSA-Optionen auf die, die auch am Client verwendet werden: $rsa->setPrivateKeyFormat(CRYPT_RSA_PRIVATE_FORMAT_XML); $rsa->setHash('SHA1'); $rsa->setSignatureMode(CRYPT_RSA_SIGNATURE_PKCS1); // privaten Schlüssel laden $rsa->loadKey(self::privateKey); // Erstellen der Signatur $signature = $rsa->sign($dataStr); // Formatierte Lizenzdaten zurückgeben return self::FormatLicense($licensee, $type, $signature); }
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 signMessage($privatekey, $message) { /** * Test code: * * $rsa->setSignatureMode(CRYPT_RSA_SIGNATURE_PKCS1); * extract($rsa->createKey()); * $spotSigning = new SpotSigning(); * $x = $spotSigning->signMessage($privatekey, 'testmessage'); * var_dump($x); * var_dump($spotSigning->checkRsaSignature('testmessage', $x['signature'], $x['publickey'])); * */ $rsa = new Crypt_RSA(); $rsa->setSignatureMode(CRYPT_RSA_SIGNATURE_PKCS1); $rsa->loadKey($privatekey); # extract de public key $signature = $rsa->sign($message); $publickey = $rsa->getPublicKey(CRYPT_RSA_PUBLIC_FORMAT_RAW); return array('signature' => base64_encode($signature), 'publickey' => array('modulo' => base64_encode($publickey['n']->toBytes()), 'exponent' => base64_encode($publickey['e']->toBytes())), 'message' => $message); }
public function rsa($hashAlg, $key) { $rsa = new Crypt_RSA(); $rsa->loadKey($key); $rsa->setHash($hashAlg); $rsa->setSignatureMode(CRYPT_RSA_SIGNATURE_PKCS1); return $rsa; }
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; }
/** * @param $rsaKey * @return \Crypt_RSA */ private function getSignor($rsaKey, $password = null) { $crypt = new \Crypt_RSA(); $crypt->loadKey($rsaKey); $crypt->setPassword($password); $crypt->setHash('sha256'); $crypt->setSignatureMode(CRYPT_RSA_SIGNATURE_PKCS1); return $crypt; }
function encrypt_and_sign($pass, $encrypt_private_key, $data_for_sign) { debug_print("pass={$pass}", __FILE__, __LINE__, __FUNCTION__, __CLASS__, __METHOD__); debug_print("encrypt_private_key={$encrypt_private_key}", __FILE__, __LINE__, __FUNCTION__, __CLASS__, __METHOD__); debug_print("data_for_sign={$data_for_sign}", __FILE__, __LINE__, __FUNCTION__, __CLASS__, __METHOD__); if ($pass !== '') { debug_print("pass exists", __FILE__, __LINE__, __FUNCTION__, __CLASS__, __METHOD__); $aes = new Crypt_AES(CRYPT_AES_MODE_ECB); $aes = new Crypt_AES(CRYPT_AES_MODE_ECB); $aes->setKey(md5($pass)); $user_private_key = $aes->decrypt($encrypt_private_key); unset($aes); } else { $user_private_key = $encrypt_private_key; } debug_print("user_private_key=" . $user_private_key, __FILE__, __LINE__, __FUNCTION__, __CLASS__, __METHOD__); $rsa = new Crypt_RSA(); $rsa->loadKey($user_private_key); $rsa->setSignatureMode(CRYPT_RSA_SIGNATURE_PKCS1); $signature = $rsa->sign($data_for_sign); unset($rsa); debug_print("signature=" . $signature, __FILE__, __LINE__, __FUNCTION__, __CLASS__, __METHOD__); return $signature; }
public function checkRsaSignature($toCheck, $signature, $rsaKey) { # 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; } # checkRsaSignature
/** * Quasi-private - marked public to work-around PHP 5.3 compat. * * @param string $key * @param string $type * 'public' or 'private' * @return \Crypt_RSA */ public static function getRsa($key, $type) { $rsa = new \Crypt_RSA(); $rsa->loadKey($key); if ($type == 'public') { $rsa->setPublicKey(); } $rsa->setEncryptionMode(Constants::RSA_ENC_MODE); $rsa->setSignatureMode(Constants::RSA_SIG_MODE); $rsa->setHash(Constants::RSA_HASH); return $rsa; }
function getPublicKey($privateKey) { $rsa = new Crypt_RSA(); $rsa->setSignatureMode(CRYPT_RSA_SIGNATURE_PKCS1); $rsa->loadKey($privateKey); /* * When we load a public key where a private key should * be loaded, this makes sure we can use it after all */ if ($rsa->publicExponent == false) { $rsa->publicExponent = $rsa->exponent; } # if # extract the public key $publicKey = $rsa->getPublicKey(CRYPT_RSA_PUBLIC_FORMAT_RAW); return array('modulo' => base64_encode($publicKey['n']->toBytes()), 'exponent' => base64_encode($publicKey['e']->toBytes())); }
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; }
static function crypt_rsa_key($mod, $exp, $hash = 'SHA256') { $rsa = new Crypt_RSA(); $rsa->setSignatureMode(CRYPT_RSA_SIGNATURE_PKCS1); $rsa->setHash(strtolower($hash)); $rsa->modulus = new Math_BigInteger($mod, 256); $rsa->k = strlen($rsa->modulus->toBytes()); $rsa->exponent = new Math_BigInteger($exp, 256); $rsa->setPublicKey(); return $rsa; }
/** * Sign a message using a private RSA key * * @param string $payload The message to be signed * @param string $private_key An RSA private key * @return string A base64-encoded and url-encoded hash of the $payload_string */ private function signMessage($payload, $private_key) { $signature_urlencoded = ''; $rsa_signature = new \Crypt_RSA(); $rsa_signature->loadKey($private_key); $rsa_signature->setSignatureMode(CRYPT_RSA_SIGNATURE_PKCS1); $rsa_signature->setHash('md5'); $payload_base64 = urldecode(substr($payload, 0, -6)); $signature_binary = $rsa_signature->sign($payload_base64); $signature_base64 = base64_encode($signature_binary); $signature_urlencoded = urlencode($signature_base64) . "decode"; return $signature_urlencoded; }
/** * Fill out $this->privateKey or $this->publicKey with a Crypt_RSA object * representing the give key (as mod/exponent pair). * * @param string $mod base64-encoded * @param string $exp base64-encoded exponent * @param string $type one of 'public' or 'private' */ public function loadKey($mod, $exp, $type = 'public') { $rsa = new Crypt_RSA(); $rsa->setSignatureMode(CRYPT_RSA_SIGNATURE_PKCS1); $rsa->setHash($this->getHash()); $rsa->modulus = new Math_BigInteger(Magicsig::base64_url_decode($mod), 256); $rsa->k = strlen($rsa->modulus->toBytes()); $rsa->exponent = new Math_BigInteger(Magicsig::base64_url_decode($exp), 256); if ($type == 'private') { $this->privateKey = $rsa; } else { $this->publicKey = $rsa; } }
/** * 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; }
/** * 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; }
function getPublicKey($privateKey) { $rsa = new Crypt_RSA(); $rsa->setSignatureMode(CRYPT_RSA_SIGNATURE_PKCS1); $rsa->loadKey($privateKey); # extract de public key $publicKey = $rsa->getPublicKey(CRYPT_RSA_PUBLIC_FORMAT_RAW); return array('publickey' => array('modulo' => base64_encode($publicKey['n']->toBytes()), 'exponent' => base64_encode($publicKey['e']->toBytes()))); }
$mrkl_root = $testBlock->merkle_tree_root($mrkl_array); $mrkl_root_binary = pack("H*", $mrkl_root); /* Заголовок TYPE (0-блок, 1-тр-я) FF (256) BLOCK_ID FF FF FF FF (4 294 967 295) TIME FF FF FF FF (4 294 967 295) USER_ID FF FF FF FF FF (1 099 511 627 775) LEVEL FF (256) SIGN от 128 байта до 512 байт. Подпись от TYPE, BLOCK_ID, PREV_BLOCK_HASH, TIME, USER_ID, LEVEL, MRKL_ROOT Далее - тело блока (Тр-ии) */ // подписываем нашим нод-ключем заголовок блока $rsa = new Crypt_RSA(); $rsa->loadKey($node_private_key); $rsa->setSignatureMode(CRYPT_RSA_SIGNATURE_PKCS1); //$rsa->setHash('sha256'); $for_sign = "0,{$new_block_id},{$testBlock->prev_block['hash']},{$time},{$my_user_id},{$testBlock->level},{$mrkl_root}"; debug_print('$for_sign=' . $for_sign, __FILE__, __LINE__, __FUNCTION__, __CLASS__, __METHOD__); $signature = $rsa->sign($for_sign); unset($rsa); list(, $signature_hex) = unpack("H*", $signature); debug_print('$signature_hex = ' . $signature_hex, __FILE__, __LINE__, __FUNCTION__, __CLASS__, __METHOD__); // хэш шапки блока. нужен для сравнивания с другими и у кого будет меньше - у того блок круче $header_hash = ParseData::dsha256("{$my_user_id},{$new_block_id},{$prev_head_hash}"); debug_print("header_hash={$header_hash}", __FILE__, __LINE__, __FUNCTION__, __CLASS__, __METHOD__); $data = "{$new_block_id}\t{$time}\t{$testBlock->level}\t{$my_user_id}\t{$header_hash}\t{$signature_hex}\t{$mrkl_root}"; debug_print($data, __FILE__, __LINE__, __FUNCTION__, __CLASS__, __METHOD__); $file = save_tmp_644('FTB', $data); // для тестов получим что там есть $tmp_testblock_data = $db->query(__FILE__, __LINE__, __FUNCTION__, __CLASS__, __METHOD__, "\n\t\t\tSELECT *\n\t\t\tFROM `" . DB_PREFIX . "testblock`\n\t\t\t", 'fetch_array');
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); } } }