Generate nonce for oauth request
322293
function get_nonce() {
        if (!empty($this->nonce)) {
            $nonce = $this->nonce;
            unset($this->nonce);
            return $nonce;
        }
        $mt = microtime();
        $rand = mt_rand();

        return md5($mt . $rand);
    }
1085915
def request_token(self, board):
    '''
    '''
    nonce = str(uuid.uuid4())

    data = {'scopes': 'write',
            'client_id': self.client_id,
            'application_name': 'HelpMe',
            'public_key': self.public_key.replace("'",""),
            'nonce': nonce }

    url = (board + "/user-api-key/new?scopes=write&application_name=HelpMe&public_key=" + 
           self.public_key.replace("'", "") + 
           "&client_id=" + self.client_id +
           "&nonce=" + nonce )

    bot.newline()
    bot.info('Open browser to:')
    bot.info(url)
    bot.newline()
    
    # the user will open browser, get a token, and then have it saved here.
    bot.info('Copy paste token, press Ctrl-D to save it:')

    lines = []

    # The message is multiple lines
    while True:
        try:
            line = enter_input()
        except EOFError:
            break
        if line:
            lines.append(line)

    message = "\n".join(lines)

    # Write to temporary file, we only need to get key
    tmpfile = mktemp()
    with open(tmpfile, 'w') as filey:
        filey.write(message)

    # Read in again, and get token **important** is binary
    with open(tmpfile, 'rb') as filey:
        message = filey.read()

    # uses pycryptodome (3.7.2)
    cipher = Cipher_PKCS1_v1_5.new(self.key)
    decrypted = json.loads(cipher.decrypt(b64decode(message), None).decode())

    # Validate nonce is in response
    if "nonce" not in decrypted:
        bot.exit('Missing nonce field in response for token, invalid.')

    # Must return nonce that we sent
    if decrypted['nonce'] != nonce:
        bot.exit('Invalid nonce, exiting.')

    return decrypted['key']
927461
protected function nonce()
    {
        $action = ($this->getParameter('action') == null) ?
                    $this->RequestContext->getControls()->getControl('action')
                  : $this->getParameter('action');

        return $this->Nonces->create($action);
    }
32113
public function getParamsToSign(RequestInterface $request, $timestamp, $nonce)
    {
        $params = new Collection(array(
            'oauth_consumer_key'     => $this->config['consumer_key'],
            'oauth_nonce'            => $nonce,
            'oauth_signature_method' => $this->config['signature_method'],
            'oauth_timestamp'        => $timestamp,
            'oauth_token'            => $this->config['token'],
            'oauth_version'          => $this->config['version']
        ));
        
        if (array_key_exists('callback', $this->config) == true) {
            $params['oauth_callback'] = $this->config['callback'];
        }
        
        if (array_key_exists('verifier', $this->config) == true) {
            $params['oauth_verifier'] = $this->config['verifier'];
        }

        // Add query string parameters
        $params->merge($request->getQuery());

        // Add POST fields to signing string if required
        if ($this->shouldPostFieldsBeSigned($request))
        {
            $params->merge($request->getPostFields());
        }

        // Sort params
        $params = $params->toArray();
        ksort($params);

        return $params;
    }
346362
function handleSocketToken(req, res, next) {
		const transomNonce = server.registry.get(nonceHandler);

		function loggable(token) {
			if (typeof transomNonce.loggableToken === 'function') {
				return transomNonce.loggableToken(token);
			}
			return `${token.substr(0, 4)}***${token.substr(-4)}`;
		}

		var p = new Promise(function (resolve, reject) {
			// Create the nonce with req.locals.user as the payload.
			transomNonce.createNonce(req.locals.user, nonceExpirySeconds, function (err, nonce) {
				if (err) {
					debug('Error creating nonce', err);
					return reject(err);
				}
				debug(`Created nonce ${loggable(nonce.token)}`);
				resolve(nonce);
			});
		}).then(function (nonce) {
			debug(`Replying with ${loggable(nonce.token)}`);
			res.json({
				token: nonce.token
			});
			next();
		}).catch(function (err) {
			debug('Error in handleSocketToken', err);
			next(err);
		});
	}
1103430
def schnorr_generate_nonce_pair(self, msg, raw=False,
                                    digest=hashlib.sha256):
        
        if not HAS_SCHNORR:
            raise Exception("secp256k1_schnorr not enabled")

        msg32 = _hash32(msg, raw, digest)
        pubnonce = ffi.new('secp256k1_pubkey *')
        privnonce = ffi.new('char [32]')

        valid = lib.secp256k1_schnorr_generate_nonce_pair(
            self.ctx, pubnonce, privnonce, msg32, self.private_key,
            ffi.NULL, ffi.NULL)
        assert valid == 1

        return pubnonce, privnonce
596166
async def do_authentication(sender):
    
    # Step 1 sending: PQ Request, endianness doesn't matter since it's random
    nonce = int.from_bytes(os.urandom(16), 'big', signed=True)
    res_pq = await sender.send(ReqPqMultiRequest(nonce))
    assert isinstance(res_pq, ResPQ), 'Step 1 answer was %s' % res_pq

    if res_pq.nonce != nonce:
        raise SecurityError('Step 1 invalid nonce from server')

    pq = get_int(res_pq.pq)

    # Step 2 sending: DH Exchange
    p, q = Factorization.factorize(pq)
    p, q = rsa.get_byte_array(p), rsa.get_byte_array(q)
    new_nonce = int.from_bytes(os.urandom(32), 'little', signed=True)

    pq_inner_data = bytes(PQInnerData(
        pq=rsa.get_byte_array(pq), p=p, q=q,
        nonce=res_pq.nonce,
        server_nonce=res_pq.server_nonce,
        new_nonce=new_nonce
    ))

    # sha_digest + data + random_bytes
    cipher_text, target_fingerprint = None, None
    for fingerprint in res_pq.server_public_key_fingerprints:
        cipher_text = rsa.encrypt(fingerprint, pq_inner_data)
        if cipher_text is not None:
            target_fingerprint = fingerprint
            break

    if cipher_text is None:
        raise SecurityError(
            'Step 2 could not find a valid key for fingerprints: {}'
            .format(', '.join(
                [str(f) for f in res_pq.server_public_key_fingerprints])
            )
        )

    server_dh_params = await sender.send(ReqDHParamsRequest(
        nonce=res_pq.nonce,
        server_nonce=res_pq.server_nonce,
        p=p, q=q,
        public_key_fingerprint=target_fingerprint,
        encrypted_data=cipher_text
    ))

    assert isinstance(
        server_dh_params, (ServerDHParamsOk, ServerDHParamsFail)),\
        'Step 2.1 answer was %s' % server_dh_params

    if server_dh_params.nonce != res_pq.nonce:
        raise SecurityError('Step 2 invalid nonce from server')

    if server_dh_params.server_nonce != res_pq.server_nonce:
        raise SecurityError('Step 2 invalid server nonce from server')

    if isinstance(server_dh_params, ServerDHParamsFail):
        nnh = int.from_bytes(
            sha1(new_nonce.to_bytes(32, 'little', signed=True)).digest()[4:20],
            'little', signed=True
        )
        if server_dh_params.new_nonce_hash != nnh:
            raise SecurityError('Step 2 invalid DH fail nonce from server')

    assert isinstance(server_dh_params, ServerDHParamsOk),\
        'Step 2.2 answer was %s' % server_dh_params

    # Step 3 sending: Complete DH Exchange
    key, iv = helpers.generate_key_data_from_nonce(
        res_pq.server_nonce, new_nonce
    )
    if len(server_dh_params.encrypted_answer) % 16 != 0:
        # See PR#453
        raise SecurityError('Step 3 AES block size mismatch')

    plain_text_answer = AES.decrypt_ige(
        server_dh_params.encrypted_answer, key, iv
    )

    with BinaryReader(plain_text_answer) as reader:
        reader.read(20)  # hash sum
        server_dh_inner = reader.tgread_object()
        assert isinstance(server_dh_inner, ServerDHInnerData),\
            'Step 3 answer was %s' % server_dh_inner

    if server_dh_inner.nonce != res_pq.nonce:
        raise SecurityError('Step 3 Invalid nonce in encrypted answer')

    if server_dh_inner.server_nonce != res_pq.server_nonce:
        raise SecurityError('Step 3 Invalid server nonce in encrypted answer')

    dh_prime = get_int(server_dh_inner.dh_prime, signed=False)
    g_a = get_int(server_dh_inner.g_a, signed=False)
    time_offset = server_dh_inner.server_time - int(time.time())

    b = get_int(os.urandom(256), signed=False)
    gb = pow(server_dh_inner.g, b, dh_prime)
    gab = pow(g_a, b, dh_prime)

    # Prepare client DH Inner Data
    client_dh_inner = bytes(ClientDHInnerData(
        nonce=res_pq.nonce,
        server_nonce=res_pq.server_nonce,
        retry_id=0,  # TODO Actual retry ID
        g_b=rsa.get_byte_array(gb)
    ))

    client_dh_inner_hashed = sha1(client_dh_inner).digest() + client_dh_inner

    # Encryption
    client_dh_encrypted = AES.encrypt_ige(client_dh_inner_hashed, key, iv)

    # Prepare Set client DH params
    dh_gen = await sender.send(SetClientDHParamsRequest(
        nonce=res_pq.nonce,
        server_nonce=res_pq.server_nonce,
        encrypted_data=client_dh_encrypted,
    ))

    nonce_types = (DhGenOk, DhGenRetry, DhGenFail)
    assert isinstance(dh_gen, nonce_types), 'Step 3.1 answer was %s' % dh_gen
    name = dh_gen.__class__.__name__
    if dh_gen.nonce != res_pq.nonce:
        raise SecurityError('Step 3 invalid {} nonce from server'.format(name))

    if dh_gen.server_nonce != res_pq.server_nonce:
        raise SecurityError(
            'Step 3 invalid {} server nonce from server'.format(name))

    auth_key = AuthKey(rsa.get_byte_array(gab))
    nonce_number = 1 + nonce_types.index(type(dh_gen))
    new_nonce_hash = auth_key.calc_new_nonce_hash(new_nonce, nonce_number)

    dh_hash = getattr(dh_gen, 'new_nonce_hash{}'.format(nonce_number))
    if dh_hash != new_nonce_hash:
        raise SecurityError('Step 3 invalid new nonce hash')

    if not isinstance(dh_gen, DhGenOk):
        raise AssertionError('Step 3.2 answer was %s' % dh_gen)

    return auth_key, time_offset
835599
function temporaryCredentials (done) {
  var strategy = this
  var provider = strategy.provider
  var endpoint = strategy.endpoints.credentials
  var client = strategy.client
  var method = endpoint.method && endpoint.method.toLowerCase()
  var url = endpoint.url
  var header = endpoint.header || 'Authorization'
  var scheme = endpoint.scheme || 'OAuth'
  var accept = endpoint.accept || 'application/x-www-form-urlencoded'
  var key = client.oauth_consumer_key
  var secret = client.oauth_consumer_secret
  var signer = provider.oauth_signature_method || 'PLAINTEXT'
  var realm = provider.realm
  var callback = provider.oauth_callback
  var params = {}

  // Initialize request
  var req = request[method || 'post'](url)

  // Build request parameters
  params.oauth_consumer_key = key
  params.oauth_signature_method = signer
  params.oauth_timestamp = timestamp()
  params.oauth_nonce = nonce(32)
  params.oauth_callback = callback
  params.oauth_version = '1.0'

  // Generate signature (is next line needed for PLAINTEXT?)
  var input = signatureBaseString(method, url, normalizeParameters(params))
  params.oauth_signature = sign(signer, input, secret)

  if (realm) { params.realm = realm }

  // Set Authorization header
  req.set(header, scheme + ' ' + authorizationHeaderParams(params))

  // Set other headers
  req.set('Accept', accept)
  req.set('User-Agent', agent)

  // Execute request
  return req.end(function (err, res) {
    if (err) { return done(err) }
    var response = qs.parse(res.text)

    if (res.statusCode !== 200) {
      return done(new Error(res.text))
    }

    done(null, response)
  })
}
264253
public function generateNonce()
    {
        if (function_exists('openssl_random_pseudo_bytes') === true) {
            $hash = md5(openssl_random_pseudo_bytes(32));
        } else {
            $hash = md5(uniqid(mt_rand()));
        }
        return $hash;
    }
522473
def sign_nonce(key, nonce):
    ''' '''
    # HMAC.new(key, msg='', digestmod=None)
    return Cryptodome.Hash.HMAC.new(key, nonce, digestmod=Cryptodome.Hash.SHA256).digest()
231231
function useNonce($server_url, $timestamp, $salt)
    {
        global $Auth_OpenID_SKEW;

        // save one request to memcache when nonce obviously expired
        if (abs($timestamp - time()) > $Auth_OpenID_SKEW) {
            return false;
        }

        // returns false when nonce already exists
        // otherwise adds nonce
        return $this->connection->add(
            'openid_nonce_' . sha1($server_url) . '_' . sha1($salt),
            1, // any value here
            $this->compress,
            $Auth_OpenID_SKEW);
    }
151017
def generate_query_string(self, otp, nonce, timestamp=False, sl=None,
                              timeout=None):
        
        data = [('id', self.client_id),
                ('otp', otp),
                ('nonce', nonce)]

        if timestamp:
            data.append(('timestamp', '1'))

        if sl is not None:
            if sl not in range(0, 101) and sl not in ['fast', 'secure']:
                raise Exception('sl parameter value must be between 0 and '
                                '100 or string "fast" or "secure"')

            data.append(('sl', sl))

        if timeout:
            data.append(('timeout', timeout))

        query_string = urlencode(data)

        if self.key:
            hmac_signature = self.generate_message_signature(query_string)
            hmac_signature = hmac_signature
            query_string += '&h=%s' % (hmac_signature.replace('+', '%2B'))

        return query_string
782442
function nonce(len) {
  var buf = []
    , chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
    , charlen = chars.length;

  for (var i = 0; i < len; ++i) {
    buf.push(chars[Math.random() * charlen | 0]);
  }

  return buf.join('');
}
575467
def useNonce(self, server_url, timestamp, salt):
        
        if abs(timestamp - time.time()) > nonce.SKEW:
            return False

        if server_url:
            proto, rest = server_url.split('://', 1)
        else:
            # Create empty proto / rest values for empty server_url,
            # which is part of a consumer-generated nonce.
            proto, rest = '', ''

        domain = _filenameEscape(rest.split('/', 1)[0])
        url_hash = _safe64(server_url)
        salt_hash = _safe64(salt)

        filename = '%08x-%s-%s-%s-%s' % (timestamp, proto, domain,
                                         url_hash, salt_hash)

        filename = os.path.join(self.nonce_dir, filename)
        try:
            fd = os.open(filename, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0200)
        except OSError, why:
            if why.errno == EEXIST:
                return False
            else:
                raise
        else:
            os.close(fd)
            return True
1321968
function createAuthKey(context) {
    // Extract the nonces
    var newNonce = utility.string2Buffer(context.newNonce, 32);
    var serverNonce = utility.string2Buffer(context.resPQ.server_nonce, 16);
    // Create the serverSalt
    var serverSalt = utility.xor(newNonce.slice(0, 8), serverNonce.slice(0, 8));
    if (logger.isDebugEnabled()) {
        logger.debug('serverSalt(%s) = %s', serverSalt.length, serverSalt.toString('hex'));
    }
    // 
    var authKey = new AuthKey(context.authKeyID, context.authKeyValue);
    if (logger.isDebugEnabled()) {
        logger.debug('authKey = %s', authKey.toString());
    }
    return {
        key: authKey,
        serverSalt: serverSalt,
        toPrintable: tl.utility.toPrintable
    };
}
840085
function checkNonceMatch(context) {
    var newNonce1 = Buffer.concat([utility.string2Buffer(context.newNonce, 32), new Buffer([1]), context.authKeyAuxHash]);
    var newNonceHash = utility.buffer2String(utility.createSHAHash(newNonce1).slice(-16));
    var serverNewNonceHash = context.setClientDHParamsAnswer.new_nonce_hash1;
    if (logger.isDebugEnabled()) {
        logger.debug('newNonceHash = %s, new_nonce_hash1 = %s', newNonceHash.toString(), serverNewNonceHash.toString());
    }
    if (newNonceHash !== serverNewNonceHash) {
        logger.warn('\'dh_gen_ok.new_nonce_hash1\' check fails!');
        throw createError(newNonceHash + ' != ' + serverNewNonceHash, 'EREPLAYATTACK');
    }
    return context;
}
644384
def get_nonoauth_parameters(self):
        """"""
        return dict([(k, v) for k, v in self.items() 
                    if not k.startswith('oauth_')])