Ticket #2763: hashlib.patch

File hashlib.patch, 44.3 KB (added by Wilfredo Sánchez Vega, 13 years ago)
  • twisted/python/filepath.py

     
    99import os
    1010import errno
    1111import random
    12 import sha
     12try:
     13    from hashlib import sha1 as sha
     14except ImportError:
     15    from sha import sha
    1316import base64
    1417
    1518from os.path import isabs, exists, normpath, abspath, splitext
     
    120123    """
    121124    Create a pseudorandom, 16-character string for use in secure filenames.
    122125    """
    123     return armor(sha.new(randomBytes(64)).digest())[:16]
     126    return armor(sha(randomBytes(64)).digest())[:16]
    124127
    125128
    126129
  • twisted/python/otp.py

     
    4848        l = l / 256L
    4949    return result
    5050       
    51 import md5, sha
     51try:
     52    from hashlib import md5, sha1 as sha
     53except ImportError:
     54    from md5 import md5
     55    from sha import sha
    5256hashid = {md5: 'md5', sha: 'sha1'}
    5357
    5458INITIALSEQUENCE = 1000
     
    120124
    121125    def hashUpdate(self, digest):
    122126        "Run through the hash and fold to 64 bit"
    123         h = self.hash.new(digest)
     127        h = self.hash(digest)
    124128        return self.foldDigest(h.digest())
    125129   
    126130    def generateOTP(self, seed, passwd, sequence):
  • twisted/python/test/test_zipstream.py

     
    66"""
    77import sys
    88import random
    9 import md5
     9try:
     10    from hashlib import md5
     11except ImportError:
     12    from md5 import md5
    1013import zipfile
    1114
    1215from twisted.python import zipstream, filepath
     
    347350        unzipIterChunky should unzip the given number of bytes per iteration.
    348351        """
    349352        junk = ' '.join([str(random.random()) for n in xrange(1000)])
    350         junkmd5 = md5.new(junk).hexdigest()
     353        junkmd5 = md5(junk).hexdigest()
    351354
    352355        tempdir = filepath.FilePath(self.mktemp())
    353356        tempdir.makedirs()
     
    364367        for r in uziter:
    365368            pass
    366369        self.assertEqual(r, 0)
    367         newmd5 = md5.new(
     370        newmd5 = md5(
    368371            tempdir.child("zipstreamjunk").open().read()).hexdigest()
    369372        self.assertEqual(newmd5, junkmd5)
    370373
  • twisted/protocols/sip.py

     
    1414import socket
    1515import random
    1616import time
    17 import md5
     17try:
     18    from hashlib import md5
     19except ImportError:
     20    from md5 import md5
    1821import sys
    1922from zope.interface import implements, Interface
    2023
     
    132135    pszNonce,
    133136    pszCNonce,
    134137):
    135     m = md5.md5()
     138    m = md5()
    136139    m.update(pszUserName)
    137140    m.update(":")
    138141    m.update(pszRealm)
     
    140143    m.update(pszPassword)
    141144    HA1 = m.digest()
    142145    if pszAlg == "md5-sess":
    143         m = md5.md5()
     146        m = md5()
    144147        m.update(HA1)
    145148        m.update(":")
    146149        m.update(pszNonce)
     
    159162    pszDigestUri,
    160163    pszHEntity,
    161164):
    162     m = md5.md5()
     165    m = md5()
    163166    m.update(pszMethod)
    164167    m.update(":")
    165168    m.update(pszDigestUri)
     
    168171        m.update(pszHEntity)
    169172    HA2 = m.digest().encode('hex')
    170173   
    171     m = md5.md5()
     174    m = md5()
    172175    m.update(HA1)
    173176    m.update(":")
    174177    m.update(pszNonce)
  • twisted/conch/test/test_transport.py

     
    55Tests for ssh/transport.py and the classes therein.
    66"""
    77
    8 import md5, sha
     8try:
     9    from hashlib import md5, sha1 as sha
     10except ImportError:
     11    from md5 import md5
     12    from sha import sha
    913
    1014try:
    1115    import Crypto.Cipher.DES3
     
    856860        """
    857861        self.proto.sessionID = 'EF'
    858862
    859         k1 = sha.new('AB' + 'CD'
     863        k1 = sha('AB' + 'CD'
    860864                     + 'K' + self.proto.sessionID).digest()
    861         k2 = sha.new('ABCD' + k1).digest()
     865        k2 = sha('ABCD' + k1).digest()
    862866        self.assertEquals(self.proto._getKey('K', 'AB', 'CD'), k1 + k2)
    863867
    864868
     
    11091113        f = common._MPpow(transport.DH_GENERATOR, y, transport.DH_PRIME)
    11101114        sharedSecret = common._MPpow(e, y, transport.DH_PRIME)
    11111115
    1112         h = sha.new()
     1116        h = sha()
    11131117        h.update(common.NS(self.proto.ourVersionString) * 2)
    11141118        h.update(common.NS(self.proto.ourKexInitPayload) * 2)
    11151119        h.update(common.NS(self.proto.factory.publicKeys['ssh-rsa'].blob()))
     
    11901194        y = common.getMP('\x00\x00\x00\x80' + '\x99' * 128)[0]
    11911195        f = common._MPpow(self.proto.g, y, self.proto.p)
    11921196        sharedSecret = common._MPpow(e, y, self.proto.p)
    1193         h = sha.new()
     1197        h = sha()
    11941198        h.update(common.NS(self.proto.ourVersionString) * 2)
    11951199        h.update(common.NS(self.proto.ourKexInitPayload) * 2)
    11961200        h.update(common.NS(self.proto.factory.publicKeys['ssh-rsa'].blob()))
     
    12211225        y = common.getMP('\x00\x00\x00\x80' + '\x99' * 128)[0]
    12221226        f = common._MPpow(self.proto.g, y, self.proto.p)
    12231227        sharedSecret = common._MPpow(e, y, self.proto.p)
    1224         h = sha.new()
     1228        h = sha()
    12251229        h.update(common.NS(self.proto.ourVersionString) * 2)
    12261230        h.update(common.NS(self.proto.ourKexInitPayload) * 2)
    12271231        h.update(common.NS(self.proto.factory.publicKeys['ssh-rsa'].blob()))
     
    13601364        self.calledVerifyHostKey = True
    13611365        self.assertEquals(pubKey, self.blob)
    13621366        self.assertEquals(fingerprint.replace(':', ''),
    1363                           md5.new(pubKey).hexdigest())
     1367                          md5(pubKey).hexdigest())
    13641368        return defer.succeed(True)
    13651369
    13661370
     
    14271431
    14281432        sharedSecret = common._MPpow(transport.DH_GENERATOR,
    14291433                                     self.proto.x, transport.DH_PRIME)
    1430         h = sha.new()
     1434        h = sha()
    14311435        h.update(common.NS(self.proto.ourVersionString) * 2)
    14321436        h.update(common.NS(self.proto.ourKexInitPayload) * 2)
    14331437        h.update(common.NS(self.blob))
     
    14761480
    14771481        self.test_KEX_DH_GEX_GROUP()
    14781482        sharedSecret = common._MPpow(3, self.proto.x, self.proto.p)
    1479         h = sha.new()
     1483        h = sha()
    14801484        h.update(common.NS(self.proto.ourVersionString) * 2)
    14811485        h.update(common.NS(self.proto.ourKexInitPayload) * 2)
    14821486        h.update(common.NS(self.blob))
  • twisted/conch/test/test_keys.py

     
    1212from twisted.conch.test import keydata
    1313from twisted.python import randbytes
    1414from twisted.trial import unittest
    15 import sha, os, base64
     15import os, base64
     16try:
     17    from hashlib import sha1 as sha
     18except ImportError:
     19    from sha import sha
    1620
    1721class SSHKeysHandlingTestCase(unittest.TestCase):
    1822    """
     
    316320        messageSize = 6
    317321        self.assertEquals(keys.pkcs1Pad(data, messageSize),
    318322                '\x01\xff\x00ABC')
    319         hash = sha.new().digest()
     323        hash = sha().digest()
    320324        messageSize = 40
    321325        self.assertEquals(keys.pkcs1Digest('', messageSize),
    322326                '\x01\xff\xff\xff\x00' + keys.ID_SHA1 + hash)
     
    348352        """
    349353        data = 'data'
    350354        key, sig = self._signDSA(data)
    351         sigData = sha.new(data).digest()
     355        sigData = sha(data).digest()
    352356        v = key.sign(sigData, '\x55' * 19)
    353357        self.assertEquals(sig, common.NS('ssh-dss') + common.NS(
    354358            Crypto.Util.number.long_to_bytes(v[0], 20) +
  • twisted/conch/scripts/ckeygen.py

     
    1010from twisted.conch.ssh import keys
    1111from twisted.python import log, usage, randbytes
    1212
    13 import sys, os, getpass, md5, socket
     13import sys, os, getpass, socket
     14try:
     15    from hashlib import md5
     16except ImportError:
     17    from md5 import md5
    1418if getpass.getpass == getpass.unix_getpass:
    1519    try:
    1620        import termios # hack around broken termios
     
    99103        obj = keys.getPublicKeyObject(string)
    100104        print '%s %s %s' % (
    101105            obj.size()+1,
    102             ':'.join(['%02x' % ord(x) for x in md5.new(string).digest()]),
     106            ':'.join(['%02x' % ord(x) for x in md5(string).digest()]),
    103107            os.path.basename(options['filename']))
    104108    except:
    105109        sys.exit('bad key')
     
    173177    print 'Your identification has been saved in %s' % options['filename']
    174178    print 'Your public key has been saved in %s.pub' % options['filename']
    175179    print 'The key fingerprint is:'
    176     print ':'.join(['%02x' % ord(x) for x in md5.new(pubKey).digest()])
     180    print ':'.join(['%02x' % ord(x) for x in md5(pubKey).digest()])
    177181
    178182if __name__ == '__main__':
    179183    run()
  • twisted/conch/ssh/transport.py

     
    1313
    1414# base library imports
    1515import struct
    16 import md5
    17 import sha
     16try:
     17    from hashlib import md5, sha1 as sha
     18except ImportError:
     19    from md5 import md5
     20    from sha import sha
    1821import zlib
    1922import array
    2023
     
    532535        @type sharedSecret: C{str}
    533536        @type exchangeHash: C{str}
    534537        """
    535         k1 = sha.new(sharedSecret + exchangeHash + c + self.sessionID)
     538        k1 = sha(sharedSecret + exchangeHash + c + self.sessionID)
    536539        k1 = k1.digest()
    537         k2 = sha.new(sharedSecret + exchangeHash + k1).digest()
     540        k2 = sha(sharedSecret + exchangeHash + k1).digest()
    538541        return k1 + k2
    539542
    540543
     
    723726            y = Util.number.getRandomNumber(512, randbytes.secureRandom)
    724727            serverDHpublicKey = _MPpow(DH_GENERATOR, y, DH_PRIME)
    725728            sharedSecret = _MPpow(clientDHpublicKey, y, DH_PRIME)
    726             h = sha.new()
     729            h = sha()
    727730            h.update(NS(self.otherVersionString))
    728731            h.update(NS(self.ourVersionString))
    729732            h.update(NS(self.otherKexInitPayload))
     
    792795
    793796        serverDHpublicKey = _MPpow(self.g, y, self.p)
    794797        sharedSecret = _MPpow(clientDHpublicKey, y, self.p)
    795         h = sha.new()
     798        h = sha()
    796799        h.update(NS(self.otherVersionString))
    797800        h.update(NS(self.ourVersionString))
    798801        h.update(NS(self.otherKexInitPayload))
     
    933936            f, packet = getMP(packet)
    934937            signature, packet = getNS(packet)
    935938            fingerprint = ':'.join([ch.encode('hex') for ch in
    936                                     md5.new(pubKey).digest()])
     939                                    md5(pubKey).digest()])
    937940            d = self.verifyHostKey(pubKey, fingerprint)
    938941            d.addCallback(self._continueKEXDH_REPLY, pubKey, f, signature)
    939942            d.addErrback(
     
    962965        """
    963966        serverKey = keys.Key.fromString(pubKey)
    964967        sharedSecret = _MPpow(f, self.x, DH_PRIME)
    965         h = sha.new()
     968        h = sha()
    966969        h.update(NS(self.ourVersionString))
    967970        h.update(NS(self.otherVersionString))
    968971        h.update(NS(self.ourKexInitPayload))
     
    992995        f, packet = getMP(packet)
    993996        signature, packet = getNS(packet)
    994997        fingerprint = ':'.join(map(lambda c: '%02x'%ord(c),
    995             md5.new(pubKey).digest()))
     998            md5(pubKey).digest()))
    996999        d = self.verifyHostKey(pubKey, fingerprint)
    9971000        d.addCallback(self._continueGEX_REPLY, pubKey, f, signature)
    9981001        d.addErrback(
     
    10151018        """
    10161019        serverKey = keys.Key.fromString(pubKey)
    10171020        sharedSecret = _MPpow(f, self.x, self.p)
    1018         h = sha.new()
     1021        h = sha()
    10191022        h.update(NS(self.ourVersionString))
    10201023        h.update(NS(self.otherVersionString))
    10211024        h.update(NS(self.ourKexInitPayload))
     
    12231226            return _DummyCipher()
    12241227        mod = __import__('Crypto.Cipher.%s'%modName, {}, {}, 'x')
    12251228        if counterMode:
    1226             return mod.new(key[:keySize], mod.MODE_CTR, iv[:mod.block_size],
    1227                            counter=_Counter(iv, mod.block_size))
     1229            return mod(key[:keySize], mod.MODE_CTR, iv[:mod.block_size],
     1230                       counter=_Counter(iv, mod.block_size))
    12281231        else:
    1229             return mod.new(key[:keySize], mod.MODE_CBC, iv[:mod.block_size])
     1232            return mod(key[:keySize], mod.MODE_CBC, iv[:mod.block_size])
    12301233
    12311234
    12321235    def _getMAC(self, mac, key):
     
    12441247        if not mod:
    12451248            return (None, '', '', 0)
    12461249        #if not hasattr(mod, 'digest_size'):
    1247         #     ds = len(mod.new().digest())
     1250        #     ds = len(mod().digest())
    12481251        #else:
    1249         ds = mod.digest_size
     1252        ds = mod().digest_size
    12501253        key = key[:ds] + '\x00' * (64 - ds)
    12511254        i = XOR.new('\x36').encrypt(key)
    12521255        o = XOR.new('\x5c').encrypt(key)
     
    12871290            return ''
    12881291        data = struct.pack('>L', seqid) + data
    12891292        mod, i, o, ds = self.outMAC
    1290         inner = mod.new(i + data)
    1291         outer = mod.new(o + inner.digest())
     1293        inner = mod(i + data)
     1294        outer = mod(o + inner.digest())
    12921295        return outer.digest()
    12931296
    12941297
     
    13091312            return mac == ''
    13101313        data = struct.pack('>L', seqid) + data
    13111314        mod, i, o, ds = self.inMAC
    1312         inner = mod.new(i + data)
    1313         outer = mod.new(o + inner.digest())
     1315        inner = mod(i + data)
     1316        outer = mod(o + inner.digest())
    13141317        return mac == outer.digest()
    13151318
    13161319
  • twisted/conch/ssh/keys.py

     
    1212
    1313# base library imports
    1414import base64
    15 import sha, md5
     15try:
     16    from hashlib import md5, sha1 as sha
     17except ImportError:
     18    from md5 import md5
     19    from sha import sha
    1620import warnings
    1721
    1822# external library imports
     
    207211                len(ivdata), 2)])
    208212            if not passphrase:
    209213                raise EncryptedKeyError('encrypted key with no passphrase')
    210             ba = md5.new(passphrase + iv).digest()
    211             bb = md5.new(ba + passphrase + iv).digest()
     214            ba = md5(passphrase + iv).digest()
     215            bb = md5(ba + passphrase + iv).digest()
    212216            decKey = (ba + bb)[:24]
    213217            b64Data = base64.decodestring(''.join(lines[3:-1]))
    214218            keyData = DES3.new(decKey, DES3.MODE_CBC, iv).decrypt(b64Data)
     
    575579                hexiv = ''.join(['%02X' % ord(x) for x in iv])
    576580                lines.append('Proc-Type: 4,ENCRYPTED')
    577581                lines.append('DEK-Info: DES-EDE3-CBC,%s\n' % hexiv)
    578                 ba = md5.new(extra + iv).digest()
    579                 bb = md5.new(ba + extra + iv).digest()
     582                ba = md5(extra + iv).digest()
     583                bb = md5(ba + extra + iv).digest()
    580584                encKey = (ba + bb)[:24]
    581585            asn1Data = asn1.pack([objData])
    582586            if extra:
     
    659663            signature = self.keyObject.sign(digest, '')[0]
    660664            ret = common.NS(Util.number.long_to_bytes(signature))
    661665        elif self.type() == 'DSA':
    662             digest = sha.new(data).digest()
     666            digest = sha(data).digest()
    663667            randomBytes = randbytes.secureRandom(19)
    664668            sig = self.keyObject.sign(digest, randomBytes)
    665669            # SSH insists that the DSS signature blob be two 160-bit integers
     
    688692            signature = common.getNS(signature)[0]
    689693            numbers = [Util.number.bytes_to_long(n) for n in signature[:20],
    690694                    signature[20:]]
    691             digest = sha.new(data).digest()
     695            digest = sha(data).digest()
    692696        return self.keyObject.verify(digest, numbers)
    693697
    694698def getPublicKeyString(filename=None, line=0, data=''):
     
    841845    @type data: C{str}
    842846    @type messageLength: C{str}
    843847    """
    844     digest = sha.new(data).digest()
     848    digest = sha(data).digest()
    845849    return pkcs1Pad(ID_SHA1+digest, messageLength)
    846850
    847851def lenSig(obj):
  • twisted/words/test/test_jabbercomponent.py

     
    55Tests for L{twisted.words.protocols.jabber.component}
    66"""
    77
    8 import sha
     8try:
     9    from hashlib import sha1 as sha
     10except ImportError:
     11    from sha import sha
    912
    1013from twisted.python import failure
    1114from twisted.trial import unittest
     
    5053        handshake = self.output[-1]
    5154        self.assertEquals('handshake', handshake.name)
    5255        self.assertEquals('test:component', handshake.uri)
    53         self.assertEquals(sha.new("%s%s" % ('12345', 'secret')).hexdigest(),
     56        self.assertEquals(sha("%s%s" % ('12345', 'secret')).hexdigest(),
    5457                          unicode(handshake))
    5558
    5659        # successful authentication
     
    8083        xs.dataReceived("<stream:stream xmlns='jabber:component:accept' xmlns:stream='http://etherx.jabber.org/streams' from='cjid' id='12345'>")
    8184
    8285        # Calculate what we expect the handshake value to be
    83         hv = sha.new("%s%s" % ("12345", "secret")).hexdigest()
     86        hv = sha("%s%s" % ("12345", "secret")).hexdigest()
    8487
    8588        self.assertEquals(outlist[1], "<handshake>%s</handshake>" % (hv))
    8689
  • twisted/words/test/test_jabberclient.py

     
    55Tests for L{twisted.words.protocols.jabber.client}
    66"""
    77
    8 import sha
     8try:
     9    from hashlib import sha1 as sha
     10except ImportError:
     11    from sha import sha
    912from twisted.trial import unittest
    1013from twisted.words.protocols.jabber import client, error, jid, xmlstream
    1114from twisted.words.protocols.jabber.sasl import SASLInitiatingInitializer
     
    117120        self.assertEquals(('jabber:iq:auth', 'query'),
    118121                          (iq.children[0].uri, iq.children[0].name))
    119122        self.assertEquals('user', unicode(iq.query.username))
    120         self.assertEquals(sha.new('12345secret').hexdigest(),
     123        self.assertEquals(sha('12345secret').hexdigest(),
    121124                          unicode(iq.query.digest))
    122125        self.assertEquals('resource', unicode(iq.query.resource))
    123126
  • twisted/words/protocols/msn.py

     
    7373@author: Sam Jordan
    7474"""
    7575
    76 import types, operator, os, md5
     76import types, operator, os
     77try:
     78    from hashlib import md5
     79except ImportError:
     80    from md5 import md5
    7781from random import randint
    7882from urllib import quote, unquote
    7983
     
    856860    def handle_CHL(self, params):
    857861        checkParamLen(len(params), 2, 'CHL')
    858862        self.sendLine("QRY %s msmsgs@msnmsgr.com 32" % self._nextTransactionID())
    859         self.transport.write(md5.md5(params[1] + MSN_CHALLENGE_STR).hexdigest())
     863        self.transport.write(md5(params[1] + MSN_CHALLENGE_STR).hexdigest())
    860864
    861865    def handle_QRY(self, params):
    862866        pass
  • twisted/words/protocols/jabber/sasl_mechanisms.py

     
    77Protocol agnostic implementations of SASL authentication mechanisms.
    88"""
    99
    10 import md5, binascii, random, time, os
     10import binascii, random, time, os
     11try:
     12    from hashlib import md5
     13except ImportError:
     14    from md5 import md5
    1115
    1216from zope.interface import Interface, Attribute, implements
    1317
     
    178182        """
    179183
    180184        def H(s):
    181             return md5.new(s).digest()
     185            return md5(s).digest()
    182186
    183187        def HEX(n):
    184188            return binascii.b2a_hex(n)
     
    221225
    222226
    223227    def _gen_nonce(self):
    224         return md5.new("%s:%s:%s" % (str(random.random()) , str(time.gmtime()),str(os.getpid()))).hexdigest()
     228        return md5("%s:%s:%s" % (str(random.random()) , str(time.gmtime()),str(os.getpid()))).hexdigest()
  • twisted/words/protocols/jabber/xmlstream.py

     
    4242    """
    4343    Create a SHA1-digest string of a session identifier and password.
    4444    """
    45     import sha
    46     return sha.new("%s%s" % (sid, password)).hexdigest()
     45    try:
     46        from hashlib import sha1 as sha
     47    except ImportError:
     48        from sha import sha
     49    return sha("%s%s" % (sid, password)).hexdigest()
    4750
    4851
    4952
  • twisted/words/protocols/oscar.py

     
    1515from twisted.python import log
    1616
    1717import struct
    18 import md5
     18try:
     19    from hashlib import md5
     20except ImportError:
     21    from md5 import md5
    1922import string
    2023import socket
    2124import random
     
    6265    return dict,data
    6366
    6467def encryptPasswordMD5(password,key):
    65     m=md5.new()
     68    m=md5()
    6669    m.update(key)
    67     m.update(md5.new(password).digest())
     70    m.update(md5(password).digest())
    6871    m.update("AOL Instant Messenger (SM)")
    6972    return m.digest()
    7073
  • twisted/web2/test/test_httpauth.py

     
    1 import md5
     1try:
     2    from hashlib import md5
     3except ImportError:
     4    from md5 import md5
    25from twisted.internet import address
    36from twisted.trial import unittest
    47from twisted.cred import error
     
    263266        creds = self.credentialFactory.decode(clientResponse, _trivial_GET)
    264267
    265268        self.failUnless(creds.checkHash(
    266                 md5.md5('username:test realm:password').hexdigest()))
     269                md5('username:test realm:password').hexdigest()))
    267270
    268271        self.failIf(creds.checkHash(
    269                 md5.md5('username:test realm:bogus').hexdigest()))
     272                md5('username:test realm:bogus').hexdigest()))
    270273
    271274    def test_invalidOpaque(self):
    272275        """
     
    364367        key = '%s,%s,%s' % (challenge['nonce'],
    365368                            clientAddress.host,
    366369                            '-137876876')
    367         digest = md5.new(key + credentialFactory.privateKey).hexdigest()
     370        digest = md5(key + credentialFactory.privateKey).hexdigest()
    368371        ekey = key.encode('base64')
    369372
    370373        oldNonceOpaque = '%s-%s' % (digest, ekey.strip('\n'))
     
    390393                            clientAddress.host,
    391394                            '0')
    392395
    393         digest = md5.new(key + 'this is not the right pkey').hexdigest()
     396        digest = md5(key + 'this is not the right pkey').hexdigest()
    394397
    395398        badChecksum = '%s-%s' % (digest,
    396399                                 key.encode('base64').strip('\n'))
  • twisted/web2/server.py

     
    522522    def _cbFinishRender(self, result):
    523523        def filterit(response, f):
    524524            if (hasattr(f, 'handleErrors') or
    525                 (response.code >= 200 and response.code < 300 and response.code != 204)):
     525                (response.code >= 200 and response.code < 300)):
    526526                return f(self, response)
    527527            else:
    528528                return response
  • twisted/web2/auth/digest.py

     
    1212
    1313from twisted.web2.auth.interfaces import ICredentialFactory
    1414
    15 import md5, sha
     15try:
     16    from hashlib import md5, sha1 as sha
     17except ImportError:
     18    from md5 import md5
     19    from sha import sha
    1620import random, sys
    1721
    1822# The digest math
    1923
    2024algorithms = {
    21     'md5': md5.new,
    22     'md5-sess': md5.new,
    23     'sha': sha.new,
     25    'md5': md5,
     26    'md5-sess': md5,
     27    'sha': sha,
    2428}
    2529
    2630# DigestCalcHA1
     
    228232        # Now, what we do is encode the nonce, client ip and a timestamp
    229233        # in the opaque value with a suitable digest
    230234        key = "%s,%s,%s" % (nonce, clientip, str(int(self._getTime())))
    231         digest = md5.new(key + self.privateKey).hexdigest()
     235        digest = md5(key + self.privateKey).hexdigest()
    232236        ekey = key.encode('base64')
    233237        return "%s-%s" % (digest, ekey.strip('\n'))
    234238
     
    275279                'Invalid response, incompatible opaque/nonce too old')
    276280
    277281        # Verify the digest
    278         digest = md5.new(key + self.privateKey).hexdigest()
     282        digest = md5(key + self.privateKey).hexdigest()
    279283        if digest != opaqueParts[0]:
    280284            raise error.LoginFailed('Invalid response, invalid opaque value')
    281285
  • twisted/web2/static.py

     
    99# System Imports
    1010import os, time, stat
    1111import tempfile
    12 import md5
    1312
    1413# Sibling Imports
    1514from twisted.web2 import http_headers, resource
  • twisted/persisted/sob.py

     
    99Maintainer: Moshe Zadka
    1010"""
    1111
    12 import os, md5, sys
     12import os, sys
    1313try:
     14    from hashlib import md5
     15except ImportError:
     16    from md5 import md5
     17try:
    1418    import cPickle as pickle
    1519except ImportError:
    1620    import pickle
     
    3135    leftover = len(data) % cipher.block_size
    3236    if leftover:
    3337        data += ' '*(cipher.block_size - leftover)
    34     return cipher.new(md5.new(passphrase).digest()[:16]).encrypt(data)
     38    return cipher.new(md5(passphrase).digest()[:16]).encrypt(data)
    3539
    3640def _decrypt(passphrase, data):
    3741    from Crypto.Cipher import AES
    38     return AES.new(md5.new(passphrase).digest()[:16]).decrypt(data)
     42    return AES.new(md5(passphrase).digest()[:16]).decrypt(data)
    3943
    4044
    4145class IPersistable(Interface):
  • twisted/news/database.py

     
    2121from twisted.enterprise import adbapi
    2222from twisted.persisted import dirdbm
    2323
    24 import getpass, pickle, time, socket, md5
     24import getpass, pickle, time, socket
     25try:
     26    from hashlib import md5
     27except ImportError:
     28    from md5 import md5
    2529import os
    2630import StringIO
    2731from zope.interface import implements, Interface
     
    5357
    5458        if not self.getHeader('Message-ID'):
    5559            s = str(time.time()) + self.body
    56             id = hexdigest(md5.md5(s)) + '@' + socket.gethostname()
     60            id = hexdigest(md5(s)) + '@' + socket.gethostname()
    5761            self.putHeader('Message-ID', '<%s>' % id)
    5862
    5963        if not self.getHeader('Bytes'):
  • twisted/web/server.py

     
    507507        """
    508508        (internal) Generate an opaque, unique ID for a user's session.
    509509        """
    510         import md5, random
     510        try:
     511            from hashlib import md5
     512        except ImportError:
     513            from md5 import md5
     514        import random
    511515        self.counter = self.counter + 1
    512         return md5.new("%s_%s" % (str(random.random()) , str(self.counter))).hexdigest()
     516        return md5("%s_%s" % (str(random.random()) , str(self.counter))).hexdigest()
    513517
    514518    def makeSession(self):
    515519        """
  • twisted/web/test/test_httpauth.py

     
    55Tests for L{twisted.web._auth}.
    66"""
    77
    8 import md5, sha
     8try:
     9    from hashlib import md5, sha1 as sha
     10except ImportError:
     11    from md5 import md5
     12    from sha import sha
    913
    1014from zope.interface import implements
    1115from zope.interface.verify import verifyObject
     
    181185            self.algorithm, self.realm)
    182186
    183187
    184     def test_MD5HashA1(self, _algorithm='md5', _hash=md5.md5):
     188    def test_MD5HashA1(self, _algorithm='md5', _hash=md5):
    185189        """
    186190        L{calcHA1} accepts the C{'md5'} algorithm and returns an MD5 hash of
    187191        its parameters, excluding the nonce and cnonce.
     
    203207        hashA1 = calcHA1('md5-sess', self.username, self.realm, self.password,
    204208                         nonce, self.cnonce)
    205209        a1 = '%s:%s:%s' % (self.username, self.realm, self.password)
    206         ha1 = md5.md5(a1).digest()
     210        ha1 = md5(a1).digest()
    207211        a1 = '%s:%s:%s' % (ha1, nonce, self.cnonce)
    208         expected = md5.md5(a1).hexdigest()
     212        expected = md5(a1).hexdigest()
    209213        self.assertEqual(hashA1, expected)
    210214
    211215
     
    214218        L{calcHA1} accepts the C{'sha'} algorithm and returns a SHA hash of its
    215219        parameters, excluding the nonce and cnonce.
    216220        """
    217         self.test_MD5HashA1('sha', sha.sha)
     221        self.test_MD5HashA1('sha', sha)
    218222
    219223
    220     def test_MD5HashA2Auth(self, _algorithm='md5', _hash=md5.md5):
     224    def test_MD5HashA2Auth(self, _algorithm='md5', _hash=md5):
    221225        """
    222226        L{calcHA2} accepts the C{'md5'} algorithm and returns an MD5 hash of
    223227        its arguments, excluding the entity hash for QOP other than
     
    230234        self.assertEqual(hashA2, expected)
    231235
    232236
    233     def test_MD5HashA2AuthInt(self, _algorithm='md5', _hash=md5.md5):
     237    def test_MD5HashA2AuthInt(self, _algorithm='md5', _hash=md5):
    234238        """
    235239        L{calcHA2} accepts the C{'md5'} algorithm and returns an MD5 hash of
    236240        its arguments, including the entity hash for QOP of C{'auth-int'}.
     
    265269        its arguments, excluding the entity hash for QOP other than
    266270        C{'auth-int'}.
    267271        """
    268         self.test_MD5HashA2Auth('sha', sha.sha)
     272        self.test_MD5HashA2Auth('sha', sha)
    269273
    270274
    271275    def test_SHAHashA2AuthInt(self):
     
    273277        L{calcHA2} accepts the C{'sha'} algorithm and returns a SHA hash of
    274278        its arguments, including the entity hash for QOP of C{'auth-int'}.
    275279        """
    276         self.test_MD5HashA2AuthInt('sha', sha.sha)
     280        self.test_MD5HashA2AuthInt('sha', sha)
    277281
    278282
    279     def test_MD5HashResponse(self, _algorithm='md5', _hash=md5.md5):
     283    def test_MD5HashResponse(self, _algorithm='md5', _hash=md5):
    280284        """
    281285        L{calcResponse} accepts the C{'md5'} algorithm and returns an MD5 hash
    282286        of its parameters, excluding the nonce count, client nonce, and QoP
     
    308312        of its parameters, excluding the nonce count, client nonce, and QoP
    309313        value if the nonce count and client nonce are C{None}
    310314        """
    311         self.test_MD5HashResponse('sha', sha.sha)
     315        self.test_MD5HashResponse('sha', sha)
    312316
    313317
    314     def test_MD5HashResponseExtra(self, _algorithm='md5', _hash=md5.md5):
     318    def test_MD5HashResponseExtra(self, _algorithm='md5', _hash=md5):
    315319        """
    316320        L{calcResponse} accepts the C{'md5'} algorithm and returns an MD5 hash
    317321        of its parameters, including the nonce count, client nonce, and QoP
     
    348352        of its parameters, including the nonce count, client nonce, and QoP
    349353        value if they are specified.
    350354        """
    351         self.test_MD5HashResponseExtra('sha', sha.sha)
     355        self.test_MD5HashResponseExtra('sha', sha)
    352356
    353357
    354358    def makeRequest(self, method='GET', clientAddress=None):
     
    639643        self.assertTrue(verifyObject(IUsernameDigestHash, creds))
    640644
    641645        cleartext = '%s:%s:%s' % (self.username, self.realm, self.password)
    642         hash = md5.md5(cleartext)
     646        hash = md5(cleartext)
    643647        self.assertTrue(creds.checkHash(hash.hexdigest()))
    644648        hash.update('wrong')
    645649        self.assertFalse(creds.checkHash(hash.hexdigest()))
     
    761765        key = '%s,%s,%s' % (challenge['nonce'],
    762766                            self.clientAddress.host,
    763767                            '-137876876')
    764         digest = md5.md5(key + credentialFactory.privateKey).hexdigest()
     768        digest = md5(key + credentialFactory.privateKey).hexdigest()
    765769        ekey = b64encode(key)
    766770
    767771        oldNonceOpaque = '%s-%s' % (digest, ekey.strip('\n'))
     
    786790                            self.clientAddress.host,
    787791                            '0')
    788792
    789         digest = md5.md5(key + 'this is not the right pkey').hexdigest()
     793        digest = md5(key + 'this is not the right pkey').hexdigest()
    790794        badChecksum = '%s-%s' % (digest, b64encode(key))
    791795
    792796        self.assertRaises(
  • twisted/web/woven/guard.py

     
    1616
    1717import random
    1818import time
    19 import md5
     19try:
     20    from hashlib import md5
     21except ImportError:
     22    from md5 import md5
    2023import urllib
    2124
    2225# Twisted Imports
     
    2932from twisted.cred.error import LoginFailed, UnauthorizedLogin
    3033
    3134def _sessionCookie():
    32     return md5.new("%s_%s" % (str(random.random()) , str(time.time()))).hexdigest()
     35    return md5("%s_%s" % (str(random.random()) , str(time.time()))).hexdigest()
    3336
    3437class GuardSession(components.Componentized):
    3538    """A user's session with a system.
  • twisted/web/_auth/digest.py

     
    99"""
    1010
    1111import time
    12 import md5, sha
     12try:
     13    from hashlib import md5, sha1 as sha
     14except ImportError:
     15    from md5 import md5
     16    from sha import sha
    1317
    1418from zope.interface import implements
    1519
     
    2125# The digest math
    2226
    2327algorithms = {
    24     'md5': md5.new,
     28    'md5': md5,
    2529
    2630    # md5-sess is more complicated than just another algorithm.  It requires
    2731    # H(A1) state to be remembered from the first WWW-Authenticate challenge
     
    3034    # recalculate H(A1) each time an Authorization header is received.  Read
    3135    # RFC 2617, section 3.2.2.2 and do not try to make DigestCredentialFactory
    3236    # support this unless you completely understand it. -exarkun
    33     'md5-sess': md5.new,
     37    'md5-sess': md5,
    3438
    35     'sha': sha.new,
     39    'sha': sha,
    3640}
    3741
    3842# DigestCalcHA1
     
    257261        if clientip is None:
    258262            clientip = ''
    259263        key = "%s,%s,%s" % (nonce, clientip, now)
    260         digest = md5.new(key + self.privateKey).hexdigest()
     264        digest = md5(key + self.privateKey).hexdigest()
    261265        ekey = key.encode('base64')
    262266        return "%s-%s" % (digest, ekey.strip('\n'))
    263267
     
    315319                'Invalid response, incompatible opaque/nonce too old')
    316320
    317321        # Verify the digest
    318         digest = md5.new(key + self.privateKey).hexdigest()
     322        digest = md5(key + self.privateKey).hexdigest()
    319323        if digest != opaqueParts[0]:
    320324            raise error.LoginFailed('Invalid response, invalid opaque value')
    321325
  • twisted/web/monitor.py

     
    44#
    55from twisted.web import client
    66from twisted.internet import reactor
    7 import md5
     7try:
     8    from hashlib import md5
     9except ImportError:
     10    from md5 import md5
    811from zope.interface import implements
    912
    1013class IChangeNotified:
     
    5356    def page(self, p):
    5457        if p is None:
    5558            return self.gotMD5(None)
    56         m = md5.new()
     59        m = md5()
    5760        m.update(p)
    5861        self.gotMD5(m.digest())
    5962
  • twisted/cred/util.py

     
    1212"""
    1313
    1414# System Imports
    15 import md5
     15try:
     16    from hashlib import md5
     17except ImportError:
     18    from md5 import md5
    1619import random
    1720
    1821from twisted.cred.error import Unauthorized
     
    2124    """Respond to a challenge.
    2225    This is useful for challenge/response authentication.
    2326    """
    24     m = md5.new()
     27    m = md5()
    2528    m.update(password)
    2629    hashedPassword = m.digest()
    27     m = md5.new()
     30    m = md5()
    2831    m.update(hashedPassword)
    2932    m.update(challenge)
    3033    doubleHashedPassword = m.digest()
     
    3639    crap = ''
    3740    for x in range(random.randrange(15,25)):
    3841        crap = crap + chr(random.randint(65,90))
    39     crap = md5.new(crap).digest()
     42    crap = md5(crap).digest()
    4043    return crap
  • twisted/mail/test/test_mail.py

     
    77
    88import os
    99import errno
    10 import md5
     10try:
     11    from hashlib import md5
     12except ImportError:
     13    from md5 import md5
    1114import shutil
    1215import pickle
    1316import StringIO
     
    587590        shutil.rmtree(self.tmpdir)
    588591
    589592    def testAuthenticateAPOP(self):
    590         resp = md5.new(self.P.magic + 'password').hexdigest()
     593        resp = md5(self.P.magic + 'password').hexdigest()
    591594        return self.P.authenticateUserAPOP('user', resp
    592595            ).addCallback(self._cbAuthenticateAPOP
    593596            )
     
    599602        result[2]()
    600603
    601604    def testAuthenticateIncorrectUserAPOP(self):
    602         resp = md5.new(self.P.magic + 'password').hexdigest()
     605        resp = md5(self.P.magic + 'password').hexdigest()
    603606        return self.assertFailure(
    604607            self.P.authenticateUserAPOP('resu', resp),
    605608            cred.error.UnauthorizedLogin)
    606609
    607610    def testAuthenticateIncorrectResponseAPOP(self):
    608         resp = md5.new('wrong digest').hexdigest()
     611        resp = md5('wrong digest').hexdigest()
    609612        return self.assertFailure(
    610613            self.P.authenticateUserAPOP('user', resp),
    611614            cred.error.UnauthorizedLogin)
  • twisted/mail/pop3client.py

     
    1010@author: Jp Calderone
    1111"""
    1212
    13 import re, md5
     13import re
     14try:
     15    from hashlib import md5
     16except ImportError:
     17    from md5 import md5
    1418
    1519from twisted.python import log
    1620from twisted.internet import defer
     
    485489    def _apop(self, username, password, challenge):
    486490        # Internal helper.  Computes and sends an APOP response.  Returns
    487491        # a Deferred that fires when the server responds to the response.
    488         digest = md5.new(challenge + password).hexdigest()
     492        digest = md5(challenge + password).hexdigest()
    489493        return self.apop(username, digest)
    490494
    491495    def apop(self, username, digest):
  • twisted/mail/maildir.py

     
    1212import stat
    1313import socket
    1414import time
    15 import md5
     15try:
     16    from hashlib import md5
     17except ImportError:
     18    from md5 import md5
    1619import cStringIO
    1720
    1821from zope.interface import implements
     
    298301        """
    299302        # Returning the actual filename is a mistake.  Hash it.
    300303        base = os.path.basename(self.list[i])
    301         return md5.md5(base).hexdigest()
     304        return md5(base).hexdigest()
    302305
    303306    def deleteMessage(self, i):
    304307        """Delete a message
     
    355358        return StringIO.StringIO(self.msgs[i])
    356359
    357360    def getUidl(self, i):
    358         return md5.new(self.msgs[i]).hexdigest()
     361        return md5(self.msgs[i]).hexdigest()
    359362
    360363    def deleteMessage(self, i):
    361364        pass
  • twisted/mail/pop3.py

     
    1414import string
    1515import base64
    1616import binascii
    17 import md5
     17try:
     18    from hashlib import md5
     19except ImportError:
     20    from md5 import md5
    1821import warnings
    1922
    2023from zope.interface import implements, Interface
     
    4447
    4548    def checkPassword(self, password):
    4649        seed = self.magic + password
    47         myDigest = md5.new(seed).hexdigest()
     50        myDigest = md5(seed).hexdigest()
    4851        return myDigest == self.digest
    4952
    5053
     
    10311034            self._dispatch(self.command+"_continue", None, line)
    10321035
    10331036    def apopAuthenticate(self, user, password, magic):
    1034         digest = md5.new(magic + password).hexdigest()
     1037        digest = md5(magic + password).hexdigest()
    10351038        self.apop(user, digest)
    10361039
    10371040    def apop(self, user, digest):
  • twisted/internet/_sslverify.py

     
    11# -*- test-case-name: twisted.test.test_sslverify -*-
    22# Copyright 2005 Divmod, Inc.  See LICENSE file for details
    33
    4 import itertools, md5
     4import itertools
     5try:
     6    from hashlib import md5
     7except ImportError:
     8    from md5 import md5
    59from OpenSSL import SSL, crypto
    610
    711from twisted.python import reflect, util
     
    451455        MD5 hex digest of signature on an empty certificate request with this
    452456        key.
    453457        """
    454         return md5.md5(self._emptyReq).hexdigest()
     458        return md5(self._emptyReq).hexdigest()
    455459
    456460
    457461    def inspect(self):
     
    725729            ctx.set_options(self._OP_ALL)
    726730
    727731        if self.enableSessions:
    728             sessionName = md5.md5("%s-%d" % (reflect.qual(self.__class__), _sessionCounter())).hexdigest()
     732            sessionName = md5("%s-%d" % (reflect.qual(self.__class__), _sessionCounter())).hexdigest()
    729733            ctx.set_session_id(sessionName)
    730734
    731735        return ctx
  • twisted/trial/test/test_loader.py

     
    55Tests for loading tests by name.
    66"""
    77
    8 import md5
     8try:
     9    from hashlib import md5
     10except ImportError:
     11    from md5 import md5
    912import os
    1013import shutil
    1114import sys
     
    484487#             if isinstance(s, type) or isinstance(s, types.ClassType):
    485488#                 return s.__module__+'.'+s.__name__
    486489            n = runner.name(s)
    487             d = md5.new(n).hexdigest()
     490            d = md5(n).hexdigest()
    488491            return d
    489492        self.loadSortedPackages(sillySorter)
    490493
  • twisted/spread/pb.py

     
    2727@author: Glyph Lefkowitz
    2828"""
    2929
    30 import md5
     30try:
     31    from hashlib import md5
     32except ImportError:
     33    from md5 import md5
    3134import random
    3235import new
    3336import types
     
    9971000
    9981001    This is useful for challenge/response authentication.
    9991002    """
    1000     m = md5.new()
     1003    m = md5()
    10011004    m.update(password)
    10021005    hashedPassword = m.digest()
    1003     m = md5.new()
     1006    m = md5()
    10041007    m.update(hashedPassword)
    10051008    m.update(challenge)
    10061009    doubleHashedPassword = m.digest()
     
    10111014    crap = ''
    10121015    for x in range(random.randrange(15,25)):
    10131016        crap = crap + chr(random.randint(65,90))
    1014     crap = md5.new(crap).digest()
     1017    crap = md5(crap).digest()
    10151018    return crap
    10161019
    10171020
     
    13401343
    13411344    # IUsernameHashedPassword:
    13421345    def checkPassword(self, password):
    1343         return self.checkMD5Password(md5.md5(password).digest())
     1346        return self.checkMD5Password(md5(password).digest())
    13441347
    13451348
    13461349    # IUsernameMD5Password
    13471350    def checkMD5Password(self, md5Password):
    1348         md = md5.new()
     1351        md = md5()
    13491352        md.update(md5Password)
    13501353        md.update(self.challenge)
    13511354        correct = md.digest()