• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

PHP MWCryptRand类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了PHP中MWCryptRand的典型用法代码示例。如果您正苦于以下问题:PHP MWCryptRand类的具体用法?PHP MWCryptRand怎么用?PHP MWCryptRand使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了MWCryptRand类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的PHP代码示例。

示例1: memcacheSave

 /**
  * Serialize and save data to memcache
  *
  * Note that it also sets a time to live for the
  * cached version set to self::TTL
  *
  * @param string $cacheKey Cache key
  * @param mixed  $data     Data to send to memcached, will use serialize();
  *
  * @return null
  */
 private function memcacheSave($data)
 {
     $url_friendly_key = MWCryptRand::generateHex(16);
     $key = wfMemcKey($url_friendly_key, 'wpdsso');
     $this->memcache->set($key, json_encode($data), self::TTL);
     return $url_friendly_key;
 }
开发者ID:renoirb,项目名称:mediawiki-fxa-sso,代码行数:18,代码来源:FirefoxAccountsManager.php


示例2: execute

 public function execute()
 {
     $user = $this->getUser();
     $params = $this->extractRequestParams();
     // If we're in JSON callback mode, no tokens can be obtained
     if ($this->lacksSameOriginSecurity()) {
         $this->dieUsage('Cannot obtain a centralauthtoken when using a callback', 'hascallback');
     }
     if ($user->isAnon()) {
         $this->dieUsage('Anonymous users cannot obtain a centralauthtoken', 'notloggedin');
     }
     if (CentralAuthHooks::hasApiToken()) {
         $this->dieUsage('Cannot obtain a centralauthtoken when using centralauthtoken', 'norecursion');
     }
     $centralUser = CentralAuthUser::getInstance($user);
     if (!$centralUser->exists() || !$centralUser->isAttached()) {
         $this->dieUsage('Cannot obtain a centralauthtoken without an attached global account', 'notattached');
     }
     $data = array('userName' => $user->getName(), 'token' => $centralUser->getAuthToken());
     global $wgMemc;
     $loginToken = MWCryptRand::generateHex(32) . dechex($centralUser->getId());
     $key = CentralAuthUser::memcKey('api-token', $loginToken);
     $wgMemc->add($key, $data, 60);
     $this->getResult()->addValue(null, $this->getModuleName(), array('centralauthtoken' => $loginToken));
 }
开发者ID:NDKilla,项目名称:mediawiki-extensions-CentralAuth,代码行数:25,代码来源:ApiCentralAuthToken.php


示例3: crypt

 public function crypt($password)
 {
     if (count($this->args) == 0) {
         $this->args[] = base64_encode(MWCryptRand::generate(16, true));
     }
     if (function_exists('hash_pbkdf2')) {
         $hash = hash_pbkdf2($this->params['algo'], $password, base64_decode($this->args[0]), (int) $this->params['rounds'], (int) $this->params['length'], true);
         if (!is_string($hash)) {
             throw new PasswordError('Error when hashing password.');
         }
     } else {
         $hashLenHash = hash($this->params['algo'], '', true);
         if (!is_string($hashLenHash)) {
             throw new PasswordError('Error when hashing password.');
         }
         $hashLen = strlen($hashLenHash);
         $blockCount = ceil($this->params['length'] / $hashLen);
         $hash = '';
         $salt = base64_decode($this->args[0]);
         for ($i = 1; $i <= $blockCount; ++$i) {
             $roundTotal = $lastRound = hash_hmac($this->params['algo'], $salt . pack('N', $i), $password, true);
             for ($j = 1; $j < $this->params['rounds']; ++$j) {
                 $lastRound = hash_hmac($this->params['algo'], $lastRound, $password, true);
                 $roundTotal ^= $lastRound;
             }
             $hash .= $roundTotal;
         }
         $hash = substr($hash, 0, $this->params['length']);
     }
     $this->hash = base64_encode($hash);
 }
开发者ID:kynikos,项目名称:archlinux-mediawiki,代码行数:31,代码来源:Pbkdf2Password.php


示例4: lqtThread

 static function lqtThread($parser, $args, $parser, $frame)
 {
     $pout = $parser->getOutput();
     // Prepare information.
     $title = Title::newFromText($args['thread']);
     $thread = null;
     if ($args['thread']) {
         if (is_numeric($args['thread'])) {
             $thread = Threads::withId($args['thread']);
         } elseif ($title) {
             $article = new Article($title, 0);
             $thread = Threads::withRoot($article);
         }
     }
     if (is_null($thread)) {
         return '';
     }
     $data = array('type' => 'thread', 'args' => $args, 'thread' => $thread->id(), 'title' => $thread->title());
     if (!isset($pout->mLqtReplacements)) {
         $pout->mLqtReplacements = array();
     }
     // Generate a token
     $tok = MWCryptRand::generateHex(32);
     $text = '<!--LQT-THREAD-' . $tok . '-->';
     $pout->mLqtReplacements[$text] = $data;
     return $text;
 }
开发者ID:Rikuforever,项目名称:wiki,代码行数:27,代码来源:ParserFunctions.php


示例5: crypt

 public function crypt($plaintext)
 {
     if (count($this->args) == 0) {
         $this->args[] = MWCryptRand::generateHex(8);
     }
     $this->hash = md5($this->args[0] . '-' . md5($plaintext));
 }
开发者ID:MediaWiki-stable,项目名称:1.26.1,代码行数:7,代码来源:MWSaltedPassword.php


示例6: crypt

 public function crypt($plaintext)
 {
     if (count($this->args) == 0) {
         $this->args[] = MWCryptRand::generateHex(8);
     }
     $this->hash = md5($this->args[0] . '-' . md5($plaintext));
     if (!is_string($this->hash) || strlen($this->hash) < 32) {
         throw new PasswordError('Error when hashing password.');
     }
 }
开发者ID:claudinec,项目名称:galan-wiki,代码行数:10,代码来源:MWSaltedPassword.php


示例7: setUp

 protected function setUp()
 {
     // Needs to be before setup since this gets cached
     $this->mergeMwGlobalArrayValue('wgGroupPermissions', array('sysop' => array('deleterevision' => true)));
     parent::setUp();
     // Make a few edits for us to play with
     for ($i = 1; $i <= 5; $i++) {
         self::editPage(self::$page, MWCryptRand::generateHex(10), 'summary');
         $this->revs[] = Title::newFromText(self::$page)->getLatestRevID(Title::GAID_FOR_UPDATE);
     }
 }
开发者ID:MediaWiki-stable,项目名称:1.26.1,代码行数:11,代码来源:ApiRevisionDeleteTest.php


示例8: getPreloadId

 protected static function getPreloadId($create_if_not_exists)
 {
     global $wgUser, $wgRequest;
     if (!$wgUser->isAnon()) {
         return ModerationPreload::User_to_PreloadId($wgUser);
     }
     $anon_id = $wgRequest->getSessionData('anon_id');
     if (!$anon_id) {
         if (!$create_if_not_exists) {
             return false;
         }
         $anon_id = MWCryptRand::generateHex(32);
         $wgRequest->setSessionData('anon_id', $anon_id);
     }
     return ModerationPreload::AnonId_to_PreloadId($anon_id);
 }
开发者ID:ATCARES,项目名称:mediawiki-moderation,代码行数:16,代码来源:ModerationPreload.php


示例9: update

 /**
  * Updates the underlying hash by encrypting it with the newest secret.
  *
  * @throws MWException If the configuration is not valid
  * @return bool True if the password was updated
  */
 public function update()
 {
     if (count($this->args) != 2 || $this->params == $this->getDefaultParams()) {
         // Hash does not need updating
         return false;
     }
     // Decrypt the underlying hash
     $underlyingHash = openssl_decrypt(base64_decode($this->args[1]), $this->params['cipher'], $this->config['secrets'][$this->params['secret']], 0, base64_decode($this->args[0]));
     // Reset the params
     $this->params = $this->getDefaultParams();
     // Check the key size with the new params
     $iv = MWCryptRand::generate(openssl_cipher_iv_length($this->params['cipher']), true);
     $this->hash = base64_encode(openssl_encrypt($underlyingHash, $this->params['cipher'], $this->config['secrets'][$this->params['secret']], 0, $iv));
     $this->args = array(base64_encode($iv));
     return true;
 }
开发者ID:jpena88,项目名称:mediawiki-dokku-deploy,代码行数:22,代码来源:EncryptedPassword.php


示例10: crypt

 /**
  * @param string $password Password to encrypt
  *
  * @throws PasswordError If bcrypt has an unknown error
  * @throws MWException If bcrypt is not supported by PHP
  */
 public function crypt($password)
 {
     if (!defined('CRYPT_BLOWFISH')) {
         throw new MWException('Bcrypt is not supported.');
     }
     // Either use existing hash or make a new salt
     // Bcrypt expects 22 characters of base64-encoded salt
     // Note: bcrypt does not use MIME base64. It uses its own base64 without any '=' padding.
     //       It expects a 128 bit salt, so it will ignore anything after the first 128 bits
     if (!isset($this->args[0])) {
         $this->args[] = substr(strtr(base64_encode(MWCryptRand::generate(16, true)), '+', '.'), 0, 22);
     }
     $hash = crypt($password, sprintf('$2y$%02d$%s', (int) $this->params['rounds'], $this->args[0]));
     if (!is_string($hash) || strlen($hash) <= 13) {
         throw new PasswordError('Error when hashing password.');
     }
     // Strip the $2y$
     $parts = explode($this->getDelimiter(), substr($hash, 4));
     $this->params['rounds'] = (int) $parts[0];
     $this->args[0] = substr($parts[1], 0, 22);
     $this->hash = substr($parts[1], 22);
 }
开发者ID:claudinec,项目名称:galan-wiki,代码行数:28,代码来源:BcryptPassword.php


示例11: setSecret

 /**
  * Set a value in the session, encrypted
  *
  * This relies on the secrecy of $wgSecretKey (by default), or $wgSessionSecret.
  *
  * @param string|int $key
  * @param mixed $value
  */
 public function setSecret($key, $value)
 {
     global $wgSessionInsecureSecrets;
     list($encKey, $hmacKey) = $this->getSecretKeys();
     $serialized = serialize($value);
     // The code for encryption (with OpenSSL) and sealing is taken from
     // Chris Steipp's OATHAuthUtils class in Extension::OATHAuth.
     // Encrypt
     // @todo: import a pure-PHP library for AES instead of doing $wgSessionInsecureSecrets
     $iv = \MWCryptRand::generate(16, true);
     if (function_exists('openssl_encrypt')) {
         $ciphertext = openssl_encrypt($serialized, 'aes-256-ctr', $encKey, OPENSSL_RAW_DATA, $iv);
         if ($ciphertext === false) {
             throw new UnexpectedValueException('Encryption failed: ' . openssl_error_string());
         }
     } elseif (function_exists('mcrypt_encrypt')) {
         $ciphertext = mcrypt_encrypt('rijndael-128', $encKey, $serialized, 'ctr', $iv);
         if ($ciphertext === false) {
             throw new UnexpectedValueException('Encryption failed');
         }
     } elseif ($wgSessionInsecureSecrets) {
         $ex = new \Exception('No encryption is available, storing data as plain text');
         $this->logger->warning($ex->getMessage(), ['exception' => $ex]);
         $ciphertext = $serialized;
     } else {
         throw new \BadMethodCallException('Encryption is not available. You really should install the PHP OpenSSL extension, ' . 'or failing that the mcrypt extension. But if you really can\'t and you\'re willing ' . 'to accept insecure storage of sensitive session data, set ' . '$wgSessionInsecureSecrets = true in LocalSettings.php to make this exception go away.');
     }
     // Seal
     $sealed = base64_encode($iv) . '.' . base64_encode($ciphertext);
     $hmac = hash_hmac('sha256', $sealed, $hmacKey, true);
     $encrypted = base64_encode($hmac) . '.' . $sealed;
     // Store
     $this->set($key, $encrypted);
 }
开发者ID:claudinec,项目名称:galan-wiki,代码行数:42,代码来源:Session.php


示例12: confirmationToken

 /**
  * Generate, store, and return a new e-mail confirmation code.
  * A hash (unsalted, since it's used as a key) is stored.
  *
  * @note Call saveSettings() after calling this function to commit
  * this change to the database.
  *
  * @param string &$expiration Accepts the expiration time
  * @return string New token
  */
 protected function confirmationToken(&$expiration)
 {
     global $wgUserEmailConfirmationTokenExpiry;
     $now = time();
     $expires = $now + $wgUserEmailConfirmationTokenExpiry;
     $expiration = wfTimestamp(TS_MW, $expires);
     $this->load();
     $token = MWCryptRand::generateHex(32);
     $hash = md5($token);
     $this->mEmailToken = $hash;
     $this->mEmailTokenExpires = $expiration;
     return $token;
 }
