1. David Bennett
  2. django-private-media


django-private-media / private_media / utils.py

from base64 import urlsafe_b64encode, urlsafe_b64decode
from itertools import izip, cycle
from urllib import unquote
from django.utils.http import urlquote, force_unicode, smart_str, allow_lazy
from private_media.conf import settings
assert urlquote

def xor_crypt_string(data, key=None):
    if key is None:
        key = settings.PRIVATE_MEDIA_ENCODE_KEY
    return ''.join(chr(ord(x) ^ ord(y)) for (x, y) in izip(data, cycle(key)))

def encode_key(key):
    return urlsafe_b64encode(xor_crypt_string(key)).strip('=')

def decode_key(key):
    return xor_crypt_string(urlsafe_b64decode(str(key) + '=='))

def urlunquote(quoted_url):
    A wrapper for Python's urllib.unquote() function that can operate on
    the result of django.utils.http.urlquote().
    return force_unicode(unquote(smart_str(quoted_url)))
urlunquote = allow_lazy(urlunquote, unicode)