Ticket #2763: fix-md5-and-sha.patch

File fix-md5-and-sha.patch, 50.9 KB (added by devinus, 14 years ago)
  • twisted/python/filepath.py

     
    99import os
    1010import errno
    1111import random
    12 import sha
     12import hashlib
    1313import base64
    1414
    1515from os.path import isabs, exists, normpath, abspath, splitext
     
    109109    """
    110110    Create a pseudorandom, 16-character string for use in secure filenames.
    111111    """
    112     return armor(sha.new(randomBytes(64)).digest())[:16]
     112    return armor(hashlib.sha1(randomBytes(64)).digest())[:16]
    113113
    114114class _PathHelper:
    115115    """
  • twisted/python/otp.py

     
    4747        result = chr(l % 256) + result
    4848        l = l / 256L
    4949    return result
    50        
    51 import md5, sha
     50
     51from hashlib import md5 as md5, sha1 as sha
    5252hashid = {md5: 'md5', sha: 'sha1'}
    5353
    5454INITIALSEQUENCE = 1000
     
    5656
    5757class Unauthorized(Exception):
    5858    """the Unauthorized exception
    59    
     59
    6060    This exception is raised when an action is not allowed, or a user is not
    6161    authenticated properly.
    6262    """
    6363
    6464class OTPAuthenticator:
    6565    """A One Time Password System
    66    
     66
    6767    Based on RFC 2289, which is based on a the S/KEY Authentication-scheme.
    6868    It uses the MD5- and SHA-algorithms for hashing
    69    
     69
    7070    The variable OTP is at all times a 64bit string"""
    7171
    7272    def __init__(self, hash = md5):
    7373        "Set the hash to either md5 or sha1"
    7474        self.hash = hash
    7575        pass
    76    
     76
    7777    def generateSeed(self):
    7878        "Return a 10 char random seed, with 6 lowercase chars and 4 digits"
    7979        seed = ''
     
    8888            return self.foldDigest128(otp)
    8989        if self.hash == sha:
    9090            return self.foldDigest160(otp)
    91    
     91
    9292    def foldDigest128(self, otp128):
    9393        "Fold a 128 bit digest to 64 bit"
    9494        regs = stringToDWords(otp128)
     
    122122        "Run through the hash and fold to 64 bit"
    123123        h = self.hash.new(digest)
    124124        return self.foldDigest(h.digest())
    125    
     125
    126126    def generateOTP(self, seed, passwd, sequence):
    127127        """Return a 64 bit OTP based on inputs
    128128        Run through makeReadable to get a 6 word pass-phrase"""
     
    138138        for i in xrange(0, 64, 2):
    139139            parity = parity + otp & 0x3
    140140            otp = otp >> 2
    141         return parity       
     141        return parity
    142142
    143143    def makeReadable(self, otp):
    144144        "Returns a 6 word pass-phrase from a 64bit OTP"
     
    151151        return string.join(list)
    152152
    153153    def challenge(self, seed, sequence):
    154         """Return a challenge in the format otp-<hash> <sequence> <seed>""" 
     154        """Return a challenge in the format otp-<hash> <sequence> <seed>"""
    155155        return "otp-%s %i %s" % (hashid[self.hash], sequence, seed)
    156156
    157157    def parsePhrase(self, phrase):
     
    178178    On the next authentication, the stored password is hashed and checked
    179179    up against the one given by the user. If they match, the sequencecounter
    180180    is decreased and the circle is closed.
    181    
     181
    182182    This object should be glued to each user
    183    
     183
    184184    Note:
    185185    It does NOT reset the sequence when the combinations left approach zero,
    186186    This has to be done manuelly by instancing a new object
  • twisted/python/test/test_zipstream.py

     
    66"""
    77import sys
    88import random
    9 import md5
     9import hashlib
    1010import zipfile
    1111
    1212from twisted.python import zipstream, filepath
     
    347347        unzipIterChunky should unzip the given number of bytes per iteration.
    348348        """
    349349        junk = ' '.join([str(random.random()) for n in xrange(1000)])
    350         junkmd5 = md5.new(junk).hexdigest()
     350        junkmd5 = hashlib.md5(junk).hexdigest()
    351351
    352352        tempdir = filepath.FilePath(self.mktemp())
    353353        tempdir.makedirs()
     
    364364        for r in uziter:
    365365            pass
    366366        self.assertEqual(r, 0)
    367         newmd5 = md5.new(
     367        newmd5 = hashlib.md5(
    368368            tempdir.child("zipstreamjunk").open().read()).hexdigest()
    369369        self.assertEqual(newmd5, junkmd5)
    370370
  • twisted/protocols/sip.py

     
    1414import socket
    1515import random
    1616import time
    17 import md5
     17import hashlib
    1818import sys
    1919from zope.interface import implements, Interface
    2020
     
    9494    488: "Not Acceptable Here",
    9595    491: "Request Pending",
    9696    493: "Undecipherable",
    97    
     97
    9898    500: "Internal Server Error",
    9999    501: "Not Implemented",
    100100    502: "Bad Gateway", # no donut
     
    102102    504: "Server Time-out",
    103103    505: "SIP Version not supported",
    104104    513: "Message Too Large",
    105    
     105
    106106    600: "Busy Everywhere",
    107107    603: "Decline",
    108108    604: "Does not exist anywhere",
     
    132132    pszNonce,
    133133    pszCNonce,
    134134):
    135     m = md5.md5()
     135    m = hashlib.md5()
    136136    m.update(pszUserName)
    137137    m.update(":")
    138138    m.update(pszRealm)
     
    140140    m.update(pszPassword)
    141141    HA1 = m.digest()
    142142    if pszAlg == "md5-sess":
    143         m = md5.md5()
     143        m = hashlib.md5()
    144144        m.update(HA1)
    145145        m.update(":")
    146146        m.update(pszNonce)
     
    159159    pszDigestUri,
    160160    pszHEntity,
    161161):
    162     m = md5.md5()
     162    m = hashlib.md5()
    163163    m.update(pszMethod)
    164164    m.update(":")
    165165    m.update(pszDigestUri)
     
    167167        m.update(":")
    168168        m.update(pszHEntity)
    169169    HA2 = m.digest().encode('hex')
    170    
    171     m = md5.md5()
     170
     171    m = hashlib.md5()
    172172    m.update(HA1)
    173173    m.update(":")
    174174    m.update(pszNonce)
     
    301301
    302302    def __str__(self):
    303303        return self.toString()
    304    
     304
    305305    def __repr__(self):
    306306        return '<URL %s:%s@%s:%r/%s>' % (self.username, self.password, self.host, self.port, self.transport)
    307307
     
    419419    """A SIP message."""
    420420
    421421    length = None
    422    
     422
    423423    def __init__(self):
    424424        self.headers = util.OrderedDict() # map name to list of values
    425425        self.body = ""
    426426        self.finished = 0
    427    
     427
    428428    def addHeader(self, name, value):
    429429        name = name.lower()
    430430        name = longHeaders.get(name, name)
     
    434434
    435435    def bodyDataReceived(self, data):
    436436        self.body += data
    437    
     437
    438438    def creationFinished(self):
    439439        if (self.length != None) and (self.length != len(self.body)):
    440440            raise ValueError, "wrong body length"
     
    465465        else:
    466466            self.uri = parseURL(uri)
    467467            cleanRequestURL(self.uri)
    468    
     468
    469469    def __repr__(self):
    470470        return "<SIP Request %d:%s %s>" % (id(self), self.method, self.uri.toString())
    471471
     
    501501    acceptResponses = 1
    502502    acceptRequests = 1
    503503    state = "firstline" # or "headers", "body" or "invalid"
    504    
     504
    505505    debug = 0
    506    
     506
    507507    def __init__(self, messageReceivedCallback):
    508508        self.messageReceived = messageReceivedCallback
    509509        self.reset()
     
    514514        self.bodyReceived = 0 # how much of the body we received
    515515        self.message = None
    516516        self.setLineMode(remainingData)
    517    
     517
    518518    def invalidMessage(self):
    519519        self.state = "invalid"
    520520        self.setRawMode()
    521    
     521
    522522    def dataDone(self):
    523523        # clear out any buffered data that may be hanging around
    524524        self.clearLineBuffer()
     
    536536        else:
    537537            # we have enough data and message wasn't finished? something is wrong
    538538            raise RuntimeError, "this should never happen"
    539    
     539
    540540    def dataReceived(self, data):
    541541        try:
    542542            basic.LineReceiver.dataReceived(self, data)
    543543        except:
    544544            log.err()
    545545            self.invalidMessage()
    546    
     546
    547547    def handleFirstLine(self, line):
    548548        """Expected to create self.message."""
    549549        raise NotImplementedError
    550550
    551551    def lineLengthExceeded(self, line):
    552552        self.invalidMessage()
    553    
     553
    554554    def lineReceived(self, line):
    555555        if self.state == "firstline":
    556556            while line.startswith("\n") or line.startswith("\r"):
     
    608608        self.message.creationFinished()
    609609        self.messageReceived(self.message)
    610610        self.reset(remainingData)
    611    
     611
    612612    def rawDataReceived(self, data):
    613613        assert self.state in ("body", "invalid")
    614614        if self.state == "invalid":
     
    631631
    632632class Base(protocol.DatagramProtocol):
    633633    """Base class for SIP clients and servers."""
    634    
     634
    635635    PORT = PORT
    636636    debug = False
    637    
     637
    638638    def __init__(self):
    639639        self.messages = []
    640640        self.parser = MessagesParser(self.addMessage)
     
    658658    def _fixupNAT(self, message, (srcHost, srcPort)):
    659659        # RFC 2543 6.40.2,
    660660        senderVia = parseViaHeader(message.headers["via"][0])
    661         if senderVia.host != srcHost:           
     661        if senderVia.host != srcHost:
    662662            senderVia.received = srcHost
    663663            if senderVia.port != srcPort:
    664664                senderVia.rport = srcPort
     
    709709
    710710    def handle_response(self, message, addr):
    711711        """Override to define behavior for responses received.
    712        
     712
    713713        @type message: C{Message}
    714714        @type addr: C{tuple}
    715715        """
     
    760760
    761761class Proxy(Base):
    762762    """SIP proxy."""
    763    
     763
    764764    PORT = PORT
    765765
    766766    locator = None # object implementing ILocator
    767    
     767
    768768    def __init__(self, host=None, port=PORT):
    769769        """Create new instance.
    770770
     
    774774        self.host = host or socket.getfqdn()
    775775        self.port = port
    776776        Base.__init__(self)
    777        
     777
    778778    def getVia(self):
    779779        """Return value of Via header for this proxy."""
    780780        return Via(host=self.host, port=self.port)
     
    797797                d.addErrback(lambda e:
    798798                    self.deliverResponse(self.responseFromRequest(e.code, message))
    799799                )
    800        
     800
    801801    def handle_request_default(self, message, (srcHost, srcPort)):
    802802        """Default request handler.
    803        
     803
    804804        Default behaviour for OPTIONS and unknown methods for proxies
    805805        is to forward message on to the client.
    806806
     
    808808        everything.
    809809        """
    810810        def _mungContactHeader(uri, message):
    811             message.headers['contact'][0] = uri.toString()           
     811            message.headers['contact'][0] = uri.toString()
    812812            return self.sendMessage(uri, message)
    813        
     813
    814814        viaHeader = self.getVia()
    815815        if viaHeader.toString() in message.headers["via"]:
    816816            # must be a loop, so drop message
     
    824824        d = self.locator.getAddress(uri)
    825825        d.addCallback(self.sendMessage, message)
    826826        d.addErrback(self._cantForwardRequest, message)
    827    
     827
    828828    def _cantForwardRequest(self, error, message):
    829829        error.trap(LookupError)
    830830        del message.headers["via"][0] # this'll be us
    831831        self.deliverResponse(self.responseFromRequest(404, message))
    832    
     832
    833833    def deliverResponse(self, responseMessage):
    834834        """Deliver response.
    835835
     
    838838        # XXX we don't do multicast yet
    839839        host = destVia.received or destVia.host
    840840        port = destVia.rport or destVia.port or self.PORT
    841        
     841
    842842        destAddr = URL(host=host, port=port)
    843843        self.sendMessage(destAddr, responseMessage)
    844844
     
    848848        for name in ("via", "to", "from", "call-id", "cseq"):
    849849            response.headers[name] = request.headers.get(name, [])[:]
    850850        return response
    851    
     851
    852852    def handle_response(self, message, addr):
    853853        """Default response handler."""
    854854        v = parseViaHeader(message.headers["via"][0])
     
    864864            self.gotResponse(message, addr)
    865865            return
    866866        self.deliverResponse(message)
    867    
     867
    868868    def gotResponse(self, message, addr):
    869869        """Called with responses that are addressed at this server."""
    870870        pass
     
    872872class IAuthorizer(Interface):
    873873    def getChallenge(peer):
    874874        """Generate a challenge the client may respond to.
    875        
     875
    876876        @type peer: C{tuple}
    877877        @param peer: The client's address
    878        
     878
    879879        @rtype: C{str}
    880880        @return: The challenge string
    881881        """
    882    
     882
    883883    def decode(response):
    884884        """Create a credentials object from the given response.
    885        
     885
    886886        @type response: C{str}
    887887        """
    888  
     888
    889889class BasicAuthorizer:
    890890    """Authorizer for insecure Basic (base64-encoded plaintext) authentication.
    891    
     891
    892892    This form of authentication is broken and insecure.  Do not use it.
    893893    """
    894894
    895895    implements(IAuthorizer)
    896    
     896
    897897    def getChallenge(self, peer):
    898898        return None
    899    
     899
    900900    def decode(self, response):
    901901        # At least one SIP client improperly pads its Base64 encoded messages
    902902        for i in range(3):
     
    917917
    918918class DigestedCredentials(cred.credentials.UsernameHashedPassword):
    919919    """Yet Another Simple Digest-MD5 authentication scheme"""
    920    
     920
    921921    def __init__(self, username, fields, challenges):
    922922        self.username = username
    923923        self.fields = fields
    924924        self.challenges = challenges
    925    
     925
    926926    def checkPassword(self, password):
    927927        method = 'REGISTER'
    928928        response = self.fields.get('response')
     
    937937        if opaque not in self.challenges:
    938938            return False
    939939        del self.challenges[opaque]
    940        
     940
    941941        user, domain = self.username.split('@', 1)
    942942        if uri is None:
    943943            uri = 'sip:' + domain
     
    946946            DigestCalcHA1(algo, user, domain, password, nonce, cnonce),
    947947            nonce, nc, cnonce, qop, method, uri, None,
    948948        )
    949        
     949
    950950        return expected == response
    951951
    952952class DigestAuthorizer:
    953953    CHALLENGE_LIFETIME = 15
    954    
     954
    955955    implements(IAuthorizer)
    956    
     956
    957957    def __init__(self):
    958958        self.outstanding = {}
    959    
     959
    960960    def generateNonce(self):
    961961        c = tuple([random.randrange(sys.maxint) for _ in range(3)])
    962962        c = '%d%d%d' % c
     
    975975            'qop-options="auth"',
    976976            'algorithm="MD5"',
    977977        ))
    978        
     978
    979979    def decode(self, response):
    980980        response = ' '.join(response.splitlines())
    981981        parts = response.split(',')
     
    10031003    authorizers = {
    10041004        'digest': DigestAuthorizer(),
    10051005    }
    1006    
     1006
    10071007    def __init__(self, *args, **kw):
    10081008        Proxy.__init__(self, *args, **kw)
    10091009        self.liveChallenges = {}
    1010        
     1010
    10111011    def handle_ACK_request(self, message, (host, port)):
    10121012        # XXX
    10131013        # ACKs are a client's way of indicating they got the last message
     
    10421042            m.headers.setdefault('www-authenticate', []).append(value)
    10431043        self.deliverResponse(m)
    10441044
    1045  
     1045
    10461046    def login(self, message, host, port):
    10471047        parts = message.headers['authorization'][0].split(None, 1)
    10481048        a = self.authorizers.get(parts[0].lower())
     
    10671067    def _cbLogin(self, (i, a, l), message, host, port):
    10681068        # It's stateless, matey.  What a joke.
    10691069        self.register(message, host, port)
    1070    
     1070
    10711071    def _ebLogin(self, failure, message, host, port):
    10721072        failure.trap(cred.error.UnauthorizedLogin)
    10731073        self.unauthorized(message, host, port)
     
    11371137    """A simplistic registry for a specific domain."""
    11381138
    11391139    implements(IRegistry, ILocator)
    1140    
     1140
    11411141    def __init__(self, domain):
    11421142        self.domain = domain # the domain we handle registration for
    11431143        self.users = {} # map username to (IDelayedCall for expiry, address URI)
     
    11501150            return defer.succeed(url)
    11511151        else:
    11521152            return defer.fail(LookupError("no such user"))
    1153            
     1153
    11541154    def getRegistrationInfo(self, userURI):
    11551155        if userURI.host != self.domain:
    11561156            return defer.fail(LookupError("unknown domain"))
     
    11591159            return defer.succeed(Registration(int(dc.getTime() - time.time()), url))
    11601160        else:
    11611161            return defer.fail(LookupError("no such user"))
    1162        
     1162
    11631163    def _expireRegistration(self, username):
    11641164        try:
    11651165            dc, url = self.users[username]
     
    11691169            dc.cancel()
    11701170            del self.users[username]
    11711171        return defer.succeed(Registration(0, url))
    1172    
     1172
    11731173    def registerAddress(self, domainURL, logicalURL, physicalURL):
    11741174        if domainURL.host != self.domain:
    11751175            log.msg("Registration for domain we don't handle.")
  • 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 hashlib, os, base64
    1616
    1717class SSHKeysHandlingTestCase(unittest.TestCase):
    1818    """
     
    316316        messageSize = 6
    317317        self.assertEquals(keys.pkcs1Pad(data, messageSize),
    318318                '\x01\xff\x00ABC')
    319         hash = sha.new().digest()
     319        hash = hashlib.sha1().digest()
    320320        messageSize = 40
    321321        self.assertEquals(keys.pkcs1Digest('', messageSize),
    322322                '\x01\xff\xff\xff\x00' + keys.ID_SHA1 + hash)
     
    348348        """
    349349        data = 'data'
    350350        key, sig = self._signDSA(data)
    351         sigData = sha.new(data).digest()
     351        sigData = hashlib.sha1(data).digest()
    352352        v = key.sign(sigData, '\x55' * 19)
    353353        self.assertEquals(sig, common.NS('ssh-dss') + common.NS(
    354354            Crypto.Util.number.long_to_bytes(v[0], 20) +
  • twisted/conch/ssh/transport.py

     
    33# Copyright (c) 2001-2004 Twisted Matrix Laboratories.
    44# See LICENSE for details.
    55
    6 # 
     6#
    77
    88"""The lowest level SSH protocol.  This handles the key negotiation, the encryption and the compression.
    99
     
    1616
    1717# base library imports
    1818import struct
    19 import md5
    20 import sha
     19import hashlib
    2120import zlib
    2221import math # for math.log
    2322import array
     
    4443    comment = ''
    4544    ourVersionString = ('SSH-'+protocolVersion+'-'+version+' '+comment).strip()
    4645
    47     supportedCiphers = ['aes256-ctr', 'aes256-cbc', 'aes192-ctr', 'aes192-cbc', 
    48                         'aes128-ctr', 'aes128-cbc', 'cast128-ctr', 
     46    supportedCiphers = ['aes256-ctr', 'aes256-cbc', 'aes192-ctr', 'aes192-cbc',
     47                        'aes128-ctr', 'aes128-cbc', 'cast128-ctr',
    4948                        'cast128-cbc', 'blowfish-ctr', 'blowfish', 'idea-ctr'
    5049                        'idea-cbc', '3des-ctr', '3des-cbc'] # ,'none']
    5150    supportedMACs = ['hmac-sha1', 'hmac-md5'] # , 'none']
    52    
     51
    5352    # both of the above support 'none', but for security are disabled by
    5453    # default.  to enable them, subclass this class and add it, or do:
    5554    #   SSHTransportBase.supportedCiphers.append('none')
    5655
    57     supportedKeyExchanges = ['diffie-hellman-group-exchange-sha1', 
     56    supportedKeyExchanges = ['diffie-hellman-group-exchange-sha1',
    5857                             'diffie-hellman-group1-sha1']
    5958    supportedPublicKeys = ['ssh-rsa', 'ssh-dss']
    6059    supportedCompressions = ['none', 'zlib']
     
    150149        if len(packet) != 4+packetLen:
    151150            self.sendDisconnect(DISCONNECT_PROTOCOL_ERROR, 'bad packet length')
    152151            return
    153         if ms: 
     152        if ms:
    154153            macData, self.buf = self.buf[:ms],  self.buf[ms:]
    155154            if not self.currentEncryptions.verify(self.incomingPacketSequence, packet, macData):
    156155                self.sendDisconnect(DISCONNECT_MAC_ERROR, 'bad MAC')
     
    303302        self.kexAlg = ffs(kexAlgs, self.supportedKeyExchanges)
    304303        self.keyAlg = ffs(keyAlgs, self.supportedPublicKeys)
    305304        self.nextEncryptions = SSHCiphers(
    306         ffs(encSC, self.supportedCiphers), 
    307             ffs(encCS, self.supportedCiphers), 
    308             ffs(macSC, self.supportedMACs), 
    309             ffs(macCS, self.supportedMACs), 
     305        ffs(encSC, self.supportedCiphers),
     306            ffs(encCS, self.supportedCiphers),
     307            ffs(macSC, self.supportedMACs),
     308            ffs(macCS, self.supportedMACs),
    310309         )
    311310        self.outgoingCompressionType = ffs(compSC, self.supportedCompressions)
    312311        self.incomingCompressionType = ffs(compCS, self.supportedCompressions)
     
    317316            self.sendDisconnect(DISCONNECT_KEY_EXCHANGE_FAILED, "couldn't match all kex parts")
    318317            return
    319318        log.msg('kex alg, key alg: %s %s'%(self.kexAlg, self.keyAlg))
    320         log.msg('server->client: %s %s %s'%(self.nextEncryptions.outCipType, 
    321                                             self.nextEncryptions.outMacType, 
     319        log.msg('server->client: %s %s %s'%(self.nextEncryptions.outCipType,
     320                                            self.nextEncryptions.outMacType,
    322321                                            self.outgoingCompressionType))
    323         log.msg('client->server: %s %s %s'%(self.nextEncryptions.inCipType, 
    324                                             self.nextEncryptions.inMacType, 
     322        log.msg('client->server: %s %s %s'%(self.nextEncryptions.inCipType,
     323                                            self.nextEncryptions.inMacType,
    325324                                            self.incomingCompressionType))
    326325
    327326
     
    334333            y = Util.number.getRandomNumber(16, randbytes.secureRandom)
    335334            f = pow(DH_GENERATOR, y, DH_PRIME)
    336335            sharedSecret = _MPpow(clientDHPubKey, y, DH_PRIME)
    337             h = sha.new()
     336            h = hashlib.sha1()
    338337            h.update(NS(self.otherVersionString))
    339338            h.update(NS(self.ourVersionString))
    340339            h.update(NS(self.clientKexInitPayload))
     
    391390
    392391        f = pow(self.g, y, self.p)
    393392        sharedSecret = _MPpow(clientDHPubKey, y, self.p)
    394         h = sha.new()
     393        h = hashlib.sha1()
    395394        h.update(NS(self.otherVersionString))
    396395        h.update(NS(self.ourVersionString))
    397396        h.update(NS(self.clientKexInitPayload))
     
    444443        self.sendPacket(MSG_NEWKEYS, '')
    445444
    446445    def _getKey(self, c, sharedSecret, exchangeHash):
    447         k1 = sha.new(sharedSecret+exchangeHash+c+self.sessionID).digest()
    448         k2 = sha.new(sharedSecret+exchangeHash+k1).digest()
     446        k1 = hashlib.sha1(sharedSecret+exchangeHash+c+self.sessionID).digest()
     447        k2 = hashlib.sha1(sharedSecret+exchangeHash+k1).digest()
    449448        return k1+k2
    450449
    451450class SSHClientTransport(SSHTransportBase):
     
    465464        self.kexAlg = ffs(self.supportedKeyExchanges, kexAlgs)
    466465        self.keyAlg = ffs(self.supportedPublicKeys, keyAlgs)
    467466        self.nextEncryptions = SSHCiphers(
    468         ffs(self.supportedCiphers, encCS), 
    469             ffs(self.supportedCiphers, encSC), 
    470             ffs(self.supportedMACs, macCS), 
    471             ffs(self.supportedMACs, macSC), 
     467        ffs(self.supportedCiphers, encCS),
     468            ffs(self.supportedCiphers, encSC),
     469            ffs(self.supportedMACs, macCS),
     470            ffs(self.supportedMACs, macSC),
    472471         )
    473472        self.outgoingCompressionType = ffs(self.supportedCompressions, compCS)
    474473        self.incomingCompressionType = ffs(self.supportedCompressions, compSC)
     
    479478            self.sendDisconnect(DISCONNECT_KEY_EXCHANGE_FAILED, "couldn't match all kex parts")
    480479            return
    481480        log.msg('kex alg, key alg: %s %s'%(self.kexAlg, self.keyAlg))
    482         log.msg('client->server: %s %s %s'%(self.nextEncryptions.outCipType, 
    483                                             self.nextEncryptions.outMacType, 
     481        log.msg('client->server: %s %s %s'%(self.nextEncryptions.outCipType,
     482                                            self.nextEncryptions.outMacType,
    484483                                            self.outgoingCompressionType))
    485         log.msg('server->client: %s %s %s'%(self.nextEncryptions.inCipType, 
    486                                             self.nextEncryptions.inMacType, 
     484        log.msg('server->client: %s %s %s'%(self.nextEncryptions.inCipType,
     485                                            self.nextEncryptions.inMacType,
    487486                                            self.incomingCompressionType))
    488487
    489488        if self.kexAlg == 'diffie-hellman-group1-sha1':
     
    498497            pubKey, packet = getNS(packet)
    499498            f, packet = getMP(packet)
    500499            signature, packet = getNS(packet)
    501             fingerprint = ':'.join(map(lambda c: '%02x'%ord(c), md5.new(pubKey).digest()))
     500            fingerprint = ':'.join(map(lambda c: '%02x'%ord(c), hashlib.md5(pubKey).digest()))
    502501            d = self.verifyHostKey(pubKey, fingerprint)
    503502            d.addCallback(self._continueGEX_GROUP, pubKey, f, signature)
    504503            d.addErrback(lambda unused,self=self:self.sendDisconnect(DISCONNECT_HOST_KEY_NOT_VERIFIABLE, 'bad host key'))
     
    511510
    512511    def _continueGEX_GROUP(self, ignored, pubKey, f, signature):
    513512        sharedSecret = _MPpow(f, self.x, DH_PRIME)
    514         h = sha.new()
     513        h = hashlib.sha1()
    515514        h.update(NS(self.ourVersionString))
    516515        h.update(NS(self.otherVersionString))
    517516        h.update(NS(self.ourKexInitPayload))
     
    530529        pubKey, packet = getNS(packet)
    531530        f, packet = getMP(packet)
    532531        signature, packet = getNS(packet)
    533         fingerprint = ':'.join(map(lambda c: '%02x'%ord(c), md5.new(pubKey).digest()))
     532        fingerprint = ':'.join(map(lambda c: '%02x'%ord(c), hashlib.md5(pubKey).digest()))
    534533        d = self.verifyHostKey(pubKey, fingerprint)
    535534        d.addCallback(self._continueGEX_REPLY, pubKey, f, signature)
    536535        d.addErrback(lambda unused, self=self: self.sendDisconnect(DISCONNECT_HOST_KEY_NOT_VERIFIABLE, 'bad host key'))
     
    538537    def _continueGEX_REPLY(self, ignored, pubKey, f, signature):
    539538        serverKey = keys.getPublicKeyObject(pubKey)
    540539        sharedSecret = _MPpow(f, self.x, self.p)
    541         h = sha.new()
     540        h = hashlib.sha1()
    542541        h.update(NS(self.ourVersionString))
    543542        h.update(NS(self.otherVersionString))
    544543        h.update(NS(self.ourKexInitPayload))
     
    571570            self.ssh_NEWKEYS('')
    572571
    573572    def _getKey(self, c, sharedSecret, exchangeHash):
    574         k1 = sha.new(sharedSecret+exchangeHash+c+self.sessionID).digest()
    575         k2 = sha.new(sharedSecret+exchangeHash+k1).digest()
     573        k1 = hashlib.sha1(sharedSecret+exchangeHash+c+self.sessionID).digest()
     574        k2 = hashlib.sha1(sharedSecret+exchangeHash+k1).digest()
    576575        return k1+k2
    577576
    578577    def ssh_NEWKEYS(self, packet):
     
    618617
    619618    def connectionSecure(self):
    620619        """
    621         Called when the encryption has been set up.  Generally, 
     620        Called when the encryption has been set up.  Generally,
    622621        requestService() is called to run another service over the transport.
    623622        """
    624623        raise NotImplementedError
    625624
    626625class _DummyCipher:
    627626    block_size = 1
    628    
     627
    629628    def encrypt(self, x):
    630629        return x
    631    
     630
    632631    decrypt = encrypt
    633632
    634633class SSHCiphers:
    635634    cipherMap = {
    636         '3des-cbc':('DES3', 24, 0), 
    637         'blowfish-cbc':('Blowfish', 16,0 ), 
    638         'aes256-cbc':('AES', 32, 0), 
    639         'aes192-cbc':('AES', 24, 0), 
    640         'aes128-cbc':('AES', 16, 0), 
    641         'arcfour':('ARC4', 16, 0), 
    642         'idea-cbc':('IDEA', 16, 0), 
    643         'cast128-cbc':('CAST', 16, 0), 
     635        '3des-cbc':('DES3', 24, 0),
     636        'blowfish-cbc':('Blowfish', 16,0 ),
     637        'aes256-cbc':('AES', 32, 0),
     638        'aes192-cbc':('AES', 24, 0),
     639        'aes128-cbc':('AES', 16, 0),
     640        'arcfour':('ARC4', 16, 0),
     641        'idea-cbc':('IDEA', 16, 0),
     642        'cast128-cbc':('CAST', 16, 0),
    644643        'aes128-ctr':('AES', 16, 1),
    645644        'aes192-ctr':('AES', 24, 1),
    646645        'aes256-ctr':('AES', 32, 1),
     
    651650        'none':(None, 0, 0),
    652651    }
    653652    macMap = {
    654         'hmac-sha1': 'sha', 
     653        'hmac-sha1': 'sha',
    655654        'hmac-md5': 'md5',
    656655        'none':None
    657656     }
  • twisted/conch/ssh/factory.py

     
    11# Copyright (c) 2001-2004 Twisted Matrix Laboratories.
    22# See LICENSE for details.
    33
    4 # 
     4#
    55
    66"""A Factory for SSH servers, along with an OpenSSHFactory to use the same data sources as OpenSSH.
    77
     
    1010Maintainer: U{Paul Swartz<mailto:z3p@twistedmatrix.com>}
    1111"""
    1212
    13 import md5
    14 
    1513try:
    1614    import resource
    1715except ImportError:
     
    6361
    6462    def getPublicKeys(self):
    6563        """
    66         Called when the factory is started to get the public portions of the 
    67         servers host keys.  Returns a dictionary mapping SSH key types  to 
     64        Called when the factory is started to get the public portions of the
     65        servers host keys.  Returns a dictionary mapping SSH key types  to
    6866        public key strings.
    6967
    7068        @rtype: C{dict}
     
    7371
    7472    def getPrivateKeys(self):
    7573        """
    76         Called when the factory is started to get the  private portions of the 
    77         servers host keys.  Returns a dictionary mapping SSH key types to 
     74        Called when the factory is started to get the  private portions of the
     75        servers host keys.  Returns a dictionary mapping SSH key types to
    7876        C{Crypto.PublicKey.pubkey.pubkey} objects.
    7977
    8078        @rtype: C{dict}
  • twisted/conch/ssh/keys.py

     
    1313
    1414# base library imports
    1515import base64
    16 import sha, md5
     16import hashlib
    1717import warnings
    1818
    1919# external library imports
     
    168168                len(ivdata), 2)])
    169169            if not passphrase:
    170170                raise EncryptedKeyError('encrypted key with no passphrase')
    171             ba = md5.new(passphrase + iv).digest()
    172             bb = md5.new(ba + passphrase + iv).digest()
     171            ba = hashlib.md5(passphrase + iv).digest()
     172            bb = hashlib.md5(ba + passphrase + iv).digest()
    173173            decKey = (ba + bb)[:24]
    174174            b64Data = base64.decodestring(''.join(lines[3:-1]))
    175175            keyData = DES3.new(decKey, DES3.MODE_CBC, iv).decrypt(b64Data)
     
    500500                hexiv = ''.join(['%02X' % ord(x) for x in iv])
    501501                lines.append('Proc-Type: 4,ENCRYPTED')
    502502                lines.append('DEK-Info: DES-EDE3-CBC,%s\n' % hexiv)
    503                 ba = md5.new(extra + iv).digest()
    504                 bb = md5.new(ba + extra + iv).digest()
     503                ba = hashlib.md5(extra + iv).digest()
     504                bb = hashlib.md5(ba + extra + iv).digest()
    505505                encKey = (ba + bb)[:24]
    506506            asn1Data = asn1.pack([objData])
    507507            if extra:
     
    584584            signature = self.keyObject.sign(digest, '')[0]
    585585            ret = common.NS(Util.number.long_to_bytes(signature))
    586586        elif self.type() == 'DSA':
    587             digest = sha.new(data).digest()
     587            digest = hashlib.sha1(data).digest()
    588588            randomBytes = randbytes.secureRandom(19)
    589589            sig = self.keyObject.sign(digest, randomBytes)
    590590            # SSH insists that the DSS signature blob be two 160-bit integers
     
    613613            signature = common.getNS(signature)[0]
    614614            numbers = [Util.number.bytes_to_long(n) for n in signature[:20],
    615615                    signature[20:]]
    616             digest = sha.new(data).digest()
     616            digest = hashlib.sha1(data).digest()
    617617        return self.keyObject.verify(digest, numbers)
    618618
    619619def getPublicKeyString(filename=None, line=0, data=''):
     
    766766    @type data: C{str}
    767767    @type messageLength: C{str}
    768768    """
    769     digest = sha.new(data).digest()
     769    digest = hashlib.sha1(data).digest()
    770770    return pkcs1Pad(ID_SHA1+digest, messageLength)
    771771
    772772def lenSig(obj):
  • twisted/words/test/test_jabbercomponent.py

     
    55Tests for L{twisted.words.protocols.jabber.component}
    66"""
    77
    8 import sha
     8import hashlib
    99from twisted.trial import unittest
    1010
    1111from twisted.words.protocols.jabber import component
     
    4848        handshake = self.output[-1]
    4949        self.assertEquals('handshake', handshake.name)
    5050        self.assertEquals('test:component', handshake.uri)
    51         self.assertEquals(sha.new("%s%s" % ('12345', 'secret')).hexdigest(),
     51        self.assertEquals(hashlib.sha1("%s%s" % ('12345', 'secret')).hexdigest(),
    5252                          unicode(handshake))
    5353
    5454        # successful authentication
     
    7878        xs.dataReceived("<stream:stream xmlns='jabber:component:accept' xmlns:stream='http://etherx.jabber.org/streams' from='cjid' id='12345'>")
    7979
    8080        # Calculate what we expect the handshake value to be
    81         hv = sha.new("%s%s" % ("12345", "secret")).hexdigest()
     81        hv = hashlib.sha1("%s%s" % ("12345", "secret")).hexdigest()
    8282
    8383        self.assertEquals(outlist[1], "<handshake>%s</handshake>" % (hv))
    8484
  • twisted/words/test/test_jabberclient.py

     
    55Tests for L{twisted.words.protocols.jabber.client}
    66"""
    77
    8 import sha
     8import hashlib
    99from twisted.trial import unittest
    1010from twisted.words.protocols.jabber import client, error, jid, xmlstream
    1111from twisted.words.protocols.jabber.sasl import SASLInitiatingInitializer
     
    117117        self.assertEquals(('jabber:iq:auth', 'query'),
    118118                          (iq.children[0].uri, iq.children[0].name))
    119119        self.assertEquals('user', unicode(iq.query.username))
    120         self.assertEquals(sha.new('12345secret').hexdigest(),
     120        self.assertEquals(hashlib.sha1('12345secret').hexdigest(),
    121121                          unicode(iq.query.digest))
    122122        self.assertEquals('resource', unicode(iq.query.resource))
    123123
  • twisted/words/protocols/jabber/sasl_mechanisms.py

     
    77Protocol agnostic implementations of SASL authentication mechanisms.
    88"""
    99
    10 import md5, binascii, random, time, os
     10import hashlib, binascii, random, time, os
    1111
    1212from zope.interface import Interface, Attribute, implements
    1313
     
    178178        """
    179179
    180180        def H(s):
    181             return md5.new(s).digest()
     181            return hashlib.md5(s).digest()
    182182
    183183        def HEX(n):
    184184            return binascii.b2a_hex(n)
     
    221221
    222222
    223223    def _gen_nonce(self):
    224         return md5.new("%s:%s:%s" % (str(random.random()) , str(time.gmtime()),str(os.getpid()))).hexdigest()
     224        return hashlib.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    import hashlib
     46    return hashlib.sha1("%s%s" % (sid, password)).hexdigest()
    4747
    4848
    4949class Authenticator:
  • twisted/words/protocols/oscar.py

     
    1616from twisted.python import log
    1717
    1818import struct
    19 import md5
     19import hashlib
    2020import string
    2121import socket
    2222import random
     
    6363    return dict,data
    6464
    6565def encryptPasswordMD5(password,key):
    66     m=md5.new()
     66    m=hashlib.md5()
    6767    m.update(key)
    68     m.update(md5.new(password).digest())
     68    m.update(hashlib.md5(password).digest())
    6969    m.update("AOL Instant Messenger (SM)")
    7070    return m.digest()
    7171
     
    232232                    self.alertWhen.append('unaway')
    233233            elif k == 0x013e:
    234234                self.alertSound = v
    235  
     235
    236236    def oscarRep(self, groupID, buddyID):
    237237        tlvData = reduce(lambda x,y: x+y, map(lambda (k,v):TLV(k,v), self.tlvs.items()), '\000\000')
    238238        return struct.pack('!H', len(self.name)) + self.name + \
  • twisted/web2/auth/digest.py

     
    1212
    1313from twisted.web2.auth.interfaces import ICredentialFactory
    1414
    15 import md5, sha
     15import hashlib
    1616import random, sys
    1717
    1818# The digest math
    1919
    2020algorithms = {
    21     'md5': md5.new,
    22     'md5-sess': md5.new,
    23     'sha': sha.new,
     21    'md5': hashlib.md5,
     22    'md5-sess': hashlib.md5,
     23    'sha': hashlib.sha1,
    2424}
    2525
    2626# DigestCalcHA1
     
    228228        # Now, what we do is encode the nonce, client ip and a timestamp
    229229        # in the opaque value with a suitable digest
    230230        key = "%s,%s,%s" % (nonce, clientip, str(int(self._getTime())))
    231         digest = md5.new(key + self.privateKey).hexdigest()
     231        digest = hashlib.md5(key + self.privateKey).hexdigest()
    232232        ekey = key.encode('base64')
    233233        return "%s-%s" % (digest, ekey.strip('\n'))
    234234
     
    275275                'Invalid response, incompatible opaque/nonce too old')
    276276
    277277        # Verify the digest
    278         digest = md5.new(key + self.privateKey).hexdigest()
     278        digest = hashlib.md5(key + self.privateKey).hexdigest()
    279279        if digest != opaqueParts[0]:
    280280            raise error.LoginFailed('Invalid response, invalid opaque value')
    281281
  • twisted/web2/dav/test/test_copy.py

     
    77# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
    88# copies of the Software, and to permit persons to whom the Software is
    99# furnished to do so, subject to the following conditions:
    10 # 
     10#
    1111# The above copyright notice and this permission notice shall be included in all
    1212# copies or substantial portions of the Software.
    13 # 
     13#
    1414# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    1515# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    1616# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
     
    2424
    2525import os
    2626import urllib
    27 import md5
     27import hashlib
    2828
    2929import twisted.web2.dav.test.util
    3030from twisted.web2 import responsecode
     
    162162            yield (request, do_test)
    163163
    164164def sumFile(path):
    165     m = md5.new()
     165    m = hashlib.md5()
    166166
    167167    if os.path.isfile(path):
    168168        f = file(path)
  • twisted/web2/test/test_httpauth.py

     
    1 import md5
     1import hashlib
    22from twisted.internet import address
    33from twisted.trial import unittest
    44from twisted.cred import error
     
    263263        creds = self.credentialFactory.decode(clientResponse, _trivial_GET)
    264264
    265265        self.failUnless(creds.checkHash(
    266                 md5.md5('username:test realm:password').hexdigest()))
     266                hashlib.md5('username:test realm:password').hexdigest()))
    267267
    268268        self.failIf(creds.checkHash(
    269                 md5.md5('username:test realm:bogus').hexdigest()))
     269                hashlib.md5('username:test realm:bogus').hexdigest()))
    270270
    271271    def test_invalidOpaque(self):
    272272        """
     
    364364        key = '%s,%s,%s' % (challenge['nonce'],
    365365                            clientAddress.host,
    366366                            '-137876876')
    367         digest = md5.new(key + credentialFactory.privateKey).hexdigest()
     367        digest = hashlib.md5(key + credentialFactory.privateKey).hexdigest()
    368368        ekey = key.encode('base64')
    369369
    370370        oldNonceOpaque = '%s-%s' % (digest, ekey.strip('\n'))
     
    390390                            clientAddress.host,
    391391                            '0')
    392392
    393         digest = md5.new(key + 'this is not the right pkey').hexdigest()
     393        digest = hashlib.md5(key + 'this is not the right pkey').hexdigest()
    394394
    395395        badChecksum = '%s-%s' % (digest,
    396396                                 key.encode('base64').strip('\n'))
     
    834834    def test_forceAuthentication(self):
    835835        """
    836836        Test that if an HTTPError with an Unauthorized status code is raised
    837         from within our protected resource, we add the WWW-Authenticate 
     837        from within our protected resource, we add the WWW-Authenticate
    838838        headers if they do not already exist.
    839839        """
    840840        self.portal.registerChecker(checkers.AllowAnonymousAccess())
  • 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
     
    475474            flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, "O_BINARY", 0)
    476475
    477476            fileobject = os.fdopen(os.open(outname, flags, self.permissions), 'wb', 0)
    478                
     477
    479478            stream.readIntoFile(filestream, fileobject)
    480479
    481480        return outname
  • twisted/cred/util.py

     
    1616"""
    1717
    1818# System Imports
    19 import md5
     19import hashlib
    2020import random
    2121
    2222from twisted.cred.error import Unauthorized
     
    2525    """Respond to a challenge.
    2626    This is useful for challenge/response authentication.
    2727    """
    28     m = md5.new()
     28    m = hashlib.md5()
    2929    m.update(password)
    3030    hashedPassword = m.digest()
    3131    m = md5.new()
     
    4040    crap = ''
    4141    for x in range(random.randrange(15,25)):
    4242        crap = crap + chr(random.randint(65,90))
    43     crap = md5.new(crap).digest()
     43    crap = hashlib.md5(crap).digest()
    4444    return crap
  • twisted/web/server.py

     
    471471class Site(http.HTTPFactory):
    472472    """
    473473    A web site: manage log, sessions, and resources.
    474    
     474
    475475    @ivar counter: increment value used for generating unique sessions ID.
    476476    @ivar requestFactory: factory creating requests objects. Default to
    477477        L{Request}.
     
    507507        """
    508508        (internal) Generate an opaque, unique ID for a user's session.
    509509        """
    510         import md5, random
     510        import hashlib, random
    511511        self.counter = self.counter + 1
    512         return md5.new("%s_%s" % (str(random.random()) , str(self.counter))).hexdigest()
     512        return hashlib.md5("%s_%s" % (str(random.random()) , str(self.counter))).hexdigest()
    513513
    514514    def makeSession(self):
    515515        """
  • twisted/web/woven/guard.py

     
    1616
    1717import random
    1818import time
    19 import md5
     19import hashlib
    2020import urllib
    2121
    2222# Twisted Imports
     
    2929from twisted.cred.error import LoginFailed, UnauthorizedLogin
    3030
    3131def _sessionCookie():
    32     return md5.new("%s_%s" % (str(random.random()) , str(time.time()))).hexdigest()
     32    return hashlib.md5("%s_%s" % (str(random.random()) , str(time.time()))).hexdigest()
    3333
    3434class GuardSession(components.Componentized):
    3535    """A user's session with a system.
     
    186186class SessionWrapper(Resource):
    187187
    188188    sessionLifetime = 1800
    189    
     189
    190190    def __init__(self, rsrc, cookieKey=None):
    191191        Resource.__init__(self)
    192192        self.resource = rsrc
     
    295295    If you want to determine what unauthenticated users see, make sure your
    296296    L{Portal<twisted.cred.portal.Portal>} has a checker associated that allows
    297297    anonymous access. (See L{twisted.cred.checkers.AllowAnonymousAccess})
    298    
     298
    299299    """
    300    
     300
    301301    def __init__(self, portal, callback=None, errback=None):
    302302        """Constructs a UsernamePasswordWrapper around the given portal.
    303303
     
    305305            associated with this portal must be able to accept username/password
    306306            credentials.
    307307        @type portal: L{twisted.cred.portal.Portal}
    308        
     308
    309309        @param callback: Gets called after a successful login attempt.
    310310            A resource that redirects to "." will display the avatar resource.
    311311            If this parameter isn't provided, defaults to a standard Woven
     
    343343            def triggerLogin(username, password, submit=None):
    344344                return self.portal.login(
    345345                    UsernamePassword(username, password),
    346                     None, 
     346                    None,
    347347                    IResource
    348348                ).addCallback(
    349349                    loginSuccess
  • twisted/web/monitor.py

     
    44#
    55from twisted.web import client
    66from twisted.internet import reactor
    7 import md5
     7import hashlib
    88from zope.interface import implements
    99
    1010class IChangeNotified:
     
    5353    def page(self, p):
    5454        if p is None:
    5555            return self.gotMD5(None)
    56         m = md5.new()
     56        m = hashlib.md5()
    5757        m.update(p)
    5858        self.gotMD5(m.digest())
    5959
  • twisted/mail/test/test_mail.py

     
    77
    88import os
    99import errno
    10 import md5
     10import hashlib
    1111import shutil
    1212import pickle
    1313import StringIO
     
    587587        shutil.rmtree(self.tmpdir)
    588588
    589589    def testAuthenticateAPOP(self):
    590         resp = md5.new(self.P.magic + 'password').hexdigest()
     590        resp = hashlib.md5(self.P.magic + 'password').hexdigest()
    591591        return self.P.authenticateUserAPOP('user', resp
    592592            ).addCallback(self._cbAuthenticateAPOP
    593593            )
     
    599599        result[2]()
    600600
    601601    def testAuthenticateIncorrectUserAPOP(self):
    602         resp = md5.new(self.P.magic + 'password').hexdigest()
     602        resp = hashlib.md5(self.P.magic + 'password').hexdigest()
    603603        return self.assertFailure(
    604604            self.P.authenticateUserAPOP('resu', resp),
    605605            cred.error.UnauthorizedLogin)
    606606
    607607    def testAuthenticateIncorrectResponseAPOP(self):
    608         resp = md5.new('wrong digest').hexdigest()
     608        resp = hashlib.md5('wrong digest').hexdigest()
    609609        return self.assertFailure(
    610610            self.P.authenticateUserAPOP('user', resp),
    611611            cred.error.UnauthorizedLogin)
  • twisted/mail/maildir.py

     
    1212import stat
    1313import socket
    1414import time
    15 import md5
     15import hashlib
    1616import cStringIO
    1717
    1818from zope.interface import implements
     
    298298        """
    299299        # Returning the actual filename is a mistake.  Hash it.
    300300        base = os.path.basename(self.list[i])
    301         return md5.md5(base).hexdigest()
     301        return hashlib.md5(base).hexdigest()
    302302
    303303    def deleteMessage(self, i):
    304304        """Delete a message
     
    355355        return StringIO.StringIO(self.msgs[i])
    356356
    357357    def getUidl(self, i):
    358         return md5.new(self.msgs[i]).hexdigest()
     358        return hashlib.md5(self.msgs[i]).hexdigest()
    359359
    360360    def deleteMessage(self, i):
    361361        pass
  • twisted/mail/pop3.py

     
    1515import string
    1616import base64
    1717import binascii
    18 import md5
     18import hashlib
    1919import warnings
    2020
    2121from zope.interface import implements, Interface
     
    4545
    4646    def checkPassword(self, password):
    4747        seed = self.magic + password
    48         myDigest = md5.new(seed).hexdigest()
     48        myDigest = hashlib.md5(seed).hexdigest()
    4949        return myDigest == self.digest
    5050
    5151
     
    10321032            self._dispatch(self.command+"_continue", None, line)
    10331033
    10341034    def apopAuthenticate(self, user, password, magic):
    1035         digest = md5.new(magic + password).hexdigest()
     1035        digest = hashlib.md5(magic + password).hexdigest()
    10361036        self.apop(user, digest)
    10371037
    10381038    def apop(self, user, digest):
  • twisted/trial/test/test_loader.py

     
    11
    2 import md5
     2import hashlib
    33import os
    44import shutil
    55
     
    468468#             if isinstance(s, type) or isinstance(s, types.ClassType):
    469469#                 return s.__module__+'.'+s.__name__
    470470            n = runner.name(s)
    471             d = md5.new(n).hexdigest()
     471            d = hashlib.md5(n).hexdigest()
    472472            return d
    473473        self.loadSortedPackages(sillySorter)
    474474
  • twisted/spread/pb.py

     
    6363except ImportError:
    6464    import StringIO
    6565
    66 import md5
     66import hashlib
    6767import random
    6868import new
    6969import types
     
    10061006
    10071007    This is useful for challenge/response authentication.
    10081008    """
    1009     m = md5.new()
     1009    m = hashlib.md5()
    10101010    m.update(password)
    10111011    hashedPassword = m.digest()
    1012     m = md5.new()
     1012    m = hashlib.md5()
    10131013    m.update(hashedPassword)
    10141014    m.update(challenge)
    10151015    doubleHashedPassword = m.digest()
     
    10201020    crap = ''
    10211021    for x in range(random.randrange(15,25)):
    10221022        crap = crap + chr(random.randint(65,90))
    1023     crap = md5.new(crap).digest()
     1023    crap = hashlib.md5(crap).digest()
    10241024    return crap
    10251025
    10261026
     
    13361336
    13371337    # IUsernameHashedPassword:
    13381338    def checkPassword(self, password):
    1339         return self.checkMD5Password(md5.md5(password).digest())
     1339        return self.checkMD5Password(hashlib.md5(password).digest())
    13401340
    13411341
    13421342    # IUsernameMD5Password
    13431343    def checkMD5Password(self, md5Password):
    1344         md = md5.new()
     1344        md = hashlib.md5()
    13451345        md.update(md5Password)
    13461346        md.update(self.challenge)
    13471347        correct = md.digest()