Пример #1
0
    def test_sha1(self):
        """
        L{hashlib.sha1} returns an object which can be used to compute a SHA1
        hash as defined by U{RFC 3174<http://tools.ietf.org/rfc/rfc3174.txt>}.
        """
        def format(s):
            return ''.join(s.split()).lower()

        # Test the result using values from section 7.3 of the RFC.
        self.assertEqual(
            sha1("abc").hexdigest(),
            format(
                "A9 99 3E 36 47 06 81 6A BA 3E 25 71 78 50 C2 6C 9C D0 D8 9D"))
        self.assertEqual(
            sha1("abcdbcdecdefdefgefghfghighijhi"
                 "jkijkljklmklmnlmnomnopnopq").hexdigest(),
            format(
                "84 98 3E 44 1C 3B D2 6E BA AE 4A A1 F9 51 29 E5 E5 46 70 F1"))

        # It should have digest and update methods, too.
        self.assertEqual(
            sha1("abc").digest().encode('hex'),
            format(
                "A9 99 3E 36 47 06 81 6A BA 3E 25 71 78 50 C2 6C 9C D0 D8 9D"))
        hash = sha1()
        hash.update("abc")
        self.assertEqual(
            hash.digest().encode('hex'),
            format(
                "A9 99 3E 36 47 06 81 6A BA 3E 25 71 78 50 C2 6C 9C D0 D8 9D"))

        # Instances of it should have a digest_size attribute.
        self.assertEqual(sha1().digest_size, 20)
Пример #2
0
    def test_sha1(self):
        """
        L{hashlib.sha1} returns an object which can be used to compute a SHA1
        hash as defined by U{RFC 3174<http://tools.ietf.org/rfc/rfc3174.txt>}.
        """
        def format(s):
            return ''.join(s.split()).lower()
        # Test the result using values from section 7.3 of the RFC.
        self.assertEqual(
            sha1("abc").hexdigest(),
            format(
                "A9 99 3E 36 47 06 81 6A BA 3E 25 71 78 50 C2 6C 9C D0 D8 9D"))
        self.assertEqual(
            sha1("abcdbcdecdefdefgefghfghighijhi"
                 "jkijkljklmklmnlmnomnopnopq").hexdigest(),
            format(
                "84 98 3E 44 1C 3B D2 6E BA AE 4A A1 F9 51 29 E5 E5 46 70 F1"))

        # It should have digest and update methods, too.
        self.assertEqual(
            sha1("abc").digest().encode('hex'),
            format(
                "A9 99 3E 36 47 06 81 6A BA 3E 25 71 78 50 C2 6C 9C D0 D8 9D"))
        hash = sha1()
        hash.update("abc")
        self.assertEqual(
            hash.digest().encode('hex'),
            format(
                "A9 99 3E 36 47 06 81 6A BA 3E 25 71 78 50 C2 6C 9C D0 D8 9D"))

        # Instances of it should have a digest_size attribute.
        self.assertEqual(
            sha1().digest_size, 20)
Пример #3
0
    def _getKey(self, c, sharedSecret, exchangeHash):
        """
        Get one of the keys for authentication/encryption.

        @type c: C{str}
        @type sharedSecret: C{str}
        @type exchangeHash: C{str}
        """
        k1 = sha1(sharedSecret + exchangeHash + c + self.sessionID)
        k1 = k1.digest()
        k2 = sha1(sharedSecret + exchangeHash + k1).digest()
        return k1 + k2
Пример #4
0
    def _getKey(self, c, sharedSecret, exchangeHash):
        """
        Get one of the keys for authentication/encryption.

        @type c: C{str}
        @type sharedSecret: C{str}
        @type exchangeHash: C{str}
        """
        k1 = sha1(sharedSecret + exchangeHash + c + self.sessionID)
        k1 = k1.digest()
        k2 = sha1(sharedSecret + exchangeHash + k1).digest()
        return k1 + k2
Пример #5
0
    def _continueKEXDH_REPLY(self, ignored, pubKey, f, signature):
        """
        The host key has been verified, so we generate the keys.

        @param pubKey: the public key blob for the server's public key.
        @type pubKey: C{str}
        @param f: the server's Diffie-Hellman public key.
        @type f: C{long}
        @param signature: the server's signature, verifying that it has the
            correct private key.
        @type signature: C{str}
        """
        serverKey = keys.Key.fromString(pubKey)
        sharedSecret = _MPpow(f, self.x, DH_PRIME)
        h = sha1()
        h.update(NS(self.ourVersionString))
        h.update(NS(self.otherVersionString))
        h.update(NS(self.ourKexInitPayload))
        h.update(NS(self.otherKexInitPayload))
        h.update(NS(pubKey))
        h.update(self.e)
        h.update(MP(f))
        h.update(sharedSecret)
        exchangeHash = h.digest()
        if not serverKey.verify(signature, exchangeHash):
            self.sendDisconnect(DISCONNECT_KEY_EXCHANGE_FAILED,
                                'bad signature')
            return
        self._keySetup(sharedSecret, exchangeHash)
Пример #6
0
    def testDigest(self):
        """
        Test digest authentication.

        Set up a stream, and act as if authentication succeeds.
        """
        d = self.init.initialize()

        # The initializer should have sent query to find out auth methods.

        iq = self.output[-1]

        # Send server response
        iq['type'] = 'result'
        iq.query.addElement('username')
        iq.query.addElement('digest')
        iq.query.addElement('resource')
        self.xmlstream.dataReceived(iq.toXml())

        # Upon receiving the response, the initializer can start authentication

        iq = self.output[-1]
        self.assertEquals('iq', iq.name)
        self.assertEquals('set', iq['type'])
        self.assertEquals(('jabber:iq:auth', 'query'),
                          (iq.children[0].uri, iq.children[0].name))
        self.assertEquals('user', unicode(iq.query.username))
        self.assertEquals(sha1('12345secret').hexdigest(),
                          unicode(iq.query.digest))
        self.assertEquals('resource', unicode(iq.query.resource))

        # Send server response
        self.xmlstream.dataReceived("<iq type='result' id='%s'/>" % iq['id'])
        return d
Пример #7
0
    def _continueGEX_REPLY(self, ignored, pubKey, f, signature):
        """
        The host key has been verified, so we generate the keys.

        @param pubKey: the public key blob for the server's public key.
        @type pubKey: C{str}
        @param f: the server's Diffie-Hellman public key.
        @type f: C{long}
        @param signature: the server's signature, verifying that it has the
            correct private key.
        @type signature: C{str}
        """
        serverKey = keys.Key.fromString(pubKey)
        sharedSecret = _MPpow(f, self.x, self.p)
        h = sha1()
        h.update(NS(self.ourVersionString))
        h.update(NS(self.otherVersionString))
        h.update(NS(self.ourKexInitPayload))
        h.update(NS(self.otherKexInitPayload))
        h.update(NS(pubKey))
        h.update('\x00\x00\x08\x00')
        h.update(MP(self.p))
        h.update(MP(self.g))
        h.update(self.e)
        h.update(MP(f))
        h.update(sharedSecret)
        exchangeHash = h.digest()
        if not serverKey.verify(signature, exchangeHash):
            self.sendDisconnect(DISCONNECT_KEY_EXCHANGE_FAILED,
                                'bad signature')
            return
        self._keySetup(sharedSecret, exchangeHash)
Пример #8
0
    def testDigest(self):
        """
        Test digest authentication.

        Set up a stream, and act as if authentication succeeds.
        """
        d = self.init.initialize()

        # The initializer should have sent query to find out auth methods.

        iq = self.output[-1]

        # Send server response
        iq['type'] = 'result'
        iq.query.addElement('username')
        iq.query.addElement('digest')
        iq.query.addElement('resource')
        self.xmlstream.dataReceived(iq.toXml())

        # Upon receiving the response, the initializer can start authentication

        iq = self.output[-1]
        self.assertEquals('iq', iq.name)
        self.assertEquals('set', iq['type'])
        self.assertEquals(('jabber:iq:auth', 'query'),
                          (iq.children[0].uri, iq.children[0].name))
        self.assertEquals('user', unicode(iq.query.username))
        self.assertEquals(
            sha1('12345secret').hexdigest(), unicode(iq.query.digest))
        self.assertEquals('resource', unicode(iq.query.resource))

        # Send server response
        self.xmlstream.dataReceived("<iq type='result' id='%s'/>" % iq['id'])
        return d
Пример #9
0
    def verify(self, signature, data):
        """
        Returns true if the signature for data is valid for this Key.

        @type signature: C{str}
        @type data: C{str}
        @rtype: C{bool}
        """
        if len(signature) == 40:
            # DSA key with no padding
            signatureType, signature = 'ssh-dss', common.NS(signature)
        else:
            signatureType, signature = common.getNS(signature)
        if signatureType != self.sshType():
            return False
        if self.type() == 'RSA':
            numbers = common.getMP(signature)
            digest = pkcs1Digest(data, self.keyObject.size() / 8)
        elif self.type() == 'DSA':
            signature = common.getNS(signature)[0]
            numbers = [
                Util.number.bytes_to_long(n)
                for n in signature[:20], signature[20:]
            ]
            digest = sha1(data).digest()
        return self.keyObject.verify(digest, numbers)
Пример #10
0
def pkcs1Digest(data, messageLength):
    """
    Create a message digest using the SHA1 hash algorithm according to the
    PKCS#1 standard.
    @type data: C{str}
    @type messageLength: C{str}
    """
    digest = sha1(data).digest()
    return pkcs1Pad(ID_SHA1+digest, messageLength)
Пример #11
0
def pkcs1Digest(data, messageLength):
    """
    Create a message digest using the SHA1 hash algorithm according to the
    PKCS#1 standard.
    @type data: C{str}
    @type messageLength: C{str}
    """
    digest = sha1(data).digest()
    return pkcs1Pad(ID_SHA1 + digest, messageLength)
Пример #12
0
 def test_pkcs1(self):
     """
     Test Public Key Cryptographic Standard #1 functions.
     """
     data = 'ABC'
     messageSize = 6
     self.assertEqual(keys.pkcs1Pad(data, messageSize), '\x01\xff\x00ABC')
     hash = sha1().digest()
     messageSize = 40
     self.assertEqual(keys.pkcs1Digest('', messageSize),
                      '\x01\xff\xff\xff\x00' + keys.ID_SHA1 + hash)
Пример #13
0
    def ssh_KEX_DH_GEX_REQUEST_OLD(self, packet):
        """
        This represents two different key exchange methods that share the
        same integer value.

        KEXDH_INIT (for diffie-hellman-group1-sha1 exchanges) payload::

                integer e (the client's Diffie-Hellman public key)

            We send the KEXDH_REPLY with our host key and signature.

        KEX_DH_GEX_REQUEST_OLD (for diffie-hellman-group-exchange-sha1)
        payload::

                integer ideal (ideal size for the Diffie-Hellman prime)

            We send the KEX_DH_GEX_GROUP message with the group that is
            closest in size to ideal.

        If we were told to ignore the next key exchange packet by
        ssh_KEXINIT, drop it on the floor and return.
        """
        if self.ignoreNextPacket:
            self.ignoreNextPacket = 0
            return
        if self.kexAlg == 'diffie-hellman-group1-sha1':
            # this is really KEXDH_INIT
            clientDHpublicKey, foo = getMP(packet)
            y = Util.number.getRandomNumber(512, randbytes.secureRandom)
            serverDHpublicKey = _MPpow(DH_GENERATOR, y, DH_PRIME)
            sharedSecret = _MPpow(clientDHpublicKey, y, DH_PRIME)
            h = sha1()
            h.update(NS(self.otherVersionString))
            h.update(NS(self.ourVersionString))
            h.update(NS(self.otherKexInitPayload))
            h.update(NS(self.ourKexInitPayload))
            h.update(NS(self.factory.publicKeys[self.keyAlg].blob()))
            h.update(MP(clientDHpublicKey))
            h.update(serverDHpublicKey)
            h.update(sharedSecret)
            exchangeHash = h.digest()
            self.sendPacket(
                MSG_KEXDH_REPLY,
                NS(self.factory.publicKeys[self.keyAlg].blob()) +
                serverDHpublicKey +
                NS(self.factory.privateKeys[self.keyAlg].sign(exchangeHash)))
            self._keySetup(sharedSecret, exchangeHash)
        elif self.kexAlg == 'diffie-hellman-group-exchange-sha1':
            self.dhGexRequest = packet
            ideal = struct.unpack('>L', packet)[0]
            self.g, self.p = self.factory.getDHPrime(ideal)
            self.sendPacket(MSG_KEX_DH_GEX_GROUP, MP(self.p) + MP(self.g))
        else:
            raise error.ConchError('bad kexalg: %s' % self.kexAlg)
Пример #14
0
    def ssh_KEX_DH_GEX_REQUEST_OLD(self, packet):
        """
        This represents two different key exchange methods that share the
        same integer value.

        KEXDH_INIT (for diffie-hellman-group1-sha1 exchanges) payload::

                integer e (the client's Diffie-Hellman public key)

            We send the KEXDH_REPLY with our host key and signature.

        KEX_DH_GEX_REQUEST_OLD (for diffie-hellman-group-exchange-sha1)
        payload::

                integer ideal (ideal size for the Diffie-Hellman prime)

            We send the KEX_DH_GEX_GROUP message with the group that is
            closest in size to ideal.

        If we were told to ignore the next key exchange packet by
        ssh_KEXINIT, drop it on the floor and return.
        """
        if self.ignoreNextPacket:
            self.ignoreNextPacket = 0
            return
        if self.kexAlg == 'diffie-hellman-group1-sha1':
            # this is really KEXDH_INIT
            clientDHpublicKey, foo = getMP(packet)
            y = Util.number.getRandomNumber(512, randbytes.secureRandom)
            serverDHpublicKey = _MPpow(DH_GENERATOR, y, DH_PRIME)
            sharedSecret = _MPpow(clientDHpublicKey, y, DH_PRIME)
            h = sha1()
            h.update(NS(self.otherVersionString))
            h.update(NS(self.ourVersionString))
            h.update(NS(self.otherKexInitPayload))
            h.update(NS(self.ourKexInitPayload))
            h.update(NS(self.factory.publicKeys[self.keyAlg].blob()))
            h.update(MP(clientDHpublicKey))
            h.update(serverDHpublicKey)
            h.update(sharedSecret)
            exchangeHash = h.digest()
            self.sendPacket(
                MSG_KEXDH_REPLY,
                NS(self.factory.publicKeys[self.keyAlg].blob()) +
                serverDHpublicKey +
                NS(self.factory.privateKeys[self.keyAlg].sign(exchangeHash)))
            self._keySetup(sharedSecret, exchangeHash)
        elif self.kexAlg == 'diffie-hellman-group-exchange-sha1':
            self.dhGexRequest = packet
            ideal = struct.unpack('>L', packet)[0]
            self.g, self.p = self.factory.getDHPrime(ideal)
            self.sendPacket(MSG_KEX_DH_GEX_GROUP, MP(self.p) + MP(self.g))
        else:
            raise error.ConchError('bad kexalg: %s' % self.kexAlg)
Пример #15
0
 def test_signDSA(self):
     """
     Test that DSA keys return appropriate signatures.
     """
     data = 'data'
     key, sig = self._signDSA(data)
     sigData = sha1(data).digest()
     v = key.sign(sigData, '\x55' * 19)
     self.assertEquals(sig, common.NS('ssh-dss') + common.NS(
         Crypto.Util.number.long_to_bytes(v[0], 20) +
         Crypto.Util.number.long_to_bytes(v[1], 20)))
     return key, sig
Пример #16
0
 def test_pkcs1(self):
     """
     Test Public Key Cryptographic Standard #1 functions.
     """
     data = 'ABC'
     messageSize = 6
     self.assertEqual(keys.pkcs1Pad(data, messageSize),
             '\x01\xff\x00ABC')
     hash = sha1().digest()
     messageSize = 40
     self.assertEqual(keys.pkcs1Digest('', messageSize),
             '\x01\xff\xff\xff\x00' + keys.ID_SHA1 + hash)
Пример #17
0
 def test_signDSA(self):
     """
     Test that DSA keys return appropriate signatures.
     """
     data = 'data'
     key, sig = self._signDSA(data)
     sigData = sha1(data).digest()
     v = key.sign(sigData, '\x55' * 19)
     self.assertEqual(sig, common.NS('ssh-dss') + common.NS(
         Crypto.Util.number.long_to_bytes(v[0], 20) +
         Crypto.Util.number.long_to_bytes(v[1], 20)))
     return key, sig
        def onAuthSet(iq):
            """
            Called when the initializer sent the authentication request.

            The server checks the credentials and responds with an empty result
            signalling success.
            """
            self.assertEquals("user", unicode(iq.query.username))
            self.assertEquals(sha1("12345secret").hexdigest(), unicode(iq.query.digest).encode("utf-8"))
            self.assertEquals("resource", unicode(iq.query.resource))

            # Send server response
            response = xmlstream.toResponse(iq, "result")
            self.pipe.source.send(response)
Пример #19
0
def hashPassword(sid, password):
    """
    Create a SHA1-digest string of a session identifier and password.

    @param sid: The stream session identifier.
    @type sid: C{unicode}.
    @param password: The password to be hashed.
    @type password: C{unicode}.
    """
    if not isinstance(sid, unicode):
        raise TypeError("The session identifier must be a unicode object")
    if not isinstance(password, unicode):
        raise TypeError("The password must be a unicode object")
    input = u"%s%s" % (sid, password)
    return sha1(input.encode('utf-8')).hexdigest()
        def onAuthSet(iq):
            """
            Called when the initializer sent the authentication request.

            The server checks the credentials and responds with an empty result
            signalling success.
            """
            self.assertEquals('user', unicode(iq.query.username))
            self.assertEquals(sha1('12345secret').hexdigest(),
                              unicode(iq.query.digest).encode('utf-8'))
            self.assertEquals('resource', unicode(iq.query.resource))

            # Send server response
            response = xmlstream.toResponse(iq, 'result')
            self.pipe.source.send(response)
Пример #21
0
def hashPassword(sid, password):
    """
    Create a SHA1-digest string of a session identifier and password.

    @param sid: The stream session identifier.
    @type sid: C{unicode}.
    @param password: The password to be hashed.
    @type password: C{unicode}.
    """
    if not isinstance(sid, unicode):
        raise TypeError("The session identifier must be a unicode object")
    if not isinstance(password, unicode):
        raise TypeError("The password must be a unicode object")
    input = u"%s%s" % (sid, password)
    return sha1(input.encode('utf-8')).hexdigest()
Пример #22
0
    def verify(self, signature, data):
        """
        Returns true if the signature for data is valid for this Key.

        @type signature: C{str}
        @type data: C{str}
        @rtype: C{bool}
        """
        signatureType, signature = common.getNS(signature)
        if signatureType != self.sshType():
            return False
        if self.type() == 'RSA':
            numbers = common.getMP(signature)
            digest = pkcs1Digest(data, self.keyObject.size() / 8)
        elif self.type() == 'DSA':
            signature = common.getNS(signature)[0]
            numbers = [Util.number.bytes_to_long(n) for n in signature[:20],
                    signature[20:]]
            digest = sha1(data).digest()
        return self.keyObject.verify(digest, numbers)
Пример #23
0
    def testHandshake(self):
        """
        Test basic operations of component handshake.
        """

        d = self.init.initialize()

        # the initializer should have sent the handshake request

        handshake = self.output[-1]
        self.assertEqual('handshake', handshake.name)
        self.assertEqual('test:component', handshake.uri)
        self.assertEqual(sha1("%s%s" % ('12345', 'secret')).hexdigest(),
                          unicode(handshake))

        # successful authentication

        handshake.children = []
        self.xmlstream.dataReceived(handshake.toXml())

        return d
Пример #24
0
    def testHandshake(self):
        """
        Test basic operations of component handshake.
        """

        d = self.init.initialize()

        # the initializer should have sent the handshake request

        handshake = self.output[-1]
        self.assertEquals('handshake', handshake.name)
        self.assertEquals('test:component', handshake.uri)
        self.assertEquals(
            sha1("%s%s" % ('12345', 'secret')).hexdigest(), unicode(handshake))

        # successful authentication

        handshake.children = []
        self.xmlstream.dataReceived(handshake.toXml())

        return d
Пример #25
0
    def ssh_KEX_DH_GEX_INIT(self, packet):
        """
        Called when we get a MSG_KEX_DH_GEX_INIT message.  Payload::
            integer e (client DH public key)

        We send the MSG_KEX_DH_GEX_REPLY message with our host key and
        signature.
        """
        clientDHpublicKey, foo = getMP(packet)
        # TODO: we should also look at the value they send to us and reject
        # insecure values of f (if g==2 and f has a single '1' bit while the
        # rest are '0's, then they must have used a small y also).

        # TODO: This could be computed when self.p is set up
        #  or do as openssh does and scan f for a single '1' bit instead

        pSize = Util.number.size(self.p)
        y = Util.number.getRandomNumber(pSize, randbytes.secureRandom)

        serverDHpublicKey = _MPpow(self.g, y, self.p)
        sharedSecret = _MPpow(clientDHpublicKey, y, self.p)
        h = sha1()
        h.update(NS(self.otherVersionString))
        h.update(NS(self.ourVersionString))
        h.update(NS(self.otherKexInitPayload))
        h.update(NS(self.ourKexInitPayload))
        h.update(NS(self.factory.publicKeys[self.keyAlg].blob()))
        h.update(self.dhGexRequest)
        h.update(MP(self.p))
        h.update(MP(self.g))
        h.update(MP(clientDHpublicKey))
        h.update(serverDHpublicKey)
        h.update(sharedSecret)
        exchangeHash = h.digest()
        self.sendPacket(
            MSG_KEX_DH_GEX_REPLY,
            NS(self.factory.publicKeys[self.keyAlg].blob()) +
            serverDHpublicKey +
            NS(self.factory.privateKeys[self.keyAlg].sign(exchangeHash)))
        self._keySetup(sharedSecret, exchangeHash)
Пример #26
0
    def ssh_KEX_DH_GEX_INIT(self, packet):
        """
        Called when we get a MSG_KEX_DH_GEX_INIT message.  Payload::
            integer e (client DH public key)

        We send the MSG_KEX_DH_GEX_REPLY message with our host key and
        signature.
        """
        clientDHpublicKey, foo = getMP(packet)
        # TODO: we should also look at the value they send to us and reject
        # insecure values of f (if g==2 and f has a single '1' bit while the
        # rest are '0's, then they must have used a small y also).

        # TODO: This could be computed when self.p is set up
        #  or do as openssh does and scan f for a single '1' bit instead

        pSize = Util.number.size(self.p)
        y = Util.number.getRandomNumber(pSize, randbytes.secureRandom)

        serverDHpublicKey = _MPpow(self.g, y, self.p)
        sharedSecret = _MPpow(clientDHpublicKey, y, self.p)
        h = sha1()
        h.update(NS(self.otherVersionString))
        h.update(NS(self.ourVersionString))
        h.update(NS(self.otherKexInitPayload))
        h.update(NS(self.ourKexInitPayload))
        h.update(NS(self.factory.publicKeys[self.keyAlg].blob()))
        h.update(self.dhGexRequest)
        h.update(MP(self.p))
        h.update(MP(self.g))
        h.update(MP(clientDHpublicKey))
        h.update(serverDHpublicKey)
        h.update(sharedSecret)
        exchangeHash = h.digest()
        self.sendPacket(
            MSG_KEX_DH_GEX_REPLY,
            NS(self.factory.publicKeys[self.keyAlg].blob()) +
            serverDHpublicKey +
            NS(self.factory.privateKeys[self.keyAlg].sign(exchangeHash)))
        self._keySetup(sharedSecret, exchangeHash)
Пример #27
0
    def sign(self, data):
        """
        Returns a signature with this Key.

        @type data: C{str}
        @rtype: C{str}
        """
        if self.type() == 'RSA':
            digest = pkcs1Digest(data, self.keyObject.size()/8)
            signature = self.keyObject.sign(digest, '')[0]
            ret = common.NS(Util.number.long_to_bytes(signature))
        elif self.type() == 'DSA':
            digest = sha1(data).digest()
            randomBytes = randbytes.secureRandom(19)
            sig = self.keyObject.sign(digest, randomBytes)
            # SSH insists that the DSS signature blob be two 160-bit integers
            # concatenated together. The sig[0], [1] numbers from obj.sign
            # are just numbers, and could be any length from 0 to 160 bits.
            # Make sure they are padded out to 160 bits (20 bytes each)
            ret = common.NS(Util.number.long_to_bytes(sig[0], 20) +
                             Util.number.long_to_bytes(sig[1], 20))
        return common.NS(self.sshType()) + ret
Пример #28
0
    def sign(self, data):
        """
        Returns a signature with this Key.

        @type data: C{str}
        @rtype: C{str}
        """
        if self.type() == 'RSA':
            digest = pkcs1Digest(data, self.keyObject.size() / 8)
            signature = self.keyObject.sign(digest, '')[0]
            ret = common.NS(Util.number.long_to_bytes(signature))
        elif self.type() == 'DSA':
            digest = sha1(data).digest()
            randomBytes = randbytes.secureRandom(19)
            sig = self.keyObject.sign(digest, randomBytes)
            # SSH insists that the DSS signature blob be two 160-bit integers
            # concatenated together. The sig[0], [1] numbers from obj.sign
            # are just numbers, and could be any length from 0 to 160 bits.
            # Make sure they are padded out to 160 bits (20 bytes each)
            ret = common.NS(
                Util.number.long_to_bytes(sig[0], 20) +
                Util.number.long_to_bytes(sig[1], 20))
        return common.NS(self.sshType()) + ret
Пример #29
0
    def testAuth(self):
        self.authComplete = False
        outlist = []

        ca = component.ConnectComponentAuthenticator("cjid", "secret")
        xs = xmlstream.XmlStream(ca)
        xs.transport = DummyTransport(outlist)

        xs.addObserver(xmlstream.STREAM_AUTHD_EVENT,
                       self.authPassed)

        # Go...
        xs.connectionMade()
        xs.dataReceived("<stream:stream xmlns='jabber:component:accept' xmlns:stream='http://etherx.jabber.org/streams' from='cjid' id='12345'>")

        # Calculate what we expect the handshake value to be
        hv = sha1("%s%s" % ("12345", "secret")).hexdigest()

        self.assertEqual(outlist[1], "<handshake>%s</handshake>" % (hv))

        xs.dataReceived("<handshake/>")

        self.assertEqual(self.authComplete, True)
Пример #30
0
def hashPassword(sid, password):
    """
    Create a SHA1-digest string of a session identifier and password.
    """
    from twisted.python.hashlib import sha1
    return sha1("%s%s" % (sid, password)).hexdigest()
Пример #31
0
def _secureEnoughString():
    """
    Create a pseudorandom, 16-character string for use in secure filenames.
    """
    return armor(sha1(randomBytes(64)).digest())[:16]
Пример #32
0
 def image_key(self, url):
     year,month = url.split('/')[-5],url.split('/')[-6]
     image_guid = hashlib.sha1(url).hexdigest()
     img_path = "%s/%s/%s" % (year,month,'tt')
     return '%s/%s.jpg' % (img_path, self.image_name)