Created
February 16, 2012 17:39
-
-
Save rvause/1846656 to your computer and use it in GitHub Desktop.
Encoder for ids in urls in a Django app
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import random | |
from base64 import b64encode, b64decode | |
from django.conf import settings | |
ALPHABET = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' | |
class URLEncoder(object): | |
def __init__(self, secret, alphabet=ALPHABET, noise_length=12): | |
self.secret = secret | |
self.alphabet = alphabet | |
self.noise_length = noise_length | |
@staticmethod | |
def xor(str1, str2): | |
return ''.join(chr(ord(a) ^ ord(b)) for a,b in zip(str1, str2)) | |
def noise(self, length): | |
return ''.join([random.choice(self.alphabet) for i in range(length)]) | |
def encode(self, string): | |
string = self.noise(self.noise_length) + string | |
return b64encode(self.xor(string, self.secret), '-_').replace('=', '') | |
def encode_id(self, id): | |
return self.encode(str(id)) | |
def decode(self, string): | |
if len(string) % 4: | |
add = (4 - len(string) % 4) * '=' | |
else: | |
add = '' | |
return self.xor( | |
b64decode(string + add, '-_'), self.secret | |
)[self.noise_length:] | |
def decode_id(self, string): | |
return int(self.decode(string)) | |
encoder = URLEncoder(settings.SECRET_KEY) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment