Ticket #2763: hashlib.v2.patch

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

     
    99import os
    1010import errno
    1111import random
    12 import sha
    1312import base64
    1413
    1514from os.path import isabs, exists, normpath, abspath, splitext
     
    2524# modified for inclusion in the standard library.  --glyph
    2625
    2726from twisted.python.runtime import platform
     27from twisted.python.hashlib import sha1
    2828
    2929from twisted.python.win32 import ERROR_FILE_NOT_FOUND, ERROR_PATH_NOT_FOUND
    3030from twisted.python.win32 import ERROR_INVALID_NAME, ERROR_DIRECTORY
     
    120120    """
    121121    Create a pseudorandom, 16-character string for use in secure filenames.
    122122    """
    123     return armor(sha.new(randomBytes(64)).digest())[:16]
     123    return armor(sha1(randomBytes(64)).digest())[:16]
    124124
    125125
    126126
  • twisted/python/otp.py

     
    4848        l = l / 256L
    4949    return result
    5050       
    51 import md5, sha
    52 hashid = {md5: 'md5', sha: 'sha1'}
     51from twisted.python.hashlib import md5, sha1
     52hashid = {md5: 'md5', sha1: 'sha1'}
    5353
    5454INITIALSEQUENCE = 1000
    5555MINIMUMSEQUENCE = 50
     
    8686    def foldDigest(self, otp):
    8787        if self.hash == md5:
    8888            return self.foldDigest128(otp)
    89         if self.hash == sha:
     89        if self.hash == sha1:
    9090            return self.foldDigest160(otp)
    9191   
    9292    def foldDigest128(self, otp128):
     
    120120
    121121    def hashUpdate(self, digest):
    122122        "Run through the hash and fold to 64 bit"
    123         h = self.hash.new(digest)
     123        h = self.hash(digest)
    124124        return self.foldDigest(h.digest())
    125125   
    126126    def generateOTP(self, seed, passwd, sequence):
  • twisted/python/test/test_zipstream.py

     
    66"""
    77import sys
    88import random
    9 import md5
    109import zipfile
    1110
    1211from twisted.python import zipstream, filepath
     12from twisted.python.hashlib import md5
    1313from twisted.trial import unittest
    1414
    1515class FileEntryMixin:
     
    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 = 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 = 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
    1817import sys
    1918from zope.interface import implements, Interface
    2019
    2120# twisted imports
    2221from twisted.python import log, util
     22from twisted.python.hashlib import md5
    2323from twisted.internet import protocol, defer, reactor
    2424
    2525from twisted import cred
     
    132132    pszNonce,
    133133    pszCNonce,
    134134):
    135     m = md5.md5()
     135    m = 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 = md5()
    144144        m.update(HA1)
    145145        m.update(":")
    146146        m.update(pszNonce)
     
    159159    pszDigestUri,
    160160    pszHEntity,
    161161):
    162     m = md5.md5()
     162    m = md5()
    163163    m.update(pszMethod)
    164164    m.update(":")
    165165    m.update(pszDigestUri)
     
    168168        m.update(pszHEntity)
    169169    HA2 = m.digest().encode('hex')
    170170   
    171     m = md5.md5()
     171    m = md5()
    172172    m.update(HA1)
    173173    m.update(":")
    174174    m.update(pszNonce)
  • twisted/conch/test/test_transport.py

     
    55Tests for ssh/transport.py and the classes therein.
    66"""
    77
    8 import md5, sha
    9 
    108try:
    119    import Crypto.Cipher.DES3
    1210except ImportError:
     
    2725from twisted.protocols import loopback
    2826from twisted.python import randbytes
    2927from twisted.python.reflect import qual
     28from twisted.python.hashlib import md5, sha1
    3029from twisted.conch.ssh import service
    3130from twisted.test import proto_helpers
    3231
     
    856855        """
    857856        self.proto.sessionID = 'EF'
    858857
    859         k1 = sha.new('AB' + 'CD'
    860                      + 'K' + self.proto.sessionID).digest()
    861         k2 = sha.new('ABCD' + k1).digest()
     858        k1 = sha1('AB' + 'CD' + 'K' + self.proto.sessionID).digest()
     859        k2 = sha1('ABCD' + k1).digest()
    862860        self.assertEquals(self.proto._getKey('K', 'AB', 'CD'), k1 + k2)
    863861
    864862
     
    11091107        f = common._MPpow(transport.DH_GENERATOR, y, transport.DH_PRIME)
    11101108        sharedSecret = common._MPpow(e, y, transport.DH_PRIME)
    11111109
    1112         h = sha.new()
     1110        h = sha1()
    11131111        h.update(common.NS(self.proto.ourVersionString) * 2)
    11141112        h.update(common.NS(self.proto.ourKexInitPayload) * 2)
    11151113        h.update(common.NS(self.proto.factory.publicKeys['ssh-rsa'].blob()))
     
    11901188        y = common.getMP('\x00\x00\x00\x80' + '\x99' * 128)[0]
    11911189        f = common._MPpow(self.proto.g, y, self.proto.p)
    11921190        sharedSecret = common._MPpow(e, y, self.proto.p)
    1193         h = sha.new()
     1191        h = sha1()
    11941192        h.update(common.NS(self.proto.ourVersionString) * 2)
    11951193        h.update(common.NS(self.proto.ourKexInitPayload) * 2)
    11961194        h.update(common.NS(self.proto.factory.publicKeys['ssh-rsa'].blob()))
     
    12211219        y = common.getMP('\x00\x00\x00\x80' + '\x99' * 128)[0]
    12221220        f = common._MPpow(self.proto.g, y, self.proto.p)
    12231221        sharedSecret = common._MPpow(e, y, self.proto.p)
    1224         h = sha.new()
     1222        h = sha1()
    12251223        h.update(common.NS(self.proto.ourVersionString) * 2)
    12261224        h.update(common.NS(self.proto.ourKexInitPayload) * 2)
    12271225        h.update(common.NS(self.proto.factory.publicKeys['ssh-rsa'].blob()))
     
    13601358        self.calledVerifyHostKey = True
    13611359        self.assertEquals(pubKey, self.blob)
    13621360        self.assertEquals(fingerprint.replace(':', ''),
    1363                           md5.new(pubKey).hexdigest())
     1361                          md5(pubKey).hexdigest())
    13641362        return defer.succeed(True)
    13651363
    13661364
     
    14271425
    14281426        sharedSecret = common._MPpow(transport.DH_GENERATOR,
    14291427                                     self.proto.x, transport.DH_PRIME)
    1430         h = sha.new()
     1428        h = sha1()
    14311429        h.update(common.NS(self.proto.ourVersionString) * 2)
    14321430        h.update(common.NS(self.proto.ourKexInitPayload) * 2)
    14331431        h.update(common.NS(self.blob))
     
    14761474
    14771475        self.test_KEX_DH_GEX_GROUP()
    14781476        sharedSecret = common._MPpow(3, self.proto.x, self.proto.p)
    1479         h = sha.new()
     1477        h = sha1()
    14801478        h.update(common.NS(self.proto.ourVersionString) * 2)
    14811479        h.update(common.NS(self.proto.ourKexInitPayload) * 2)
    14821480        h.update(common.NS(self.blob))
  • twisted/conch/test/test_keys.py

     
    99else:
    1010    from twisted.conch.ssh import keys, common, sexpy, asn1
    1111
     12import os, base64
    1213from twisted.conch.test import keydata
    1314from twisted.python import randbytes
     15from twisted.python.hashlib import sha1
    1416from twisted.trial import unittest
    15 import sha, os, base64
    1617
    1718class SSHKeysHandlingTestCase(unittest.TestCase):
    1819    """
     
    316317        messageSize = 6
    317318        self.assertEquals(keys.pkcs1Pad(data, messageSize),
    318319                '\x01\xff\x00ABC')
    319         hash = sha.new().digest()
     320        hash = sha1().digest()
    320321        messageSize = 40
    321322        self.assertEquals(keys.pkcs1Digest('', messageSize),
    322323                '\x01\xff\xff\xff\x00' + keys.ID_SHA1 + hash)
     
    348349        """
    349350        data = 'data'
    350351        key, sig = self._signDSA(data)
    351         sigData = sha.new(data).digest()
     352        sigData = sha1(data).digest()
    352353        v = key.sign(sigData, '\x55' * 19)
    353354        self.assertEquals(sig, common.NS('ssh-dss') + common.NS(
    354355            Crypto.Util.number.long_to_bytes(v[0], 20) +
  • twisted/conch/scripts/ckeygen.py

     
    99
    1010from twisted.conch.ssh import keys
    1111from twisted.python import log, usage, randbytes
     12from twisted.python.hashlib import md5
    1213
    13 import sys, os, getpass, md5, socket
     14import sys, os, getpass, socket
    1415if getpass.getpass == getpass.unix_getpass:
    1516    try:
    1617        import termios # hack around broken termios
     
    99100        obj = keys.getPublicKeyObject(string)
    100101        print '%s %s %s' % (
    101102            obj.size()+1,
    102             ':'.join(['%02x' % ord(x) for x in md5.new(string).digest()]),
     103            ':'.join(['%02x' % ord(x) for x in md5(string).digest()]),
    103104            os.path.basename(options['filename']))
    104105    except:
    105106        sys.exit('bad key')
     
    173174    print 'Your identification has been saved in %s' % options['filename']
    174175    print 'Your public key has been saved in %s.pub' % options['filename']
    175176    print 'The key fingerprint is:'
    176     print ':'.join(['%02x' % ord(x) for x in md5.new(pubKey).digest()])
     177    print ':'.join(['%02x' % ord(x) for x in md5(pubKey).digest()])
    177178
    178179if __name__ == '__main__':
    179180    run()
  • twisted/conch/ssh/transport.py

     
    1313
    1414# base library imports
    1515import struct
    16 import md5
    17 import sha
    1816import zlib
    1917import array
    2018
     
    2624from twisted.internet import protocol, defer
    2725from twisted.conch import error
    2826from twisted.python import log, randbytes
     27from twisted.python.hashlib import md5, sha1
    2928
    3029# sibling imports
    3130from twisted.conch.ssh import keys
     
    532531        @type sharedSecret: C{str}
    533532        @type exchangeHash: C{str}
    534533        """
    535         k1 = sha.new(sharedSecret + exchangeHash + c + self.sessionID)
     534        k1 = sha1(sharedSecret + exchangeHash + c + self.sessionID)
    536535        k1 = k1.digest()
    537         k2 = sha.new(sharedSecret + exchangeHash + k1).digest()
     536        k2 = sha1(sharedSecret + exchangeHash + k1).digest()
    538537        return k1 + k2
    539538
    540539
     
    723722            y = Util.number.getRandomNumber(512, randbytes.secureRandom)
    724723            serverDHpublicKey = _MPpow(DH_GENERATOR, y, DH_PRIME)
    725724            sharedSecret = _MPpow(clientDHpublicKey, y, DH_PRIME)
    726             h = sha.new()
     725            h = sha1()
    727726            h.update(NS(self.otherVersionString))
    728727            h.update(NS(self.ourVersionString))
    729728            h.update(NS(self.otherKexInitPayload))
     
    792791
    793792        serverDHpublicKey = _MPpow(self.g, y, self.p)
    794793        sharedSecret = _MPpow(clientDHpublicKey, y, self.p)
    795         h = sha.new()
     794        h = sha1()
    796795        h.update(NS(self.otherVersionString))
    797796        h.update(NS(self.ourVersionString))
    798797        h.update(NS(self.otherKexInitPayload))
     
    933932            f, packet = getMP(packet)
    934933            signature, packet = getNS(packet)
    935934            fingerprint = ':'.join([ch.encode('hex') for ch in
    936                                     md5.new(pubKey).digest()])
     935                                    md5(pubKey).digest()])
    937936            d = self.verifyHostKey(pubKey, fingerprint)
    938937            d.addCallback(self._continueKEXDH_REPLY, pubKey, f, signature)
    939938            d.addErrback(
     
    962961        """
    963962        serverKey = keys.Key.fromString(pubKey)
    964963        sharedSecret = _MPpow(f, self.x, DH_PRIME)
    965         h = sha.new()
     964        h = sha1()
    966965        h.update(NS(self.ourVersionString))
    967966        h.update(NS(self.otherVersionString))
    968967        h.update(NS(self.ourKexInitPayload))
     
    992991        f, packet = getMP(packet)
    993992        signature, packet = getNS(packet)
    994993        fingerprint = ':'.join(map(lambda c: '%02x'%ord(c),
    995             md5.new(pubKey).digest()))
     994            md5(pubKey).digest()))
    996995        d = self.verifyHostKey(pubKey, fingerprint)
    997996        d.addCallback(self._continueGEX_REPLY, pubKey, f, signature)
    998997        d.addErrback(
     
    10151014        """
    10161015        serverKey = keys.Key.fromString(pubKey)
    10171016        sharedSecret = _MPpow(f, self.x, self.p)
    1018         h = sha.new()
     1017        h = sha1()
    10191018        h.update(NS(self.ourVersionString))
    10201019        h.update(NS(self.otherVersionString))
    10211020        h.update(NS(self.ourKexInitPayload))
     
    11691168        'none':(None, 0, 0),
    11701169    }
    11711170    macMap = {
    1172         'hmac-sha1': sha,
     1171        'hmac-sha1': sha1,
    11731172        'hmac-md5': md5,
    11741173        'none':None
    11751174     }
     
    12231222            return _DummyCipher()
    12241223        mod = __import__('Crypto.Cipher.%s'%modName, {}, {}, 'x')
    12251224        if counterMode:
    1226             return mod.new(key[:keySize], mod.MODE_CTR, iv[:mod.block_size],
    1227                            counter=_Counter(iv, mod.block_size))
     1225            return mod(key[:keySize], mod.MODE_CTR, iv[:mod.block_size],
     1226                       counter=_Counter(iv, mod.block_size))
    12281227        else:
    1229             return mod.new(key[:keySize], mod.MODE_CBC, iv[:mod.block_size])
     1228            return mod(key[:keySize], mod.MODE_CBC, iv[:mod.block_size])
    12301229
    12311230
    12321231    def _getMAC(self, mac, key):
     
    12441243        if not mod:
    12451244            return (None, '', '', 0)
    12461245        #if not hasattr(mod, 'digest_size'):
    1247         #     ds = len(mod.new().digest())
     1246        #     ds = len(mod().digest())
    12481247        #else:
    1249         ds = mod.digest_size
     1248        ds = mod().digest_size
    12501249        key = key[:ds] + '\x00' * (64 - ds)
    12511250        i = XOR.new('\x36').encrypt(key)
    12521251        o = XOR.new('\x5c').encrypt(key)
     
    12871286            return ''
    12881287        data = struct.pack('>L', seqid) + data
    12891288        mod, i, o, ds = self.outMAC
    1290         inner = mod.new(i + data)
    1291         outer = mod.new(o + inner.digest())
     1289        inner = mod(i + data)
     1290        outer = mod(o + inner.digest())
    12921291        return outer.digest()
    12931292
    12941293
     
    13091308            return mac == ''
    13101309        data = struct.pack('>L', seqid) + data
    13111310        mod, i, o, ds = self.inMAC
    1312         inner = mod.new(i + data)
    1313         outer = mod.new(o + inner.digest())
     1311        inner = mod(i + data)
     1312        outer = mod(o + inner.digest())
    13141313        return mac == outer.digest()
    13151314
    13161315
  • twisted/conch/ssh/keys.py

     
    1212
    1313# base library imports
    1414import base64
    15 import sha, md5
    1615import warnings
    1716
    1817# external library imports
     
    2221
    2322# twisted
    2423from twisted.python import randbytes
     24from twisted.python.hashlib import md5, sha1
    2525
    2626# sibling imports
    2727from twisted.conch.ssh import asn1, common, sexpy
     
    207207                len(ivdata), 2)])
    208208            if not passphrase:
    209209                raise EncryptedKeyError('encrypted key with no passphrase')
    210             ba = md5.new(passphrase + iv).digest()
    211             bb = md5.new(ba + passphrase + iv).digest()
     210            ba = md5(passphrase + iv).digest()
     211            bb = md5(ba + passphrase + iv).digest()
    212212            decKey = (ba + bb)[:24]
    213213            b64Data = base64.decodestring(''.join(lines[3:-1]))
    214214            keyData = DES3.new(decKey, DES3.MODE_CBC, iv).decrypt(b64Data)
     
    575575                hexiv = ''.join(['%02X' % ord(x) for x in iv])
    576576                lines.append('Proc-Type: 4,ENCRYPTED')
    577577                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()
     578                ba = md5(extra + iv).digest()
     579                bb = md5(ba + extra + iv).digest()
    580580                encKey = (ba + bb)[:24]
    581581            asn1Data = asn1.pack([objData])
    582582            if extra:
     
    659659            signature = self.keyObject.sign(digest, '')[0]
    660660            ret = common.NS(Util.number.long_to_bytes(signature))
    661661        elif self.type() == 'DSA':
    662             digest = sha.new(data).digest()
     662            digest = sha1(data).digest()
    663663            randomBytes = randbytes.secureRandom(19)
    664664            sig = self.keyObject.sign(digest, randomBytes)
    665665            # SSH insists that the DSS signature blob be two 160-bit integers
     
    688688            signature = common.getNS(signature)[0]
    689689            numbers = [Util.number.bytes_to_long(n) for n in signature[:20],
    690690                    signature[20:]]
    691             digest = sha.new(data).digest()
     691            digest = sha1(data).digest()
    692692        return self.keyObject.verify(digest, numbers)
    693693
    694694def getPublicKeyString(filename=None, line=0, data=''):
     
    841841    @type data: C{str}
    842842    @type messageLength: C{str}
    843843    """
    844     digest = sha.new(data).digest()
     844    digest = sha1(data).digest()
    845845    return pkcs1Pad(ID_SHA1+digest, messageLength)
    846846
    847847def lenSig(obj):
  • twisted/words/test/test_jabbercomponent.py

     
    55Tests for L{twisted.words.protocols.jabber.component}
    66"""
    77
    8 import sha
    9 
    108from twisted.python import failure
     9from twisted.python.hashlib import sha1
    1110from twisted.trial import unittest
    1211from twisted.words.protocols.jabber import component, xmlstream
    1312from twisted.words.protocols.jabber.jid import JID
     
    5049        handshake = self.output[-1]
    5150        self.assertEquals('handshake', handshake.name)
    5251        self.assertEquals('test:component', handshake.uri)
    53         self.assertEquals(sha.new("%s%s" % ('12345', 'secret')).hexdigest(),
     52        self.assertEquals(sha1("%s%s" % ('12345', 'secret')).hexdigest(),
    5453                          unicode(handshake))
    5554
    5655        # successful authentication
     
    8079        xs.dataReceived("<stream:stream xmlns='jabber:component:accept' xmlns:stream='http://etherx.jabber.org/streams' from='cjid' id='12345'>")
    8180
    8281        # Calculate what we expect the handshake value to be
    83         hv = sha.new("%s%s" % ("12345", "secret")).hexdigest()
     82        hv = sha1("%s%s" % ("12345", "secret")).hexdigest()
    8483
    8584        self.assertEquals(outlist[1], "<handshake>%s</handshake>" % (hv))
    8685
  • twisted/words/test/test_jabberclient.py

     
    55Tests for L{twisted.words.protocols.jabber.client}
    66"""
    77
    8 import sha
     8from twisted.python.hashlib import sha1
    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(sha1('12345secret').hexdigest(),
    121121                          unicode(iq.query.digest))
    122122        self.assertEquals('resource', unicode(iq.query.resource))
    123123
  • twisted/words/protocols/msn.py

     
    7373@author: Sam Jordan
    7474"""
    7575
    76 import types, operator, os, md5
     76import types, operator, os
    7777from random import randint
    7878from urllib import quote, unquote
    7979
    8080from twisted.python import failure, log
     81from twisted.python.hashlib import md5
    8182from twisted.internet import reactor
    8283from twisted.internet.defer import Deferred
    8384from twisted.internet.protocol import ClientFactory
     
    856857    def handle_CHL(self, params):
    857858        checkParamLen(len(params), 2, 'CHL')
    858859        self.sendLine("QRY %s msmsgs@msnmsgr.com 32" % self._nextTransactionID())
    859         self.transport.write(md5.md5(params[1] + MSN_CHALLENGE_STR).hexdigest())
     860        self.transport.write(md5(params[1] + MSN_CHALLENGE_STR).hexdigest())
    860861
    861862    def handle_QRY(self, params):
    862863        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
    1111
    1212from zope.interface import Interface, Attribute, implements
    1313
     14from twisted.python.hashlib import md5
     15
    1416class ISASLMechanism(Interface):
    1517    name = Attribute("""Common name for the SASL Mechanism.""")
    1618
     
    178180        """
    179181
    180182        def H(s):
    181             return md5.new(s).digest()
     183            return md5(s).digest()
    182184
    183185        def HEX(n):
    184186            return binascii.b2a_hex(n)
     
    221223
    222224
    223225    def _gen_nonce(self):
    224         return md5.new("%s:%s:%s" % (str(random.random()) , str(time.gmtime()),str(os.getpid()))).hexdigest()
     226        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    from twisted.python.hashlib import sha1
     46    return sha1("%s%s" % (sid, password)).hexdigest()
    4747
    4848
    4949
  • twisted/words/protocols/oscar.py

     
    1111
    1212from __future__ import nested_scopes
    1313
    14 from twisted.internet import reactor, defer, protocol
    15 from twisted.python import log
    16 
    1714import struct
    18 import md5
    1915import string
    2016import socket
    2117import random
     
    2319import types
    2420import re
    2521
     22from twisted.internet import reactor, defer, protocol
     23from twisted.python import log
     24from twisted.python.hashlib import md5
     25
    2626def logPacketData(data):
    2727    lines = len(data)/16
    2828    if lines*16 != len(data): lines=lines+1
     
    6262    return dict,data
    6363
    6464def encryptPasswordMD5(password,key):
    65     m=md5.new()
     65    m=md5()
    6666    m.update(key)
    67     m.update(md5.new(password).digest())
     67    m.update(md5(password).digest())
    6868    m.update("AOL Instant Messenger (SM)")
    6969    return m.digest()
    7070
  • twisted/web2/test/test_httpauth.py

     
    1 import md5
     1from twisted.python.hashlib import md5
    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                md5('username:test realm:password').hexdigest()))
    267267
    268268        self.failIf(creds.checkHash(
    269                 md5.md5('username:test realm:bogus').hexdigest()))
     269                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 = 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 = md5(key + 'this is not the right pkey').hexdigest()
    394394
    395395        badChecksum = '%s-%s' % (digest,
    396396                                 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

     
    55
    66http://www.faqs.org/rfcs/rfc2617.html
    77"""
     8import sys
    89import time
     10import random
    911
    1012from twisted.cred import credentials, error
    1113from zope.interface import implements, Interface
    1214
    1315from twisted.web2.auth.interfaces import ICredentialFactory
     16from twisted.python.hashlib import md5, sha1
    1417
    15 import md5, sha
    16 import random, sys
    17 
    1818# The digest math
    1919
    2020algorithms = {
    21     'md5': md5.new,
    22     'md5-sess': md5.new,
    23     'sha': sha.new,
     21    'md5': md5,
     22    'md5-sess': md5,
     23    'sha': 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 = 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 = md5(key + self.privateKey).hexdigest()
    279279        if digest != opaqueParts[0]:
    280280            raise error.LoginFailed('Invalid response, invalid opaque value')
    281281
  • 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:
    1414    import cPickle as pickle
    1515except ImportError:
     
    1919except ImportError:
    2020    import StringIO
    2121from twisted.python import log, runtime
     22from twisted.python.hashlib import md5
    2223from twisted.persisted import styles
    2324from zope.interface import implements, Interface
    2425
     
    3132    leftover = len(data) % cipher.block_size
    3233    if leftover:
    3334        data += ' '*(cipher.block_size - leftover)
    34     return cipher.new(md5.new(passphrase).digest()[:16]).encrypt(data)
     35    return cipher.new(md5(passphrase).digest()[:16]).encrypt(data)
    3536
    3637def _decrypt(passphrase, data):
    3738    from Crypto.Cipher import AES
    38     return AES.new(md5.new(passphrase).digest()[:16]).decrypt(data)
     39    return AES.new(md5(passphrase).digest()[:16]).decrypt(data)
    3940
    4041
    4142class 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
     25from twisted.python.hashlib import md5
    2526import os
    2627import StringIO
    2728from zope.interface import implements, Interface
     
    5354
    5455        if not self.getHeader('Message-ID'):
    5556            s = str(time.time()) + self.body
    56             id = hexdigest(md5.md5(s)) + '@' + socket.gethostname()
     57            id = hexdigest(md5(s)) + '@' + socket.gethostname()
    5758            self.putHeader('Message-ID', '<%s>' % id)
    5859
    5960        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        from twisted.python.hashlib import md5
     511        import random
    511512        self.counter = self.counter + 1
    512         return md5.new("%s_%s" % (str(random.random()) , str(self.counter))).hexdigest()
     513        return md5("%s_%s" % (str(random.random()) , str(self.counter))).hexdigest()
    513514
    514515    def makeSession(self):
    515516        """
  • twisted/web/test/test_httpauth.py

     
    55Tests for L{twisted.web._auth}.
    66"""
    77
    8 import md5, sha
    98
    109from zope.interface import implements
    1110from zope.interface.verify import verifyObject
    1211
     12from twisted.python.hashlib import md5, sha1
    1313from twisted.trial import unittest
    1414from twisted.cred import error, portal
    1515from twisted.cred.checkers import InMemoryUsernamePasswordDatabaseDontUse
     
    181181            self.algorithm, self.realm)
    182182
    183183
    184     def test_MD5HashA1(self, _algorithm='md5', _hash=md5.md5):
     184    def test_MD5HashA1(self, _algorithm='md5', _hash=md5):
    185185        """
    186186        L{calcHA1} accepts the C{'md5'} algorithm and returns an MD5 hash of
    187187        its parameters, excluding the nonce and cnonce.
     
    203203        hashA1 = calcHA1('md5-sess', self.username, self.realm, self.password,
    204204                         nonce, self.cnonce)
    205205        a1 = '%s:%s:%s' % (self.username, self.realm, self.password)
    206         ha1 = md5.md5(a1).digest()
     206        ha1 = md5(a1).digest()
    207207        a1 = '%s:%s:%s' % (ha1, nonce, self.cnonce)
    208         expected = md5.md5(a1).hexdigest()
     208        expected = md5(a1).hexdigest()
    209209        self.assertEqual(hashA1, expected)
    210210
    211211
     
    214214        L{calcHA1} accepts the C{'sha'} algorithm and returns a SHA hash of its
    215215        parameters, excluding the nonce and cnonce.
    216216        """
    217         self.test_MD5HashA1('sha', sha.sha)
     217        self.test_MD5HashA1('sha', sha1)
    218218
    219219
    220     def test_MD5HashA2Auth(self, _algorithm='md5', _hash=md5.md5):
     220    def test_MD5HashA2Auth(self, _algorithm='md5', _hash=md5):
    221221        """
    222222        L{calcHA2} accepts the C{'md5'} algorithm and returns an MD5 hash of
    223223        its arguments, excluding the entity hash for QOP other than
     
    230230        self.assertEqual(hashA2, expected)
    231231
    232232
    233     def test_MD5HashA2AuthInt(self, _algorithm='md5', _hash=md5.md5):
     233    def test_MD5HashA2AuthInt(self, _algorithm='md5', _hash=md5):
    234234        """
    235235        L{calcHA2} accepts the C{'md5'} algorithm and returns an MD5 hash of
    236236        its arguments, including the entity hash for QOP of C{'auth-int'}.
     
    265265        its arguments, excluding the entity hash for QOP other than
    266266        C{'auth-int'}.
    267267        """
    268         self.test_MD5HashA2Auth('sha', sha.sha)
     268        self.test_MD5HashA2Auth('sha', sha1)
    269269
    270270
    271271    def test_SHAHashA2AuthInt(self):
     
    273273        L{calcHA2} accepts the C{'sha'} algorithm and returns a SHA hash of
    274274        its arguments, including the entity hash for QOP of C{'auth-int'}.
    275275        """
    276         self.test_MD5HashA2AuthInt('sha', sha.sha)
     276        self.test_MD5HashA2AuthInt('sha', sha1)
    277277
    278278
    279     def test_MD5HashResponse(self, _algorithm='md5', _hash=md5.md5):
     279    def test_MD5HashResponse(self, _algorithm='md5', _hash=md5):
    280280        """
    281281        L{calcResponse} accepts the C{'md5'} algorithm and returns an MD5 hash
    282282        of its parameters, excluding the nonce count, client nonce, and QoP
     
    308308        of its parameters, excluding the nonce count, client nonce, and QoP
    309309        value if the nonce count and client nonce are C{None}
    310310        """
    311         self.test_MD5HashResponse('sha', sha.sha)
     311        self.test_MD5HashResponse('sha', sha1)
    312312
    313313
    314     def test_MD5HashResponseExtra(self, _algorithm='md5', _hash=md5.md5):
     314    def test_MD5HashResponseExtra(self, _algorithm='md5', _hash=md5):
    315315        """
    316316        L{calcResponse} accepts the C{'md5'} algorithm and returns an MD5 hash
    317317        of its parameters, including the nonce count, client nonce, and QoP
     
    348348        of its parameters, including the nonce count, client nonce, and QoP
    349349        value if they are specified.
    350350        """
    351         self.test_MD5HashResponseExtra('sha', sha.sha)
     351        self.test_MD5HashResponseExtra('sha', sha1)
    352352
    353353
    354354    def makeRequest(self, method='GET', clientAddress=None):
     
    639639        self.assertTrue(verifyObject(IUsernameDigestHash, creds))
    640640
    641641        cleartext = '%s:%s:%s' % (self.username, self.realm, self.password)
    642         hash = md5.md5(cleartext)
     642        hash = md5(cleartext)
    643643        self.assertTrue(creds.checkHash(hash.hexdigest()))
    644644        hash.update('wrong')
    645645        self.assertFalse(creds.checkHash(hash.hexdigest()))
     
    761761        key = '%s,%s,%s' % (challenge['nonce'],
    762762                            self.clientAddress.host,
    763763                            '-137876876')
    764         digest = md5.md5(key + credentialFactory.privateKey).hexdigest()
     764        digest = md5(key + credentialFactory.privateKey).hexdigest()
    765765        ekey = b64encode(key)
    766766
    767767        oldNonceOpaque = '%s-%s' % (digest, ekey.strip('\n'))
     
    786786                            self.clientAddress.host,
    787787                            '0')
    788788
    789         digest = md5.md5(key + 'this is not the right pkey').hexdigest()
     789        digest = md5(key + 'this is not the right pkey').hexdigest()
    790790        badChecksum = '%s-%s' % (digest, b64encode(key))
    791791
    792792        self.assertRaises(
  • twisted/web/woven/guard.py

     
    1616
    1717import random
    1818import time
    19 import md5
    2019import urllib
    2120
    2221# Twisted Imports
    2322
    2423from twisted.python import log, components
     24from twisted.python.hashlib import md5
    2525from twisted.web.resource import Resource, IResource
    2626from twisted.web.util import redirectTo, Redirect, DeferredResource
    2727from twisted.web.static import addSlash
     
    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 md5("%s_%s" % (str(random.random()) , str(time.time()))).hexdigest()
    3333
    3434class GuardSession(components.Componentized):
    3535    """A user's session with a system.
  • twisted/web/_auth/digest.py

     
    99"""
    1010
    1111import time
    12 import md5, sha
    1312
    1413from zope.interface import implements
    1514
     15from twisted.python.hashlib import md5, sha1
    1616from twisted.python.randbytes import secureRandom
    1717from twisted.cred import credentials, error
    1818from twisted.web.iweb import ICredentialFactory, IUsernameDigestHash
     
    2121# The digest math
    2222
    2323algorithms = {
    24     'md5': md5.new,
     24    'md5': md5,
    2525
    2626    # md5-sess is more complicated than just another algorithm.  It requires
    2727    # H(A1) state to be remembered from the first WWW-Authenticate challenge
     
    3030    # recalculate H(A1) each time an Authorization header is received.  Read
    3131    # RFC 2617, section 3.2.2.2 and do not try to make DigestCredentialFactory
    3232    # support this unless you completely understand it. -exarkun
    33     'md5-sess': md5.new,
     33    'md5-sess': md5,
    3434
    35     'sha': sha.new,
     35    'sha': sha1,
    3636}
    3737
    3838# DigestCalcHA1
     
    257257        if clientip is None:
    258258            clientip = ''
    259259        key = "%s,%s,%s" % (nonce, clientip, now)
    260         digest = md5.new(key + self.privateKey).hexdigest()
     260        digest = md5(key + self.privateKey).hexdigest()
    261261        ekey = key.encode('base64')
    262262        return "%s-%s" % (digest, ekey.strip('\n'))
    263263
     
    315315                'Invalid response, incompatible opaque/nonce too old')
    316316
    317317        # Verify the digest
    318         digest = md5.new(key + self.privateKey).hexdigest()
     318        digest = md5(key + self.privateKey).hexdigest()
    319319        if digest != opaqueParts[0]:
    320320            raise error.LoginFailed('Invalid response, invalid opaque value')
    321321
  • twisted/web/monitor.py

     
    44#
    55from twisted.web import client
    66from twisted.internet import reactor
    7 import md5
     7from twisted.python.hashlib import md5
    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 = md5()
    5757        m.update(p)
    5858        self.gotMD5(m.digest())
    5959
  • twisted/cred/util.py

     
    1212"""
    1313
    1414# System Imports
    15 import md5
    1615import random
    1716
     17from twisted.python.hashlib import md5
    1818from twisted.cred.error import Unauthorized
    1919
    2020def respond(challenge, password):
    2121    """Respond to a challenge.
    2222    This is useful for challenge/response authentication.
    2323    """
    24     m = md5.new()
     24    m = md5()
    2525    m.update(password)
    2626    hashedPassword = m.digest()
    27     m = md5.new()
     27    m = md5()
    2828    m.update(hashedPassword)
    2929    m.update(challenge)
    3030    doubleHashedPassword = m.digest()
     
    3636    crap = ''
    3737    for x in range(random.randrange(15,25)):
    3838        crap = crap + chr(random.randint(65,90))
    39     crap = md5.new(crap).digest()
     39    crap = md5(crap).digest()
    4040    return crap
  • twisted/mail/test/test_mail.py

     
    77
    88import os
    99import errno
    10 import md5
    1110import shutil
    1211import pickle
    1312import StringIO
     
    3231from twisted.internet import address
    3332from twisted.python import failure
    3433from twisted.python.filepath import FilePath
     34from twisted.python.hashlib import md5
    3535
    3636from twisted import mail
    3737import twisted.mail.mail
     
    587587        shutil.rmtree(self.tmpdir)
    588588
    589589    def testAuthenticateAPOP(self):
    590         resp = md5.new(self.P.magic + 'password').hexdigest()
     590        resp = 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 = 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 = md5('wrong digest').hexdigest()
    609609        return self.assertFailure(
    610610            self.P.authenticateUserAPOP('user', resp),
    611611            cred.error.UnauthorizedLogin)
  • twisted/mail/pop3client.py

     
    1010@author: Jp Calderone
    1111"""
    1212
    13 import re, md5
     13import re
    1414
    1515from twisted.python import log
     16from twisted.python.hashlib import md5
    1617from twisted.internet import defer
    1718from twisted.protocols import basic
    1819from twisted.protocols import policies
     
    485486    def _apop(self, username, password, challenge):
    486487        # Internal helper.  Computes and sends an APOP response.  Returns
    487488        # a Deferred that fires when the server responds to the response.
    488         digest = md5.new(challenge + password).hexdigest()
     489        digest = md5(challenge + password).hexdigest()
    489490        return self.apop(username, digest)
    490491
    491492    def apop(self, username, digest):
  • twisted/mail/maildir.py

     
    1212import stat
    1313import socket
    1414import time
    15 import md5
    1615import cStringIO
    1716
    1817from zope.interface import implements
     
    2726from twisted.protocols import basic
    2827from twisted.persisted import dirdbm
    2928from twisted.python import log, failure
     29from twisted.python.hashlib import md5
    3030from twisted.mail import mail
    3131from twisted.mail import alias
    3232from twisted.internet import interfaces, defer, reactor
     
    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 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 md5(self.msgs[i]).hexdigest()
    359359
    360360    def deleteMessage(self, i):
    361361        pass
  • twisted/mail/pop3.py

     
    1414import string
    1515import base64
    1616import binascii
    17 import md5
    1817import warnings
    1918
    2019from zope.interface import implements, Interface
     
    2625from twisted.internet import defer
    2726from twisted.internet import interfaces
    2827from twisted.python import log
     28from twisted.python.hashlib import md5
    2929
    3030from twisted import cred
    3131import twisted.cred.error
     
    4444
    4545    def checkPassword(self, password):
    4646        seed = self.magic + password
    47         myDigest = md5.new(seed).hexdigest()
     47        myDigest = md5(seed).hexdigest()
    4848        return myDigest == self.digest
    4949
    5050
     
    10311031            self._dispatch(self.command+"_continue", None, line)
    10321032
    10331033    def apopAuthenticate(self, user, password, magic):
    1034         digest = md5.new(magic + password).hexdigest()
     1034        digest = md5(magic + password).hexdigest()
    10351035        self.apop(user, digest)
    10361036
    10371037    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
    55from OpenSSL import SSL, crypto
    66
    77from twisted.python import reflect, util
     8from twisted.python.hashlib import md5
    89from twisted.internet.defer import Deferred
    910from twisted.internet.error import VerifyError, CertificateError
    1011
     
    451452        MD5 hex digest of signature on an empty certificate request with this
    452453        key.
    453454        """
    454         return md5.md5(self._emptyReq).hexdigest()
     455        return md5(self._emptyReq).hexdigest()
    455456
    456457
    457458    def inspect(self):
     
    725726            ctx.set_options(self._OP_ALL)
    726727
    727728        if self.enableSessions:
    728             sessionName = md5.md5("%s-%d" % (reflect.qual(self.__class__), _sessionCounter())).hexdigest()
     729            sessionName = md5("%s-%d" % (reflect.qual(self.__class__), _sessionCounter())).hexdigest()
    729730            ctx.set_session_id(sessionName)
    730731
    731732        return ctx
  • twisted/trial/test/test_loader.py

     
    55Tests for loading tests by name.
    66"""
    77
    8 import md5
    98import os
    109import shutil
    1110import sys
    1211
    1312from twisted.python import util
     13from twisted.python.hashlib import md5
    1414from twisted.trial.test import packages
    1515from twisted.trial import runner, reporter, unittest
    1616from twisted.trial.itrial import ITestCase
     
    484484#             if isinstance(s, type) or isinstance(s, types.ClassType):
    485485#                 return s.__module__+'.'+s.__name__
    486486            n = runner.name(s)
    487             d = md5.new(n).hexdigest()
     487            d = md5(n).hexdigest()
    488488            return d
    489489        self.loadSortedPackages(sillySorter)
    490490
  • twisted/spread/pb.py

     
    2727@author: Glyph Lefkowitz
    2828"""
    2929
    30 import md5
    3130import random
    3231import new
    3332import types
     
    3837from twisted.python import log, failure, reflect
    3938from twisted.python.versions import Version
    4039from twisted.python.deprecate import deprecated
     40from twisted.python.hashlib import md5
    4141from twisted.internet import defer, protocol
    4242from twisted.cred.portal import Portal
    4343from twisted.cred.credentials import IAnonymous, ICredentials
     
    997997
    998998    This is useful for challenge/response authentication.
    999999    """
    1000     m = md5.new()
     1000    m = md5()
    10011001    m.update(password)
    10021002    hashedPassword = m.digest()
    1003     m = md5.new()
     1003    m = md5()
    10041004    m.update(hashedPassword)
    10051005    m.update(challenge)
    10061006    doubleHashedPassword = m.digest()
     
    10111011    crap = ''
    10121012    for x in range(random.randrange(15,25)):
    10131013        crap = crap + chr(random.randint(65,90))
    1014     crap = md5.new(crap).digest()
     1014    crap = md5(crap).digest()
    10151015    return crap
    10161016
    10171017
     
    13401340
    13411341    # IUsernameHashedPassword:
    13421342    def checkPassword(self, password):
    1343         return self.checkMD5Password(md5.md5(password).digest())
     1343        return self.checkMD5Password(md5(password).digest())
    13441344
    13451345
    13461346    # IUsernameMD5Password
    13471347    def checkMD5Password(self, md5Password):
    1348         md = md5.new()
     1348        md = md5()
    13491349        md.update(md5Password)
    13501350        md.update(self.challenge)
    13511351        correct = md.digest()