开发者ID:jpena88,项目名称:mediawiki-dokku-deploy,代码行数:23,代码来源:User.php


示例13: singleton

 /**
  * Return a singleton instance of MWCryptRand
  * @return MWCryptRand
  */
 protected static function singleton()
 {
     if (is_null(self::$singleton)) {
         self::$singleton = new self();
     }
     return self::$singleton;
 }
开发者ID:mb720,项目名称:mediawiki,代码行数:11,代码来源:MWCryptRand.php


示例14: newUUIDv4

 /**
  * Return an RFC4122 compliant v4 UUID
  *
  * @param int $flags Bitfield (supports UIDGenerator::QUICK_RAND)
  * @return string
  * @throws MWException
  */
 public static function newUUIDv4($flags = 0)
 {
     $hex = $flags & self::QUICK_RAND ? wfRandomString(31) : MWCryptRand::generateHex(31);
     return sprintf('%s-%s-%s-%s-%s', substr($hex, 0, 8), substr($hex, 8, 4), '4' . substr($hex, 12, 3), dechex(0x8 | hexdec($hex[15]) & 0x3) . $hex[16] . substr($hex, 17, 2), substr($hex, 19, 12));
 }
开发者ID:huatuoorg,项目名称:mediawiki,代码行数:12,代码来源:UIDGenerator.php


示例15: handleReauthBeforeExecute

 /**
  * Handle redirection when the user needs to (re)authenticate.
  *
  * Send the user to the login form if needed; in case the request was a POST, stash in the
  * session and simulate it once the user gets back.
  *
  * @param string $subPage
  * @return bool False if execution should be stopped.
  * @throws ErrorPageError When the user is not allowed to use this page.
  */
 protected function handleReauthBeforeExecute($subPage)
 {
     $authManager = AuthManager::singleton();
     $request = $this->getRequest();
     $key = 'AuthManagerSpecialPage:reauth:' . $this->getName();
     $securityLevel = $this->getLoginSecurityLevel();
     if ($securityLevel) {
         $securityStatus = AuthManager::singleton()->securitySensitiveOperationStatus($securityLevel);
         if ($securityStatus === AuthManager::SEC_REAUTH) {
             $queryParams = array_diff_key($request->getQueryValues(), ['title' => true]);
             if ($request->wasPosted()) {
                 // unique ID in case the same special page is open in multiple browser tabs
                 $uniqueId = MWCryptRand::generateHex(6);
                 $key = $key . ':' . $uniqueId;
                 $queryParams = ['authUniqueId' => $uniqueId] + $queryParams;
                 $authData = array_diff_key($request->getValues(), $this->getPreservedParams(false), ['title' => 1]);
                 $authManager->setAuthenticationSessionData($key, $authData);
             }
             $title = SpecialPage::getTitleFor('Userlogin');
             $url = $title->getFullURL(['returnto' => $this->getFullTitle()->getPrefixedDBkey(), 'returntoquery' => wfArrayToCgi($queryParams), 'force' => $securityLevel], false, PROTO_HTTPS);
             $this->getOutput()->redirect($url);
             return false;
         } elseif ($securityStatus !== AuthManager::SEC_OK) {
             throw new ErrorPageError('cannotauth-not-allowed-title', 'cannotauth-not-allowed');
         }
     }
     $uniqueId = $request->getVal('authUniqueId');
     if ($uniqueId) {
         $key = $key . ':' . $uniqueId;
         $authData = $authManager->getAuthenticationSessionData($key);
         if ($authData) {
             $authManager->removeAuthenticationSessionData($key);
             $this->setRequest($authData, true);
         }
     }
     return true;
 }
开发者ID:claudinec,项目名称:galan-wiki,代码行数:47,代码来源:AuthManagerSpecialPage.php


