当前位置: 首页>>代码示例>>Python>>正文


Python randbytes.secureRandom函数代码示例

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


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

示例1: streamStarted

    def streamStarted(self, rootElement):
        """
        Called by the stream when it has started.

        This examines the default namespace of the incoming stream and whether
        there is a requested hostname for the component. Then it generates a
        stream identifier, sends a response header and adds an observer for
        the first incoming element, triggering L{onElement}.
        """

        xmlstream.ListenAuthenticator.streamStarted(self, rootElement)

        # Compatibility fix for pre-8.2 implementations of ListenAuthenticator
        if not self.xmlstream.sid:
            from twisted.python import randbytes
            self.xmlstream.sid = randbytes.secureRandom(8).encode('hex')

        if rootElement.defaultUri != self.namespace:
            exc = error.StreamError('invalid-namespace')
            self.xmlstream.sendStreamError(exc)
            return

        # self.xmlstream.thisEntity is set to the address the component
        # wants to assume.
        if not self.xmlstream.thisEntity:
            exc = error.StreamError('improper-addressing')
            self.xmlstream.sendStreamError(exc)
            return

        self.xmlstream.sendHeader()
        self.xmlstream.addOnetimeObserver('/*', self.onElement)
开发者ID:thepaul,项目名称:wokkel,代码行数:31,代码来源:component.py

示例2: streamStarted

    def streamStarted(self, rootElement):
        xmlstream.ListenAuthenticator.streamStarted(self, rootElement)

        # Compatibility fix for pre-8.2 implementations of ListenAuthenticator
        if not self.xmlstream.sid:
            self.xmlstream.sid = randbytes.secureRandom(8).encode('hex')

        if self.xmlstream.thisEntity:
            targetDomain = self.xmlstream.thisEntity.host
        else:
            targetDomain = self.service.defaultDomain

        def prepareStream(domain):
            self.xmlstream.namespace = self.namespace
            self.xmlstream.prefixes = {xmlstream.NS_STREAMS: 'stream',
                                       NS_DIALBACK: 'db'}
            if domain:
                self.xmlstream.thisEntity = jid.internJID(domain)

        try:
            if xmlstream.NS_STREAMS != rootElement.uri or \
               self.namespace != self.xmlstream.namespace or \
               ('db', NS_DIALBACK) not in rootElement.localPrefixes.iteritems():
                raise error.StreamError('invalid-namespace')

            if targetDomain and targetDomain not in self.service.domains:
                raise error.StreamError('host-unknown')
        except error.StreamError, exc:
            prepareStream(self.service.defaultDomain)
            self.xmlstream.sendStreamError(exc)
            return
开发者ID:thepaul,项目名称:wokkel,代码行数:31,代码来源:server.py

示例3: perspective_auth_challenge

    def perspective_auth_challenge(self):
        """
        Remote method for requesting to begin the challenge/response
        Authorization handshake.  Start by creating a random, signed challenge
        string that is encrypted using the clients public key.  Only the client
        with the correct key can decrypt it and send it back

        If the Avatar does not have the public key for the client attempting to
        connect it will return -1 indicating as such.  This allows the client
        to trigger the key exchange (pairing) before retrying.
        """
        if not self.client_key:
            return -1

        challenge = secureRandom(self.key_size/16)

        # encode using master's key, only the matching private
        # key will be able to decode this message
        encrypted = self.client_key.encrypt(challenge, None)[0]

        # now encode and hash the challenge string so it is not stored 
        # plaintext.  It will be received in this same form so it will be 
        # easier to compare
        challenge = self.server_key.encrypt(challenge, None)
        challenge = hashlib.sha512(challenge[0]).hexdigest()

        self.challenge = challenge
        self.challenged = True

        return encrypted
开发者ID:jlg,项目名称:pydra-map-reduce,代码行数:30,代码来源:rsa_auth.py

示例4: sendPacket

    def sendPacket(self, messageType, payload):
        """
        Sends a packet.  If it's been set up, compress the data, encrypt it,
        and authenticate it before sending.

        @param messageType: The type of the packet; generally one of the
                            MSG_* values.
        @type messageType: C{int}
        @param payload: The payload for the message.
        @type payload: C{str}
        """
        payload = chr(messageType) + payload
        if self.outgoingCompression:
            payload = (self.outgoingCompression.compress(payload)
                       + self.outgoingCompression.flush(2))
        bs = self.currentEncryptions.encBlockSize
        # 4 for the packet length and 1 for the padding length
        totalSize = 5 + len(payload)
        lenPad = bs - (totalSize % bs)
        if lenPad < 4:
            lenPad = lenPad + bs
        packet = (struct.pack('!LB',
                              totalSize + lenPad - 4, lenPad) +
                  payload + randbytes.secureRandom(lenPad))
        encPacket = (
            self.currentEncryptions.encrypt(packet) +
            self.currentEncryptions.makeMAC(
                self.outgoingPacketSequence, packet))
        self.transport.write(encPacket)
        self.outgoingPacketSequence += 1
开发者ID:axray,项目名称:dataware.dreamplug,代码行数:30,代码来源:transport.py

示例5: passwordLogin

 def passwordLogin(self, username):
     """
     Generate a new challenge for the given username.
     """
     self.challenge = secureRandom(16)
     self.username = username
     return {'challenge': self.challenge}
开发者ID:bne,项目名称:squeal,代码行数:7,代码来源:ampauth.py

示例6: sendPacket

    def sendPacket(self, messageType, payload):
        """
        Override because OpenSSH pads with 0 on KEXINIT
        """
        if self._keyExchangeState != self._KEY_EXCHANGE_NONE:
            if not self._allowedKeyExchangeMessageType(messageType):
                self._blockedByKeyExchange.append((messageType, payload))
                return

        payload = chr(messageType) + payload
        if self.outgoingCompression:
            payload = (self.outgoingCompression.compress(payload)
                       + self.outgoingCompression.flush(2))
        bs = self.currentEncryptions.encBlockSize
        # 4 for the packet length and 1 for the padding length
        totalSize = 5 + len(payload)
        lenPad = bs - (totalSize % bs)
        if lenPad < 4:
            lenPad = lenPad + bs
        if messageType == transport.MSG_KEXINIT:
            padding = b'\0' * lenPad
        else:
            padding = randbytes.secureRandom(lenPad)

        packet = (struct.pack(b'!LB',
                              totalSize + lenPad - 4, lenPad) +
                  payload + padding)
        encPacket = (
            self.currentEncryptions.encrypt(packet) +
            self.currentEncryptions.makeMAC(
                self.outgoingPacketSequence, packet))
        self.transport.write(encPacket)
        self.outgoingPacketSequence += 1
开发者ID:davegermiquet,项目名称:cowrie,代码行数:33,代码来源:transport.py

示例7: _toString_OPENSSH

    def _toString_OPENSSH(self, extra):
        """
        Return a public or private OpenSSH string.  See
        _fromString_PUBLIC_OPENSSH and _fromString_PRIVATE_OPENSSH for the
        string formats.  If extra is present, it represents a comment for a
        public key, or a passphrase for a private key.

        @param extra: Comment for a public key or passphrase for a
            private key
        @type extra: L{bytes}

        @rtype: L{bytes}
        """
        data = self.data()
        if self.isPublic():
            b64Data = base64.encodestring(self.blob()).replace(b'\n', b'')
            if not extra:
                extra = b''
            return (self.sshType() + b' ' + b64Data + b' ' + extra).strip()
        else:
            lines = [b''.join((b'-----BEGIN ', self.type().encode('ascii'),
                               b' PRIVATE KEY-----'))]
            if self.type() == 'RSA':
                p, q = data['p'], data['q']
                objData = (0, data['n'], data['e'], data['d'], q, p,
                           data['d'] % (q - 1), data['d'] % (p - 1),
                           data['u'])
            else:
                objData = (0, data['p'], data['q'], data['g'], data['y'],
                           data['x'])
            asn1Sequence = univ.Sequence()
            for index, value in izip(itertools.count(), objData):
                asn1Sequence.setComponentByPosition(index, univ.Integer(value))
            asn1Data = berEncoder.encode(asn1Sequence)
            if extra:
                iv = randbytes.secureRandom(8)
                hexiv = ''.join(['%02X' % (ord(x),) for x in iterbytes(iv)])
                hexiv = hexiv.encode('ascii')
                lines.append(b'Proc-Type: 4,ENCRYPTED')
                lines.append(b'DEK-Info: DES-EDE3-CBC,' + hexiv + b'\n')
                ba = md5(extra + iv).digest()
                bb = md5(ba + extra + iv).digest()
                encKey = (ba + bb)[:24]
                padLen = 8 - (len(asn1Data) % 8)
                asn1Data += (chr(padLen) * padLen).encode('ascii')

                encryptor = Cipher(
                    algorithms.TripleDES(encKey),
                    modes.CBC(iv),
                    backend=default_backend()
                ).encryptor()

                asn1Data = encryptor.update(asn1Data) + encryptor.finalize()

            b64Data = base64.encodestring(asn1Data).replace(b'\n', b'')
            lines += [b64Data[i:i + 64] for i in range(0, len(b64Data), 64)]
            lines.append(b''.join((b'-----END ', self.type().encode('ascii'),
                                   b' PRIVATE KEY-----')))
            return b'\n'.join(lines)
开发者ID:daweasel27,项目名称:PhobiaEnemy,代码行数:59,代码来源:keys.py

示例8: get_bytes

 def get_bytes(self, numBytes):
     """
     Get a number of random bytes.
     """
     warnings.warn("entropy.get_bytes is deprecated, please use "
                   "twisted.python.randbytes.secureRandom instead.",
         category=DeprecationWarning, stacklevel=2)
     return randbytes.secureRandom(numBytes)
开发者ID:Almad,项目名称:twisted,代码行数:8,代码来源:common.py

示例9: _generateNonce

    def _generateNonce(self):
        """
        Create a random value suitable for use as the nonce parameter of a
        WWW-Authenticate challenge.

        @rtype: C{str}
        """
        return secureRandom(12).encode('hex')
开发者ID:0004c,项目名称:VTK,代码行数:8,代码来源:credentials.py

示例10: _generateNonce

    def _generateNonce(self):
        """
        Create a random value suitable for use as the nonce parameter of a
        WWW-Authenticate challenge.

        @rtype: L{bytes}
        """
        return hexlify(secureRandom(12))
开发者ID:12019,项目名称:OpenWrt_Luci_Lua,代码行数:8,代码来源:credentials.py

示例11: determineFrom

    def determineFrom(cls, challenge, password):
        """
        Create a nonce and use it, along with the given challenge and password,
        to generate the parameters for a response.

        @return: A C{dict} suitable to be used as the keyword arguments when
            calling this command.
        """
        nonce = secureRandom(16)
        response = _calcResponse(challenge, nonce, password)
        return dict(cnonce=nonce, response=response)
开发者ID:bne,项目名称:squeal,代码行数:11,代码来源:ampauth.py

示例12: test_bad_response

 def test_bad_response(self):
     """
     Test the response function when given an incorrect response
     """
     avatar = RSAAvatar(self.priv_key, None, self.pub_key, key_size=KEY_SIZE)
     challenge = avatar.perspective_auth_challenge()
     #create response that can't be string because its longer than the hash
     response = secureRandom(600)
     result = avatar.perspective_auth_response(response)
     self.assertEqual(result, -1, 'auth_response should return error (-1) when given bad response')
     self.assertFalse(avatar.authenticated, 'avatar.authenticated flag should be False if auth_response fails')
开发者ID:brianmartin,项目名称:Pydra,代码行数:11,代码来源:rsa_auth.py

示例13: generateOneTimePad

 def generateOneTimePad(self, userStore):
     """
     Generate a pad which can be used to authenticate via AMP.  This pad
     will expire in L{ONE_TIME_PAD_DURATION} seconds.
     """
     pad = secureRandom(16).encode('hex')
     self._oneTimePads[pad] = userStore.idInParent
     def expirePad():
         self._oneTimePads.pop(pad, None)
     self.callLater(self.ONE_TIME_PAD_DURATION, expirePad)
     return pad
开发者ID:fusionapp,项目名称:mantissa,代码行数:11,代码来源:ampserver.py

示例14: _makeProxy

    def _makeProxy(self):
        while True:
            token = base64.b64encode(secureRandom(9, False), '-_')

            if token not in proxies:
                proxies[token] = { 'ct': None, 'ident': None, 'request': None, 'creds': None }
                syslog.syslog(syslog.LOG_INFO, "Created proxy " + token)
                break

        reactor.callLater(PROXY_LIFETIME, self._deleteProxy, token)
        return token
开发者ID:SeQRentry,项目名称:seqrentry,代码行数:11,代码来源:seqrentry.py

示例15: __init__

    def __init__(self, config, router):
        self.config = config
        self.defaultDomain = config['network']
        self.domains = set()
        self.domains.add(self.defaultDomain)
        self.secret = randbytes.secureRandom(16).encode('hex')
        self.router = router

        self._outgoingStreams = {}
        self._outgoingQueues = {}
        self._outgoingConnecting = set()
        self.serial = 0
开发者ID:BillTheBest,项目名称:xmppserver,代码行数:12,代码来源:s2s.py


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