Skip to content

Instantly share code, notes, and snippets.

@raullenchai
Created July 12, 2012 20:36
Show Gist options
  • Save raullenchai/3100791 to your computer and use it in GitHub Desktop.
Save raullenchai/3100791 to your computer and use it in GitHub Desktop.
Python Implementation of Courtois Toy Cipher (CTC)
'''
Python Implementation of Courtois Toy Cipher (CTC)
CTC is a toy cipher presented for sake of cryptanalysis using algebraic attacks in http://eprint.iacr.org/2006/168.pdf.
'''
def xorRoundKey(state,roundkey):
return state ^ roundkey
def sLayer(state, B):
SBox = list([7, 6, 0, 4, 2, 5, 1, 3])
output = 0
for i in xrange(B):
output |= SBox[(state>>(i*3))&0x7]<<(i*3)
return output
def pLayer(state, B):
output = (state&0x01)<<2
for i in xrange(1,3*B):
output |= (((state>>i)&0x01) ^ ((state>>(i+137)%255)&0x01)) << ( (i*202+2)%255 )
return output
def encrypt(plain, key, B, R):
assert B>0 and R>0
assert len(key) == R+1
assert len(bin(plain))-2 <= 3*B
for k in key:
assert len(bin(k))-2 <= 3*B
state = plain
for i in xrange(R-1):
state = xorRoundKey(state,key[i])
state = sLayer(state, B)
state = pLayer(state, B)
cipher = xorRoundKey(state,key[-1])
return cipher
if __name__ == '__main__':
B = 85 #number of paralleled sboxes
R = 6 #number of rounds
key = [0,0,0,0,0,0,0]
from random import randint
plain = randint(0, (1<<3*B))
cipher = encrypt(plain, key, B, R)
print 'plain \t', bin(plain)
print 'cipher \t', bin(cipher)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment