summaryrefslogtreecommitdiff
path: root/passlib/util.py
diff options
context:
space:
mode:
Diffstat (limited to 'passlib/util.py')
-rw-r--r--passlib/util.py166
1 files changed, 166 insertions, 0 deletions
diff --git a/passlib/util.py b/passlib/util.py
index c8ea09e..492a851 100644
--- a/passlib/util.py
+++ b/passlib/util.py
@@ -270,5 +270,171 @@ def weighted_choice(rng, source):
raise RuntimeError, "failed to sum weights correctly"
#=================================================================================
+# "hash64" encoding
+#=================================================================================
+
+class H64:
+ """hash64 encoding helpers.
+
+ many of the password hash algorithms in this module
+ use a encoding that maps chunks of 3 bytes ->
+ chunks of 4 characters, in a manner similar (but not compatible with) base64.
+
+ this encoding system appears to have originated with unix-crypt,
+ but is used by md5-crypt, sha-xxx-crypt, and others.
+ this encoded is referred to (within passlib) as hash64 encoding,
+ due to it's use of a strict set of 64 ascii characters.
+
+ notably, bcrypt uses the same scheme, but with a different
+ ordering of the characters. bcrypt hashes cannot be decoded properly
+ with the H64 class.
+ """
+
+ #string of all h64 chars; position in string corresponds to value encoded
+ CHARS = "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
+
+ @classmethod
+ def randstr(cls, count, rng=srandom):
+ "generate random hash64 string containing specified # of chars; usually used as salt"
+ CHARS = cls.CHARS
+ return ''.join(rng.choice(CHARS) for idx in xrange(count))
+
+ @classmethod
+ def encode_3_offsets(cls, buffer, o1, o2, o3):
+ "do hash64 encode of three bytes at specified offsets in buffer; returns 4 chars"
+ #how 4 char output corresponds to 3 byte input:
+ #
+ #1st character: the six low bits of the first byte (0x3F)
+ #
+ #2nd character: four low bits from the second byte (0x0F) shift left 2
+ # the two high bits of the first byte (0xC0) shift right 6
+ #
+ #3rd character: the two low bits from the third byte (0x03) shift left 4
+ # the four high bits from the second byte (0xF0) shift right 4
+ #
+ #4th character: the six high bits from the third byte (0xFC) shift right 2
+ CHARS = cls.CHARS
+ v1 = ord(buffer[o1])
+ v2 = ord(buffer[o2])
+ v3 = ord(buffer[o3])
+ return CHARS[v1&0x3F] + \
+ CHARS[((v2&0x0F)<<2) + (v1>>6)] + \
+ CHARS[((v3&0x03)<<4) + (v2>>4)] + \
+ CHARS[v3>>2]
+
+ @classmethod
+ def encode_2_offsets(cls, buffer, o1, o2):
+ "do hash64 encode of two bytes at specified offsets in buffer; 2 missing msg set null; returns 3 chars"
+ CHARS = cls.CHARS
+ v1 = ord(buffer[o1])
+ v2 = ord(buffer[o2])
+ return CHARS[v1&0x3F] + \
+ CHARS[((v2&0x0F)<<2) + (v1>>6)] + \
+ CHARS[(v2>>4)]
+
+ @classmethod
+ def encode_1_offset(cls, buffer, o1):
+ "do hash64 encode of single byte at specified offset in buffer; 4 missing msb set null; returns 2 chars"
+ CHARS = cls.CHARS
+ v1 = ord(buffer[o1])
+ return CHARS[v1&0x3F] + CHARS[v1>>6]
+
+ #old code, never used...
+ ###reverse map of char -> value
+ ##CHARIDX = dict( (c,i) for i,c in enumerate(CHARS))
+ ##def _enc64(value, offset=0, num=False):
+ ## if num:
+ ## x, y, z = value[offset], value[offset+1], value[offset+2]
+ ## else:
+ ## x, y, z = ord(value[offset]), ord(value[offset+1]), ord(value[offset+2])
+ ## #xxxxxx xxyyyy yyyyzz zzzzzz
+ ## #aaaaaa bbbbbb cccccc dddddd
+ ## a = (x >> 2) # x [8..3]
+ ## b = ((x & 0x3) << 4) + (y>>4) # x[2..1] + y [8..5]
+ ## c = ((y & 0xf) << 2) + (z>>6) #y[4..1] + d[8..7]
+ ## d = z & 0x3f
+ ## return CHARS[a] + CHARS[b] + CHARS[c] + CHARS[d]
+ ##
+ ##def _dec64(value, offset=0, num=False):
+ ## a, b, c, d = CHARIDX[value[offset]], CHARIDX[value[offset+1]], \
+ ## CHARIDX[value[offset+2]], CHARIDX[value[offset+3]]
+ ## #aaaaaabb bbbbcccc ccdddddd
+ ## #xxxxxxxx yyyyyyyy zzzzzzzz
+ ## x = (a<<2) + (b >> 4) #a[6..1] + b[6..5]
+ ## y = ((b & 0xf) << 4) + (c >> 2) #b[4..1] + c[6..3]
+ ## z = ((c & 0x3) << 6) + d #c[2..1] + d[6..1]
+ ## if num:
+ ## return x, y, z
+ ## return chr(x) + chr(y) + chr(z)
+ ##
+ ##def h64_encode(value, pad=False, num=False):
+ ## "encode string of bytes into hash64 format"
+ ## if num:
+ ## value = list(value)
+ ## #pad value to align w/ 3 byte chunks
+ ## x = len(value) % 3
+ ## if x == 2:
+ ## if num:
+ ## value += [0]
+ ## else:
+ ## value += "\x00"
+ ## p = 1
+ ## elif x == 1:
+ ## if num:
+ ## value += [0, 0]
+ ## else:
+ ## value += "\x00\x00"
+ ## p = 2
+ ## else:
+ ## p = 0
+ ## assert len(value) % 3 == 0
+ ## out = "".join( _enc64(value, offset, num=num) for offset in xrange(0, len(value), 3))
+ ## assert len(out) % 4 == 0
+ ## if p:
+ ## if pad:
+ ## out = out[:-p] + "=" * p
+ ## else:
+ ## out = out[:-p]
+ ## return out
+ ##
+ ##def h64_decode(value, pad=False, num=False):
+ ## "decode string of bytes from hash64 format"
+ ## if value.endswith("="):
+ ## assert len(value) % 4 == 0, value
+ ## if value.endswith('=='):
+ ## p = 2
+ ## value = value[:-2] + '..'
+ ## else:
+ ## p = 1
+ ## value = value[:-1] + '.'
+ ## else:
+ ## #else add padding if needed
+ ## x = len(value) % 4
+ ## if x == 0:
+ ## p = 0
+ ## elif pad:
+ ## raise ValueError, "size must be multiple of 4"
+ ## elif x == 3:
+ ## p = 1
+ ## value += "."
+ ## elif x == 2:
+ ## p = 2
+ ## value += ".."
+ ## elif x == 1:
+ ## p = 3
+ ## value += "..."
+ ## assert len(value) % 4 == 0, value
+ ## if num:
+ ## out = []
+ ## for offset in xrange(0, len(value), 4):
+ ## out.extend(_dec64(value, offset, num=True))
+ ## else:
+ ## out = "".join( _dec64(value, offset) for offset in xrange(0, len(value), 4))
+ ## assert len(out) % 3 == 0
+ ## if p: #strip out garbage chars
+ ## out = out[:-p]
+ ## return out
+
+#=================================================================================
#eof
#=================================================================================