本文整理汇总了PHP中SimpleSAML_Utilities::generateRandomBytes方法的典型用法代码示例。如果您正苦于以下问题:PHP SimpleSAML_Utilities::generateRandomBytes方法的具体用法?PHP SimpleSAML_Utilities::generateRandomBytes怎么用?PHP SimpleSAML_Utilities::generateRandomBytes使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类SimpleSAML_Utilities
的用法示例。
在下文中一共展示了SimpleSAML_Utilities::generateRandomBytes方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: __construct
/**
* Construct
*
* @param array $authSourceconfig Configuration array for the selected authsource
* @param array $writeConfig Configuration array for the selected catalogue backend
* @param array $attributes The user attributes to be saved
*/
public function __construct($authSourceConfig, $writeConfig, $attributes, $hashAlgo)
{
$asc = SimpleSAML_Configuration::loadFromArray($authSourceConfig);
try {
$this->dbh = new PDO($asc->getString('dsn'), $asc->getString('username'), $asc->getString('password'));
} catch (PDOException $e) {
throw new Exception($e->getMessage());
}
$driver = explode(':', $asc->getString('dsn'), 2);
$driver = strtolower($driver[0]);
/* Driver specific initialization. */
switch ($driver) {
case 'mysql':
/* Use UTF-8. */
$this->dbh->exec("SET NAMES utf8");
$this->dbh->exec("SET CHARACTER SET utf8;");
break;
case 'pgsql':
/* Use UTF-8. */
$this->dbh->exec("SET NAMES 'UTF8'");
break;
}
$this->dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
$this->attributes = $attributes;
$this->hashAlgo = $hashAlgo;
$this->salt = bin2hex(SimpleSAML_Utilities::generateRandomBytes(64, FALSE));
$wc = SimpleSAML_Configuration::loadFromArray($writeConfig);
$this->userIdAttr = $wc->getString('user.id.param');
}
示例2: __construct
protected function __construct()
{
/* Call the parent constructor in case it should become
* necessary in the future.
*/
parent::__construct();
/* Initialize the php session handling.
*
* If session_id() returns a blank string, then we need
* to call session start. Otherwise the session is already
* started, and we should avoid calling session_start().
*/
if (session_id() === '') {
$config = SimpleSAML_Configuration::getInstance();
$cookiepath = $config->getBoolean('session.phpsession.limitedpath', FALSE) ? '/' . $config->getBaseURL() : '/';
session_set_cookie_params(0, $cookiepath, NULL, SimpleSAML_Utilities::isHTTPS());
$cookiename = $config->getString('session.phpsession.cookiename', NULL);
if (!empty($cookiename)) {
session_name($cookiename);
}
$savepath = $config->getString('session.phpsession.savepath', NULL);
if (!empty($savepath)) {
session_save_path($savepath);
}
if (!array_key_exists(session_name(), $_COOKIE)) {
/* Session cookie unset - session id not set. Generate new (secure) session id. */
session_id(SimpleSAML_Utilities::stringToHex(SimpleSAML_Utilities::generateRandomBytes(16)));
}
session_start();
}
}
示例3: getRedirectURL
/**
* Create the redirect URL for a message.
*
* @param SAML2_Message $message The message.
* @return string The URL the user should be redirected to in order to send a message.
* @throws Exception
*/
public function getRedirectURL(SAML2_Message $message)
{
$store = SimpleSAML_Store::getInstance();
if ($store === FALSE) {
throw new Exception('Unable to send artifact without a datastore configured.');
}
$generatedId = pack('H*', (string) SimpleSAML_Utilities::stringToHex(SimpleSAML_Utilities::generateRandomBytes(20)));
$artifact = base64_encode("" . sha1($message->getIssuer(), TRUE) . $generatedId);
$artifactData = $message->toUnsignedXML();
$artifactDataString = $artifactData->ownerDocument->saveXML($artifactData);
$store->set('artifact', $artifact, $artifactDataString, time() + 15 * 60);
$params = array('SAMLart' => $artifact);
$relayState = $message->getRelayState();
if ($relayState !== NULL) {
$params['RelayState'] = $relayState;
}
return SimpleSAML_Utilities::addURLparameter($message->getDestination(), $params);
}
示例4: newSessionId
/**
* Create and set new session id.
*
* @return string The new session id.
*/
public function newSessionId()
{
$session_cookie_params = session_get_cookie_params();
if ($session_cookie_params['secure'] && !SimpleSAML_Utilities::isHTTPS()) {
throw new SimpleSAML_Error_Exception('Session start with secure cookie not allowed on http.');
}
if (headers_sent()) {
throw new SimpleSAML_Error_Exception('Cannot create new session - headers already sent.');
}
/* Generate new (secure) session id. */
$sessionId = SimpleSAML_Utilities::stringToHex(SimpleSAML_Utilities::generateRandomBytes(16));
SimpleSAML_Session::createSession($sessionId);
if (session_id() !== '') {
/* Session already started, close it. */
session_write_close();
}
session_id($sessionId);
session_start();
return session_id();
}
示例5: getCookieSessionId
/**
* Retrieve the session id of saved in the session cookie.
*
* @return string The session id saved in the cookie.
*/
public function getCookieSessionId()
{
if (session_id() === '') {
$session_cookie_params = session_get_cookie_params();
if ($session_cookie_params['secure'] && !SimpleSAML_Utilities::isHTTPS()) {
throw new SimpleSAML_Error_Exception('Session start with secure cookie not allowed on http.');
}
if (!self::hasSessionCookie()) {
if (headers_sent()) {
throw new SimpleSAML_Error_Exception('Cannot create new session - headers already sent.');
}
/* Session cookie unset - session id not set. Generate new (secure) session id. */
$sessionId = SimpleSAML_Utilities::stringToHex(SimpleSAML_Utilities::generateRandomBytes(16));
SimpleSAML_Session::createSession($sessionId);
session_id($sessionId);
}
session_start();
}
return session_id();
}
示例6: send
function send()
{
if ($this->to == NULL) {
throw new Exception('EMail field [to] is required and not set.');
}
if ($this->subject == NULL) {
throw new Exception('EMail field [subject] is required and not set.');
}
if ($this->body == NULL) {
throw new Exception('EMail field [body] is required and not set.');
}
$random_hash = SimpleSAML_Utilities::stringToHex(SimpleSAML_Utilities::generateRandomBytes(16));
if (isset($this->from)) {
$this->headers[] = 'From: ' . $this->from;
}
if (isset($this->replyto)) {
$this->headers[] = 'Reply-To: ' . $this->replyto;
}
$this->headers[] = 'Content-Type: multipart/alternative; boundary="simplesamlphp-' . $random_hash . '"';
$message = '
--simplesamlphp-' . $random_hash . '
Content-Type: text/plain; charset="utf-8"
Content-Transfer-Encoding: 8bit
' . strip_tags(html_entity_decode($this->body)) . '
--simplesamlphp-' . $random_hash . '
Content-Type: text/html; charset="utf-8"
Content-Transfer-Encoding: 8bit
' . $this->getHTML($this->body) . '
--simplesamlphp-' . $random_hash . '--
';
$headers = implode("\n", $this->headers);
$mail_sent = @mail($this->to, $this->subject, $message, $headers);
SimpleSAML_Logger::debug('Email: Sending e-mail to [' . $this->to . '] : ' . ($mail_sent ? 'OK' : 'Failed'));
if (!$mail_sent) {
throw new Exception('Error when sending e-mail');
}
}
示例7: getValue
/**
* Get the NameID value.
*
* @return string|NULL The NameID value.
*/
protected function getValue(array &$state)
{
if (!isset($state['saml:NameIDFormat']) || $state['saml:NameIDFormat'] !== $this->format) {
SimpleSAML_Logger::debug('SQLPersistentNameID: Request did not specify persistent NameID format - not generating persistent NameID.');
return NULL;
}
if (!isset($state['Destination']['entityid'])) {
SimpleSAML_Logger::warning('SQLPersistentNameID: No SP entity ID - not generating persistent NameID.');
return NULL;
}
$spEntityId = $state['Destination']['entityid'];
if (!isset($state['Source']['entityid'])) {
SimpleSAML_Logger::warning('SQLPersistentNameID: No IdP entity ID - not generating persistent NameID.');
return NULL;
}
$idpEntityId = $state['Source']['entityid'];
if (!isset($state['Attributes'][$this->attribute]) || count($state['Attributes'][$this->attribute]) === 0) {
SimpleSAML_Logger::warning('SQLPersistentNameID: Missing attribute ' . var_export($this->attribute, TRUE) . ' on user - not generating persistent NameID.');
return NULL;
}
if (count($state['Attributes'][$this->attribute]) > 1) {
SimpleSAML_Logger::warning('SQLPersistentNameID: More than one value in attribute ' . var_export($this->attribute, TRUE) . ' on user - not generating persistent NameID.');
return NULL;
}
$uid = array_values($state['Attributes'][$this->attribute]);
/* Just in case the first index is no longer 0. */
$uid = $uid[0];
$value = sspmod_saml_IdP_SQLNameID::get($idpEntityId, $spEntityId, $uid);
if ($value !== NULL) {
SimpleSAML_Logger::debug('SQLPersistentNameID: Found persistent NameID ' . var_export($value, TRUE) . ' for user ' . var_export($uid, TRUE) . '.');
return $value;
}
if (!isset($state['saml:AllowCreate']) || !$state['saml:AllowCreate']) {
SimpleSAML_Logger::warning('SQLPersistentNameID: Did not find persistent NameID for user, and not allowed to create new NameID.');
throw new sspmod_saml_Error(SAML2_Const::STATUS_RESPONDER, 'urn:oasis:names:tc:SAML:2.0:status:InvalidNameIDPolicy');
}
$value = SimpleSAML_Utilities::stringToHex(SimpleSAML_Utilities::generateRandomBytes(20));
SimpleSAML_Logger::debug('SQLPersistentNameID: Created persistent NameID ' . var_export($value, TRUE) . ' for user ' . var_export($uid, TRUE) . '.');
sspmod_saml_IdP_SQLNameID::add($idpEntityId, $spEntityId, $uid, $value);
return $value;
}
示例8: __construct
protected function __construct()
{
/* Call the parent constructor in case it should become
* necessary in the future.
*/
parent::__construct();
/* Initialize the php session handling.
*
* If session_id() returns a blank string, then we need
* to call session start. Otherwise the session is already
* started, and we should avoid calling session_start().
*/
if (session_id() === '') {
$config = SimpleSAML_Configuration::getInstance();
$params = $this->getCookieParams();
$version = explode('.', PHP_VERSION);
if ((int) $version[0] === 5 && (int) $version[1] < 2) {
session_set_cookie_params($params['lifetime'], $params['path'], $params['domain'], $params['secure']);
} else {
session_set_cookie_params($params['lifetime'], $params['path'], $params['domain'], $params['secure'], $params['httponly']);
}
$cookiename = $config->getString('session.phpsession.cookiename', NULL);
if (!empty($cookiename)) {
session_name($cookiename);
}
$savepath = $config->getString('session.phpsession.savepath', NULL);
if (!empty($savepath)) {
session_save_path($savepath);
}
if (!array_key_exists(session_name(), $_COOKIE)) {
if (headers_sent()) {
throw new SimpleSAML_Error_Exception('Cannot create new session - headers already sent.');
}
/* Session cookie unset - session id not set. Generate new (secure) session id. */
session_id(SimpleSAML_Utilities::stringToHex(SimpleSAML_Utilities::generateRandomBytes(16)));
}
session_start();
}
}
示例9: pwHash
/**
* This function generates a password hash
* @param $password The unencrypted password
* @param $algo The hashing algorithm, capitals, optionally prepended with 'S' (salted)
* @param $salt Optional salt
*/
public static function pwHash($password, $algo, $salt = NULL)
{
assert('is_string($algo)');
assert('is_string($password)');
if (in_array(strtolower($algo), hash_algos())) {
$php_algo = strtolower($algo);
// 'sha256' etc
// LDAP compatibility
return '{' . preg_replace('/^SHA1$/', 'SHA', $algo) . '}' . base64_encode(hash($php_algo, $password, TRUE));
}
// Salt
if (!$salt) {
// Default 8 byte salt, but 4 byte for LDAP SHA1 hashes
$bytes = $algo == 'SSHA1' ? 4 : 8;
$salt = SimpleSAML_Utilities::generateRandomBytes($bytes);
}
if ($algo[0] == 'S' && in_array(substr(strtolower($algo), 1), hash_algos())) {
$php_algo = substr(strtolower($algo), 1);
// 'sha256' etc
// Salted hash, with LDAP compatibility
return '{' . preg_replace('/^SSHA1$/', 'SSHA', $algo) . '}' . base64_encode(hash($php_algo, $password . $salt, TRUE) . $salt);
}
throw new Exception('Hashing algoritm \'' . strtolower($algo) . '\' not supported');
}
示例10: log
/**
* Notify about an event.
*
* @param string $event The event.
* @param array $data Event data. Optional.
*/
public static function log($event, array $data = array())
{
assert('is_string($event)');
assert('!isset($data["op"])');
assert('!isset($data["time"])');
assert('!isset($data["_id"])');
if (!self::$initialized) {
self::initOutputs();
self::$initialized = TRUE;
}
if (empty(self::$outputs)) {
/* Not enabled. */
return;
}
$data['op'] = $event;
$data['time'] = microtime(TRUE);
/* The ID generation is designed to cluster IDs related in time close together. */
$int_t = (int) $data['time'];
$hd = SimpleSAML_Utilities::generateRandomBytes(16);
$data['_id'] = sprintf('%016x%s', $int_t, bin2hex($hd));
foreach (self::$outputs as $out) {
$out->emit($data);
}
}
示例11: createSessionID
private static function createSessionID()
{
return SimpleSAML_Utilities::stringToHex(SimpleSAML_Utilities::generateRandomBytes(16));
}
示例12: saveError
/**
* Save an error report.
*
* @return array The array with the error report data.
*/
protected function saveError()
{
$data = $this->format();
$emsg = array_shift($data);
$etrace = implode("\n", $data);
$reportId = SimpleSAML_Utilities::stringToHex(SimpleSAML_Utilities::generateRandomBytes(4));
SimpleSAML_Logger::error('Error report with id ' . $reportId . ' generated.');
$config = SimpleSAML_Configuration::getInstance();
$session = SimpleSAML_Session::getInstance();
if (isset($_SERVER['HTTP_REFERER'])) {
$referer = $_SERVER['HTTP_REFERER'];
/*
* Remove anything after the first '?' or ';', just
* in case it contains any sensitive data.
*/
$referer = explode('?', $referer, 2);
$referer = $referer[0];
$referer = explode(';', $referer, 2);
$referer = $referer[0];
} else {
$referer = 'unknown';
}
$errorData = array('exceptionMsg' => $emsg, 'exceptionTrace' => $etrace, 'reportId' => $reportId, 'trackId' => $session->getTrackID(), 'url' => SimpleSAML_Utilities::selfURLNoQuery(), 'version' => $config->getVersion(), 'referer' => $referer);
$session->setData('core:errorreport', $reportId, $errorData);
return $errorData;
}
示例13: _createBoundary
/**
* Creates boundary string
*
* @return void
*/
protected function _createBoundary()
{
$random_hash = SimpleSAML_Utilities::stringToHex(SimpleSAML_Utilities::generateRandomBytes(16));
$this->_altBoundary = 'alt-' . $random_hash;
$this->_mixedBoundary = 'mixed-' . $random_hash;
}
示例14: send
function send()
{
if ($this->to == NULL) {
throw new Exception('EMail field [to] is required and not set.');
}
if ($this->subject == NULL) {
throw new Exception('EMail field [subject] is required and not set.');
}
// if ($this->body == NULL) throw new Exception('EMail field [body] is required and not set.');
$random_hash = SimpleSAML_Utilities::stringToHex(SimpleSAML_Utilities::generateRandomBytes(16));
$message = $this->buildMessage($random_hash);
if (isset($this->from)) {
$this->headers[] = 'From: ' . $this->from;
}
if (isset($this->replyto)) {
$this->headers[] = 'Reply-To: ' . $this->replyto;
}
$this->headers[] = 'Content-Type: multipart/alternative; boundary="simplesamlphp-' . $random_hash . '"';
$headers = join("\r\n", $this->headers);
$mail_sent = @mail($this->to, $this->subject, $message, $headers);
SimpleSAML_Logger::debug('Email: Sending e-mail to [' . $this->to . '] : ' . ($mail_sent ? 'OK' : 'Failed'));
if (!$mail_sent) {
throw new Exception('Error when sending e-mail');
}
}
示例15: __construct
/**
* Private constructor that restricts instantiation to getInstance().
*
* @param boolean $transient Whether to create a transient session or not.
*/
private function __construct($transient = FALSE)
{
$this->authData = array();
if ($transient) {
$this->trackid = 'XXXXXXXXXX';
$this->transient = TRUE;
return;
}
$sh = SimpleSAML_SessionHandler::getSessionHandler();
$this->sessionId = $sh->newSessionId();
$this->trackid = SimpleSAML_Utilities::stringToHex(SimpleSAML_Utilities::generateRandomBytes(5));
$this->dirty = TRUE;
/* Initialize data for session check function if defined */
$globalConfig = SimpleSAML_Configuration::getInstance();
$checkFunction = $globalConfig->getArray('session.check_function', NULL);
if (isset($checkFunction)) {
assert('is_callable($checkFunction)');
call_user_func($checkFunction, $this, TRUE);
}
}