示例16: generateRandomPasswordString

 /**
  * Generate a random string suitable for a password
  *
  * @param int $minLength Minimum length of password to generate
  * @return string
  */
 public static function generateRandomPasswordString($minLength = 10)
 {
     // Decide the final password length based on our min password length,
     // stopping at a minimum of 10 chars.
     $length = max(10, $minLength);
     // Multiply by 1.25 to get the number of hex characters we need
     // Generate random hex chars
     $hex = MWCryptRand::generateHex(ceil($length * 1.25));
     // Convert from base 16 to base 32 to get a proper password like string
     return substr(Wikimedia\base_convert($hex, 16, 32, $length), -$length);
 }
开发者ID:Acidburn0zzz,项目名称:mediawiki,代码行数:17,代码来源:PasswordFactory.php


示例17: doGenerateKeys

 /**
  * Generate a secret value for variables using our CryptRand generator.
  * Produce a warning if the random source was insecure.
  *
  * @param $keys Array
  * @return Status
  */
 protected function doGenerateKeys($keys)
 {
     $status = Status::newGood();
     $strong = true;
     foreach ($keys as $name => $length) {
         $secretKey = MWCryptRand::generateHex($length, true);
         if (!MWCryptRand::wasStrong()) {
             $strong = false;
         }
         $this->setVar($name, $secretKey);
     }
     if (!$strong) {
         $names = array_keys($keys);
         $names = preg_replace('/^(.*)$/', '\\$$1', $names);
         global $wgLang;
         $status->warning('config-insecure-keys', $wgLang->listToText($names), count($names));
     }
     return $status;
 }
开发者ID:laiello,项目名称:media-wiki-law,代码行数:26,代码来源:Installer.php


示例18: newUUIDv4

	/**
	 * Return an RFC4122 compliant v4 UUID
	 *
	 * @param $flags integer Bitfield (supports UIDGenerator::QUICK_RAND)
	 * @return string
	 * @throws MWException
	 */
	public static function newUUIDv4( $flags = 0 ) {
		$hex = ( $flags & self::QUICK_RAND )
			? wfRandomString( 31 )
			: MWCryptRand::generateHex( 31 );

		return sprintf( '%s-%s-%s-%s-%s',
			// "time_low" (32 bits)
			substr( $hex, 0, 8 ),
			// "time_mid" (16 bits)
			substr( $hex, 8, 4 ),
			// "time_hi_and_version" (16 bits)
			'4' . substr( $hex, 12, 3 ),
			// "clk_seq_hi_res (8 bits, variant is binary 10x) and "clk_seq_low" (8 bits)
			dechex( 0x8 | ( hexdec( $hex[15] ) & 0x3 ) ) . $hex[16] . substr( $hex, 17, 2 ),
			// "node" (48 bits)
			substr( $hex, 19, 12 )
		);
	}
开发者ID:nahoj,项目名称:mediawiki_ynh,代码行数:25,代码来源:UIDGenerator.php


示例19: getSaltUsingCache

 /**
  * MW specific salt, cached from last run
  * @return string Binary string
  */
 protected function getSaltUsingCache()
 {
     if ($this->salt == '') {
         $lastSalt = $this->cache->get($this->cacheKey);
         if ($lastSalt === false) {
             // If we don't have a previous value to use as our salt, we use
             // 16 bytes from MWCryptRand, which will use a small amount of
             // entropy from our pool. Note, "XTR may be deterministic or keyed
             // via an optional “salt value”  (i.e., a non-secret random
             // value)..." - http://eprint.iacr.org/2010/264.pdf. However, we
             // use a strongly random value since we can.
             $lastSalt = MWCryptRand::generate(16);
         }
         // Get a binary string that is hashLen long
         $this->salt = hash($this->algorithm, $lastSalt, true);
     }
     return $this->salt;
 }
开发者ID:whysasse,项目名称:kmwiki,代码行数:22,代码来源:MWCryptHKDF.php


示例20: scratchTitle

 /**
  * @return Title
  */
 function scratchTitle()
 {
     return Title::makeTitle(NS_LQT_THREAD, MWCryptRand::generateHex(32));
 }
开发者ID:Rikuforever,项目名称:wiki,代码行数:7,代码来源:View.php



注:本文中的MWCryptRand类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
PHP MWDebug类代码示例发布时间:2022-05-23
下一篇:
PHP MVCUtils类代码示例发布时间:2022-05-23
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap