Skip to content

Instantly share code, notes, and snippets.

Created November 29, 2011 12:43
Show Gist options
  • Save anonymous/1404682 to your computer and use it in GitHub Desktop.
Save anonymous/1404682 to your computer and use it in GitHub Desktop.
"""
/**
* IntegerPerm is a reversible keyed permutation of the integers.
* This class is not cryptographically secure as the F function
* is too simple and there are not enough rounds.
*
* @author Martin Ross
*/
"""
def rshift(val, n): return val>>n if val >= 0 else (val+0x100000000)>>n
class IntCrypt():
DEFAULT_KEY = 0x6CFB18E2
LOW_16_MASK = 0xFFFF
HALF_SHIFT = 16
NUM_ROUNDS = 4
def __init__(self, key=None):
self.mRoundKeys = [0,] * self.NUM_ROUNDS
self.setkey(key if not key==None else self.DEFAULT_KEY)
def setkey(self, key):
self.mKey = key;
self.mRoundKeys[0] = self.mKey & self.LOW_16_MASK
self.mRoundKeys[1] = ~(self.mKey & self.LOW_16_MASK)
self.mRoundKeys[2] = rshift(self.mKey, self.HALF_SHIFT)
self.mRoundKeys[3] = ~(rshift(self.mKey,self.HALF_SHIFT))
def encrypt(self, plain):
rhs = plain & self.LOW_16_MASK
lhs = rshift(plain, self.HALF_SHIFT)
for i in range(self.NUM_ROUNDS):
if i>0:
temp = lhs
lhs = rhs
rhs = temp
f = self.F(lhs, i)
rhs ^= self.F(lhs, i)
rhs = rhs & self.LOW_16_MASK
#print "lhs %s rhs %s" % (lhs, rhs)
r = (lhs << self.HALF_SHIFT) + (rhs & self.LOW_16_MASK)
return r
def decrypt(self, cypher):
rhs = cypher & self.LOW_16_MASK
lhs = rshift(cypher, self.HALF_SHIFT)
for i in range(self.NUM_ROUNDS):
if i>0:
temp = lhs
lhs = rhs
rhs = temp
f = self.F(lhs, self.NUM_ROUNDS - 1 - i)
rhs ^= f
rhs = rhs & self.LOW_16_MASK
#print "lhs %s rhs %s" % (lhs, rhs)
return (lhs << self.HALF_SHIFT) + (rhs & self.LOW_16_MASK)
def F(self, num, round):
num ^= self.mRoundKeys[round]
num *= num;
return rshift(num, self.HALF_SHIFT) ^ (num & self.LOW_16_MASK)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment