Skip to content

Instantly share code, notes, and snippets.

@Cairnarvon
Created July 5, 2012 23:48
Show Gist options
  • Save Cairnarvon/3057176 to your computer and use it in GitHub Desktop.
Save Cairnarvon/3057176 to your computer and use it in GitHub Desktop.
A possibly gooder interface for hashes.
>>> from hash import Tripcode
>>> a, b = Tripcode('WokonZwxw2'), Tripcode.create('tea')
>>> a
Tripcode('WokonZwxw2')
>>> b
Tripcode.create('tea')
>>> print a, b
WokonZwxw2 WokonZwxw2
>>> a == b
True
>>> a == 'tea'
True
>>> a == 'WokonZwxw2'
False
>>> a.hash, a.plain
('WokonZwxw2', None)
>>> b.hash, b.plain
('WokonZwxw2', 'tea')
>>> a.plain = 'tea'
>>> a
Tripcode.create('tea')
>>> a.plain = 'dqn'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "hash.py", line 45, in __setattr__
raise ValueError('f(%s) != %s' % (repr(value), repr(self.hash)))
ValueError: f('dqn') != 'WokonZwxw2'
>>>
#!/usr/bin/python
import crypt
class Hash(object):
def __init__(self, hash_value):
self.hash = hash_value
self.plain = None
@classmethod
def create(cls, plain):
h = cls(cls._hash(plain))
h.plain = plain
return h
@staticmethod
def _hash(plain):
"""Subclasses should overwrite this."""
return plain
def __eq__(self, o):
if self.__class__ == o.__class__:
return self.hash == o.hash
else:
return self.hash == self.create(o).hash
def __ne__(self, o):
return not self.__eq__(o)
def __str__(self):
return self.hash
def __repr__(self):
if self.plain is not None:
return "%s.create(%s)" % (self.__class__.__name__, repr(self.plain))
else:
return "%s(%s)" % (self.__class__.__name__, repr(self.hash))
def __len__(self):
return len(self.hash)
def __setattr__(self, name, value):
if name == 'plain' and value is not None:
if self._hash(value) != self.hash:
raise ValueError('f(%s) != %s' % (repr(value), repr(self.hash)))
elif name == 'hash':
self.plain = None
object.__setattr__(self, name, value)
# To atgame
class Tripcode(Hash):
@staticmethod
def _hash(plain):
salt_table = dict(zip('/0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[/]^-`abcdefghijklmnopqrstuvwxyz',
'/0123456789ABCDEFGABCDEFGHIJKLMNOPQRSTUVWXYZabcdefabcdefghijklmnopqrstuvwxyz'))
salt = "%c%c" % (salt_table.get(plain[1], '.'),
salt_table.get(plain[2], '.'))
return crypt.crypt(plain, salt)[3:]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment