本文整理汇总了PHP中OCP\Security\ISecureRandom::generate方法的典型用法代码示例。如果您正苦于以下问题:PHP ISecureRandom::generate方法的具体用法?PHP ISecureRandom::generate怎么用?PHP ISecureRandom::generate使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类OCP\Security\ISecureRandom
的用法示例。
在下文中一共展示了ISecureRandom::generate方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: save
public function save($email)
{
$query = $this->db->prepareQuery('INSERT INTO `*PREFIX*registration`' . ' ( `email`, `token`, `requested` ) VALUES( ?, ?, NOW() )');
$token = $this->random->generate(30);
$query->execute(array($email, $token));
return $token;
}
示例2: createCredentials
/**
* @return DataResponse
*/
public function createCredentials()
{
// Create a new job and store the creation date
$this->jobList->add('OCA\\UpdateNotification\\ResetTokenBackgroundJob');
$this->config->setAppValue('core', 'updater.secret.created', $this->timeFactory->getTime());
// Create a new token
$newToken = $this->secureRandom->generate(64);
$this->config->setSystemValue('updater.secret', password_hash($newToken, PASSWORD_DEFAULT));
return new DataResponse($newToken);
}
示例3: addServer
/**
* add server to the list of trusted ownCloud servers
*
* @param $url
* @return int server id
*/
public function addServer($url)
{
$url = $this->updateProtocol($url);
$result = $this->dbHandler->addServer($url);
if ($result) {
$token = $this->secureRandom->generate(16);
$this->dbHandler->addToken($url, $token);
$this->jobList->add('OCA\\Federation\\BackgroundJob\\RequestSharedSecret', ['url' => $url, 'token' => $token]);
}
return $result;
}
示例4: sendEmail
/**
* @param string $user
* @throws \Exception
*/
protected function sendEmail($user)
{
if (!$this->userManager->userExists($user)) {
throw new \Exception($this->l10n->t('Couldn\'t send reset email. Please make sure your username is correct.'));
}
$userObject = $this->userManager->get($user);
$email = $userObject->getEMailAddress();
if (empty($email)) {
throw new \Exception($this->l10n->t('Could not send reset email because there is no email address for this username. Please contact your administrator.'));
}
$token = $this->secureRandom->generate(21, ISecureRandom::CHAR_DIGITS . ISecureRandom::CHAR_LOWER . ISecureRandom::CHAR_UPPER);
$this->config->setUserValue($user, 'owncloud', 'lostpassword', $this->timeFactory->getTime() . ':' . $token);
$link = $this->urlGenerator->linkToRouteAbsolute('core.lost.resetform', array('userId' => $user, 'token' => $token));
$tmpl = new \OC_Template('core/lostpassword', 'email');
$tmpl->assign('link', $link);
$msg = $tmpl->fetchPage();
try {
$message = $this->mailer->createMessage();
$message->setTo([$email => $user]);
$message->setSubject($this->l10n->t('%s password reset', [$this->defaults->getName()]));
$message->setPlainBody($msg);
$message->setFrom([$this->from => $this->defaults->getName()]);
$this->mailer->send($message);
} catch (\Exception $e) {
throw new \Exception($this->l10n->t('Couldn\'t send reset email. Please contact your administrator.'));
}
}
示例5: generateRandomDeviceToken
/**
* Return a 20 digit device password
*
* Example: ABCDE-FGHIJ-KLMNO-PQRST
*
* @return string
*/
private function generateRandomDeviceToken()
{
$groups = [];
for ($i = 0; $i < 4; $i++) {
$groups[] = $this->random->generate(5, implode('', range('A', 'Z')));
}
return implode('-', $groups);
}
示例6: createShare
/**
* Share a path
*
* @param \OCP\Share\IShare $share
* @return Share The share object
* @throws \Exception
*
* TODO: handle link share permissions or check them
*/
public function createShare(\OCP\Share\IShare $share)
{
if (!$this->canShare($share)) {
throw new \Exception('The Share API is disabled');
}
$this->generalCreateChecks($share);
//Verify share type
if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
$this->userCreateChecks($share);
} else {
if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
$this->groupCreateChecks($share);
} else {
if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
$this->linkCreateChecks($share);
$this->setLinkParent($share);
/*
* For now ignore a set token.
*/
$share->setToken($this->secureRandom->generate(\OC\Share\Constants::TOKEN_LENGTH, \OCP\Security\ISecureRandom::CHAR_LOWER . \OCP\Security\ISecureRandom::CHAR_UPPER . \OCP\Security\ISecureRandom::CHAR_DIGITS));
//Verify the expiration date
$this->validateExpirationDate($share);
//Verify the password
$this->verifyPassword($share->getPassword());
// If a password is set. Hash it!
if ($share->getPassword() !== null) {
$share->setPassword($this->hasher->hash($share->getPassword()));
}
}
}
}
// Verify if there are any issues with the path
$this->pathCreateChecks($share->getNode());
// On creation of a share the owner is always the owner of the path
$share->setShareOwner($share->getNode()->getOwner()->getUID());
// Cannot share with the owner
if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER && $share->getSharedWith() === $share->getShareOwner()) {
throw new \InvalidArgumentException('Can\'t share with the share owner');
}
// Generate the target
$target = $this->config->getSystemValue('share_folder', '/') . '/' . $share->getNode()->getName();
$target = \OC\Files\Filesystem::normalizePath($target);
$share->setTarget($target);
// Pre share hook
$run = true;
$error = '';
$preHookData = ['itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder', 'itemSource' => $share->getNode()->getId(), 'shareType' => $share->getShareType(), 'uidOwner' => $share->getSharedBy(), 'permissions' => $share->getPermissions(), 'fileSource' => $share->getNode()->getId(), 'expiration' => $share->getExpirationDate(), 'token' => $share->getToken(), 'itemTarget' => $share->getTarget(), 'shareWith' => $share->getSharedWith(), 'run' => &$run, 'error' => &$error];
\OC_Hook::emit('OCP\\Share', 'pre_shared', $preHookData);
if ($run === false) {
throw new \Exception($error);
}
$provider = $this->factory->getProviderForType($share->getShareType());
$share = $provider->create($share);
// Post share hook
$postHookData = ['itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder', 'itemSource' => $share->getNode()->getId(), 'shareType' => $share->getShareType(), 'uidOwner' => $share->getSharedBy(), 'permissions' => $share->getPermissions(), 'fileSource' => $share->getNode()->getId(), 'expiration' => $share->getExpirationDate(), 'token' => $share->getToken(), 'id' => $share->getId(), 'shareWith' => $share->getSharedWith(), 'itemTarget' => $share->getTarget(), 'fileTarget' => $share->getTarget()];
\OC_Hook::emit('OCP\\Share', 'post_shared', $postHookData);
return $share;
}
示例7: getId
/**
* Returns an ID for the request, value is not guaranteed to be unique and is mostly meant for logging
* If `mod_unique_id` is installed this value will be taken.
* @return string
*/
public function getId()
{
if (isset($this->server['UNIQUE_ID'])) {
return $this->server['UNIQUE_ID'];
}
if (empty($this->requestId)) {
$this->requestId = $this->secureRandom->generate(20);
}
return $this->requestId;
}
示例8: __construct
/**
* @param IConfig $config
* @param ICrypto $crypto
* @param ISecureRandom $random
* @param IRequest $request
*/
public function __construct(IConfig $config, ICrypto $crypto, ISecureRandom $random, IRequest $request)
{
$this->crypto = $crypto;
$this->config = $config;
$this->random = $random;
if (!is_null($request->getCookie(self::COOKIE_NAME))) {
$this->passphrase = $request->getCookie(self::COOKIE_NAME);
} else {
$this->passphrase = $this->random->generate(128);
$secureCookie = $request->getServerProtocol() === 'https';
// FIXME: Required for CI
if (!defined('PHPUNIT_RUN')) {
$webRoot = \OC::$WEBROOT;
if ($webRoot === '') {
$webRoot = '/';
}
setcookie(self::COOKIE_NAME, $this->passphrase, 0, $webRoot, '', $secureCookie, true);
}
}
}
示例9: encrypt
/**
* Encrypts a value and adds an HMAC (Encrypt-Then-MAC)
* @param string $plaintext
* @param string $password Password to encrypt, if not specified the secret from config.php will be taken
* @return string Authenticated ciphertext
*/
public function encrypt($plaintext, $password = '')
{
if ($password === '') {
$password = $this->config->getSystemValue('secret');
}
$this->cipher->setPassword($password);
$iv = $this->random->generate($this->ivLength);
$this->cipher->setIV($iv);
$ciphertext = bin2hex($this->cipher->encrypt($plaintext));
$hmac = bin2hex($this->calculateHMAC($ciphertext . $iv, $password));
return $ciphertext . '|' . $iv . '|' . $hmac;
}
示例10: feed
/**
* @NoAdminRequired
*
* @param string $enable 'true' if the feed is enabled
* @return DataResponse
*/
public function feed($enable)
{
$token = $tokenUrl = '';
if ($enable === 'true') {
$conflicts = true;
// Check for collisions
while (!empty($conflicts)) {
$token = $this->random->generate(30);
$conflicts = $this->config->getUsersForUserValue('activity', 'rsstoken', $token);
}
$tokenUrl = $this->urlGenerator->linkToRouteAbsolute('activity.Feed.show', ['token' => $token]);
}
$this->config->setUserValue($this->user, 'activity', 'rsstoken', $token);
return new DataResponse(array('data' => array('message' => (string) $this->l10n->t('Your settings have been updated.'), 'rsslink' => $tokenUrl)));
}
示例11: getSharedSecret
/**
* create shared secret and return it
*
* @return \OC_OCS_Result
*/
public function getSharedSecret()
{
$url = $this->request->getParam('url');
$token = $this->request->getParam('token');
if ($this->trustedServers->isTrustedServer($url) === false) {
$this->logger->log(\OCP\Util::ERROR, 'remote server not trusted (' . $url . ') while getting shared secret');
return new \OC_OCS_Result(null, HTTP::STATUS_FORBIDDEN);
}
if ($this->isValidToken($url, $token) === false) {
$this->logger->log(\OCP\Util::ERROR, 'remote server (' . $url . ') didn\'t send a valid token (got ' . $token . ') while getting shared secret');
return new \OC_OCS_Result(null, HTTP::STATUS_FORBIDDEN);
}
$sharedSecret = $this->secureRandom->generate(32);
$this->trustedServers->addSharedSecret($url, $sharedSecret);
// reset token after the exchange of the shared secret was successful
$this->dbHandler->addToken($url, '');
return new \OC_OCS_Result(['sharedSecret' => $sharedSecret], Http::STATUS_OK);
}
示例12: renameTableSchema
/**
* @param \Doctrine\DBAL\Schema\Table $table
* @param string $newName
* @return \Doctrine\DBAL\Schema\Table
*/
protected function renameTableSchema(Table $table, $newName)
{
/**
* @var \Doctrine\DBAL\Schema\Index[] $indexes
*/
$indexes = $table->getIndexes();
$newIndexes = array();
foreach ($indexes as $index) {
if ($index->isPrimary()) {
// do not rename primary key
$indexName = $index->getName();
} else {
// avoid conflicts in index names
$indexName = $this->config->getSystemValue('dbtableprefix', 'oc_') . $this->random->generate(13, ISecureRandom::CHAR_LOWER);
}
$newIndexes[] = new Index($indexName, $index->getColumns(), $index->isUnique(), $index->isPrimary());
}
// foreign keys are not supported so we just set it to an empty array
return new Table($newName, $table->getColumns(), $newIndexes, array(), 0, $table->getOptions());
}
示例13: generateToken
/**
* Generate a new access token clients can authenticate with
*
* @PublicPage
* @NoCSRFRequired
*
* @param string $user
* @param string $password
* @param string $name the name of the client
* @return JSONResponse
*/
public function generateToken($user, $password, $name = 'unknown client')
{
if (is_null($user) || is_null($password)) {
$response = new JSONResponse();
$response->setStatus(Http::STATUS_UNPROCESSABLE_ENTITY);
return $response;
}
$loginName = $user;
$user = $this->userManager->checkPassword($loginName, $password);
if ($user === false) {
$response = new JSONResponse();
$response->setStatus(Http::STATUS_UNAUTHORIZED);
return $response;
}
if ($this->twoFactorAuthManager->isTwoFactorAuthenticated($user)) {
$resp = new JSONResponse();
$resp->setStatus(Http::STATUS_UNAUTHORIZED);
return $resp;
}
$token = $this->secureRandom->generate(128);
$this->tokenProvider->generateToken($token, $user->getUID(), $loginName, $password, $name, IToken::PERMANENT_TOKEN);
return ['token' => $token];
}
示例14: generateToken
/**
* Generate a new CSRF token.
*
* @param int $length Length of the token in characters.
* @return string
*/
public function generateToken($length = 32)
{
return $this->random->generate($length);
}
示例15: generateOneTimePassword
/**
* generate one time password for the user and store it in a array
*
* @param string $uid
* @return string password
*/
protected function generateOneTimePassword($uid)
{
$password = $this->secureRandom->generate(8);
$this->userPasswords[$uid] = $password;
return $password;
}