Ticket #7919: hashcompat2.diff

File hashcompat2.diff, 17.6 KB (added by Karen Tracey, 16 years ago)

Let's try that patch again without the unrelated mysql base changes...that was for testing out a different fix

  • django/db/backends/util.py

     
    11import datetime
    2 import md5
    32from time import time
     3from django.utils.hashcompat import md5_constructor
    44
    55try:
    66    import decimal
     
    114114    if length is None or len(name) <= length:
    115115        return name
    116116
    117     hash = md5.md5(name).hexdigest()[:4]
     117    hash = md5_constructor(name).hexdigest()[:4]
    118118
    119119    return '%s%s' % (name[:length-4], hash)
    120120
  • django/core/cache/backends/filebased.py

     
    11"File-based cache backend"
    22
    3 import md5
    43import os, time
    54try:
    65    import cPickle as pickle
    76except ImportError:
    87    import pickle
    98from django.core.cache.backends.base import BaseCache
     9from django.utils.hashcompat import md5_constructor
    1010
    1111class CacheClass(BaseCache):
    1212    def __init__(self, dir, params):
     
    137137        Thus, a cache key of "foo" gets turnned into a file named
    138138        ``{cache-dir}ac/bd/18db4cc2f85cedef654fccc4a4d8``.
    139139        """
    140         path = md5.new(key.encode('utf-8')).hexdigest()
     140        path = md5_constructor(key.encode('utf-8')).hexdigest()
    141141        path = os.path.join(path[:2], path[2:4], path[4:])
    142142        return os.path.join(self._dir, path)
    143143
  • django/contrib/formtools/wizard.py

     
    1010from django.shortcuts import render_to_response
    1111from django.template.context import RequestContext
    1212import cPickle as pickle
    13 import md5
     13from django.utils.hashcompat import md5_constructor
    1414
    1515class FormWizard(object):
    1616    # Dictionary of extra template context variables.
     
    150150        # Use HIGHEST_PROTOCOL because it's the most efficient. It requires
    151151        # Python 2.3, but Django requires 2.3 anyway, so that's OK.
    152152        pickled = pickle.dumps(data, pickle.HIGHEST_PROTOCOL)
    153         return md5.new(pickled).hexdigest()
     153        return md5_constructor(pickled).hexdigest()
    154154
    155155    def determine_step(self, request, *args, **kwargs):
    156156        """
  • django/contrib/formtools/preview.py

     
    77from django.shortcuts import render_to_response
    88from django.template.context import RequestContext
    99import cPickle as pickle
    10 import md5
     10from django.utils.hashcompat import md5_constructor
    1111
    1212AUTO_ID = 'formtools_%s' # Each form here uses this as its auto_id parameter.
    1313
     
    109109        # Use HIGHEST_PROTOCOL because it's the most efficient. It requires
    110110        # Python 2.3, but Django requires 2.3 anyway, so that's OK.
    111111        pickled = pickle.dumps(data, pickle.HIGHEST_PROTOCOL)
    112         return md5.new(pickled).hexdigest()
     112        return md5_constructor(pickled).hexdigest()
    113113
    114114    def failed_hash(self, request):
    115115        "Returns an HttpResponse in the case of an invalid security hash."
  • django/contrib/comments/models.py

     
    2929        'pa,ra') and target (something like 'lcom.eventtimes:5157'). Used to
    3030        validate that submitted form options have not been tampered-with.
    3131        """
    32         import md5
    33         return md5.new(options + photo_options + rating_options + target + settings.SECRET_KEY).hexdigest()
     32        from django.utils.hashcompat import md5_constructor
     33        return md5_constructor(options + photo_options + rating_options + target + settings.SECRET_KEY).hexdigest()
    3434
    3535    def get_rating_options(self, rating_string):
    3636        """
  • django/contrib/admin/views/decorators.py

     
    11import base64
    2 import md5
    32import cPickle as pickle
    43try:
    54    from functools import wraps
     
    1211from django.contrib.auth import authenticate, login
    1312from django.shortcuts import render_to_response
    1413from django.utils.translation import ugettext_lazy, ugettext as _
     14from django.utils.hashcompat import md5_constructor
    1515
    1616ERROR_MESSAGE = ugettext_lazy("Please enter a correct username and password. Note that both fields are case-sensitive.")
    1717LOGIN_FORM_KEY = 'this_is_the_login_form'
     
    3535
    3636def _encode_post_data(post_data):
    3737    pickled = pickle.dumps(post_data)
    38     pickled_md5 = md5.new(pickled + settings.SECRET_KEY).hexdigest()
     38    pickled_md5 = md5_constructor(pickled + settings.SECRET_KEY).hexdigest()
    3939    return base64.encodestring(pickled + pickled_md5)
    4040
    4141def _decode_post_data(encoded_data):
    4242    encoded_data = base64.decodestring(encoded_data)
    4343    pickled, tamper_check = encoded_data[:-32], encoded_data[-32:]
    44     if md5.new(pickled + settings.SECRET_KEY).hexdigest() != tamper_check:
     44    if md5_constructor(pickled + settings.SECRET_KEY).hexdigest() != tamper_check:
    4545        from django.core.exceptions import SuspiciousOperation
    4646        raise SuspiciousOperation, "User may have tampered with session cookie."
    4747    return pickle.loads(pickled)
  • django/contrib/admin/sites.py

     
    1212import base64
    1313import cPickle as pickle
    1414import datetime
    15 import md5
     15from django.utils.hashcompat import md5_constructor
    1616import re
    1717
    1818ERROR_MESSAGE = ugettext_lazy("Please enter a correct username and password. Note that both fields are case-sensitive.")
     
    2929def _encode_post_data(post_data):
    3030    from django.conf import settings
    3131    pickled = pickle.dumps(post_data)
    32     pickled_md5 = md5.new(pickled + settings.SECRET_KEY).hexdigest()
     32    pickled_md5 = md5_constructor(pickled + settings.SECRET_KEY).hexdigest()
    3333    return base64.encodestring(pickled + pickled_md5)
    3434
    3535def _decode_post_data(encoded_data):
    3636    from django.conf import settings
    3737    encoded_data = base64.decodestring(encoded_data)
    3838    pickled, tamper_check = encoded_data[:-32], encoded_data[-32:]
    39     if md5.new(pickled + settings.SECRET_KEY).hexdigest() != tamper_check:
     39    if md5_constructor(pickled + settings.SECRET_KEY).hexdigest() != tamper_check:
    4040        from django.core.exceptions import SuspiciousOperation
    4141        raise SuspiciousOperation, "User may have tampered with session cookie."
    4242    return pickle.loads(pickled)
  • django/contrib/csrf/middleware.py

     
    88from django.conf import settings
    99from django.http import HttpResponseForbidden
    1010from django.utils.safestring import mark_safe
    11 import md5
     11from django.utils.hashcompat import md5_constructor
    1212import re
    1313import itertools
    1414
     
    2020_HTML_TYPES = ('text/html', 'application/xhtml+xml')   
    2121
    2222def _make_token(session_id):
    23     return md5.new(settings.SECRET_KEY + session_id).hexdigest()
     23    return md5_constructor(settings.SECRET_KEY + session_id).hexdigest()
    2424
    2525class CsrfMiddleware(object):
    2626    """Django middleware that adds protection against Cross Site
  • django/contrib/auth/tokens.py

     
    5050        # last_login will also change), we produce a hash that will be
    5151        # invalid as soon as it is used.
    5252        # We limit the hash to 20 chars to keep URL short
    53         import sha
    54         hash = sha.new(settings.SECRET_KEY + unicode(user.id) +
    55                        user.password + unicode(user.last_login) +
    56                        unicode(timestamp)).hexdigest()[::2]
     53        from django.utils.hashcompat import sha_constructor
     54        hash = sha_constructor(settings.SECRET_KEY + unicode(user.id) +
     55                               user.password + unicode(user.last_login) +
     56                               unicode(timestamp)).hexdigest()[::2]
    5757        return "%s-%s" % (ts_b36, hash)
    5858
    5959    def _num_days(self, dt):
  • django/contrib/sessions/backends/base.py

     
    11import base64
    2 import md5
    32import os
    43import random
    54import sys
     
    1211
    1312from django.conf import settings
    1413from django.core.exceptions import SuspiciousOperation
     14from django.utils.hashcompat import md5_constructor
    1515
    16 
    1716class SessionBase(object):
    1817    """
    1918    Base class for all Session classes.
     
    7372    def encode(self, session_dict):
    7473        "Returns the given session dictionary pickled and encoded as a string."
    7574        pickled = pickle.dumps(session_dict, pickle.HIGHEST_PROTOCOL)
    76         pickled_md5 = md5.new(pickled + settings.SECRET_KEY).hexdigest()
     75        pickled_md5 = md5_constructor(pickled + settings.SECRET_KEY).hexdigest()
    7776        return base64.encodestring(pickled + pickled_md5)
    7877
    7978    def decode(self, session_data):
    8079        encoded_data = base64.decodestring(session_data)
    8180        pickled, tamper_check = encoded_data[:-32], encoded_data[-32:]
    82         if md5.new(pickled + settings.SECRET_KEY).hexdigest() != tamper_check:
     81        if md5_constructor(pickled + settings.SECRET_KEY).hexdigest() != tamper_check:
    8382            raise SuspiciousOperation("User tampered with session cookie.")
    8483        try:
    8584            return pickle.loads(pickled)
     
    117116            # No getpid() in Jython, for example
    118117            pid = 1
    119118        while 1:
    120             session_key = md5.new("%s%s%s%s" % (random.randint(0, sys.maxint - 1),
    121                                   pid, time.time(), settings.SECRET_KEY)).hexdigest()
     119            session_key = md5_constructor("%s%s%s%s" % (random.randint(0, sys.maxint - 1),
     120                                          pid, time.time(), settings.SECRET_KEY)).hexdigest()
    122121            if not self.exists(session_key):
    123122                break
    124123        return session_key
  • django/contrib/sessions/models.py

     
    11import base64
    2 import md5
    32import cPickle as pickle
    43
    54from django.db import models
    65from django.utils.translation import ugettext_lazy as _
    76from django.conf import settings
     7from django.utils.hashcompat import md5_constructor
    88
    99
    1010class SessionManager(models.Manager):
     
    1313        Returns the given session dictionary pickled and encoded as a string.
    1414        """
    1515        pickled = pickle.dumps(session_dict)
    16         pickled_md5 = md5.new(pickled + settings.SECRET_KEY).hexdigest()
     16        pickled_md5 = md5_constructor(pickled + settings.SECRET_KEY).hexdigest()
    1717        return base64.encodestring(pickled + pickled_md5)
    1818
    1919    def save(self, session_key, session_dict, expire_date):
     
    5656    def get_decoded(self):
    5757        encoded_data = base64.decodestring(self.session_data)
    5858        pickled, tamper_check = encoded_data[:-32], encoded_data[-32:]
    59         if md5.new(pickled + settings.SECRET_KEY).hexdigest() != tamper_check:
     59        if md5_constructor(pickled + settings.SECRET_KEY).hexdigest() != tamper_check:
    6060            from django.core.exceptions import SuspiciousOperation
    6161            raise SuspiciousOperation, "User tampered with session cookie."
    6262        try:
  • django/utils/cache.py

     
    1717"Accept-language" header.
    1818"""
    1919
    20 import md5
    2120import re
    2221import time
    2322try:
     
    2928from django.core.cache import cache
    3029from django.utils.encoding import smart_str, iri_to_uri
    3130from django.utils.http import http_date
     31from django.utils.hashcompat import md5_constructor
    3232
    3333cc_delim_re = re.compile(r'\s*,\s*')
    3434
     
    104104    if cache_timeout < 0:
    105105        cache_timeout = 0 # Can't have max-age negative
    106106    if not response.has_header('ETag'):
    107         response['ETag'] = '"%s"' % md5.new(response.content).hexdigest()
     107        response['ETag'] = '"%s"' % md5_constructor(response.content).hexdigest()
    108108    if not response.has_header('Last-Modified'):
    109109        response['Last-Modified'] = http_date()
    110110    if not response.has_header('Expires'):
     
    138138
    139139def _generate_cache_key(request, headerlist, key_prefix):
    140140    """Returns a cache key from the headers given in the header list."""
    141     ctx = md5.new()
     141    ctx = md5_constructor()
    142142    for header in headerlist:
    143143        value = request.META.get(header, None)
    144144        if value is not None:
  • django/utils/hashcompat.py

     
     1try:
     2    import hashlib
     3    md5_constructor = hashlib.md5
     4    sha_constructor = hashlib.sha1
     5except ImportError:
     6    import md5
     7    md5_constructor = md5.new
     8    import sha
     9    sha_constructor = sha.new
     10   
     11 No newline at end of file
  • django/middleware/common.py

     
    1 import md5
    21import re
    32
    43from django.conf import settings
     
    65from django.core.mail import mail_managers
    76from django.utils.http import urlquote
    87from django.core import urlresolvers
     8from django.utils.hashcompat import md5_constructor
    99
    1010class CommonMiddleware(object):
    1111    """
     
    108108            if response.has_header('ETag'):
    109109                etag = response['ETag']
    110110            else:
    111                 etag = '"%s"' % md5.new(response.content).hexdigest()
     111                etag = '"%s"' % md5_constructor(response.content).hexdigest()
    112112            if response.status_code >= 200 and response.status_code < 300 and request.META.get('HTTP_IF_NONE_MATCH') == etag:
    113113                cookies = response.cookies
    114114                response = http.HttpResponseNotModified()
  • tests/regressiontests/cache/tests.py

     
    9999            self.assertEqual(cache.get(key), value)
    100100
    101101import os
    102 import md5
    103102import shutil
    104103import tempfile
    105104from django.core.cache.backends.filebased import CacheClass as FileCache
     105from django.utils.hashcompat import md5_constructor
    106106
    107107class FileBasedCacheTests(unittest.TestCase):
    108108    """
     
    119119    def test_hashing(self):
    120120        """Test that keys are hashed into subdirectories correctly"""
    121121        self.cache.set("foo", "bar")
    122         keyhash = md5.new("foo").hexdigest()
     122        keyhash = md5_constructor("foo").hexdigest()
    123123        keypath = os.path.join(self.dirname, keyhash[:2], keyhash[2:4], keyhash[4:])
    124124        self.assert_(os.path.exists(keypath))
    125125       
     
    128128        Make sure that the created subdirectories are correctly removed when empty.
    129129        """
    130130        self.cache.set("foo", "bar")
    131         keyhash = md5.new("foo").hexdigest()
     131        keyhash = md5_constructor("foo").hexdigest()
    132132        keypath = os.path.join(self.dirname, keyhash[:2], keyhash[2:4], keyhash[4:])
    133133        self.assert_(os.path.exists(keypath))
    134134
  • tests/regressiontests/file_uploads/tests.py

     
    11import os
    22import errno
    3 import sha
    43import shutil
    54import unittest
    65
     
    87from django.core.files.uploadedfile import SimpleUploadedFile
    98from django.test import TestCase, client
    109from django.utils import simplejson
     10from django.utils.hashcompat import sha_constructor
    1111
    1212from models import FileModel, UPLOAD_ROOT, UPLOAD_TO
    1313
     
    4545
    4646        for key in post_data.keys():
    4747            try:
    48                 post_data[key + '_hash'] = sha.new(post_data[key].read()).hexdigest()
     48                post_data[key + '_hash'] = sha_constructor(post_data[key].read()).hexdigest()
    4949                post_data[key].seek(0)
    5050            except AttributeError:
    51                 post_data[key + '_hash'] = sha.new(post_data[key]).hexdigest()
     51                post_data[key + '_hash'] = sha_constructor(post_data[key]).hexdigest()
    5252
    5353        response = self.client.post('/file_uploads/verify/', post_data)
    5454
  • tests/regressiontests/test_client_regress/models.py

     
    66from django.core.urlresolvers import reverse
    77from django.core.exceptions import SuspiciousOperation
    88import os
    9 import sha
    109
    1110class AssertContainsTests(TestCase):
    1211    def test_contains(self):
Back to Top