Contact
CoCalc Logo Icon
StoreFeaturesDocsShareSupport News AboutSign UpSign In
| Download
Views: 59
1
from sage.crypto.sbox import SBox
2
3
# function that maps a list of 4-bits (e.g. [1,0,1,1]) to an integer (e.g. in this case 8+2+1=11)
4
def bits2word(L): return L[0]*8+L[1]*4+L[2]*2+L[3]
5
6
# inverse of bits2word
7
def word2bits(W): return [(W//8)%2, (W//4)%2, (W//2)%2, W%2]
8
9
# xor 2 bits
10
def xorbits(x,y): return (((x)+(y))%2)
11
12
# xor 2 lists of bits elementwise
13
def xor(L,M): return map(xorbits,L,M)
14
15
# function that maps an integer i in [0,65536) to list of 16 bits (left-most bit is MSB)
16
def int2state(i): return [((i//(2**(15-b)))%2) for b in range(16)]
17
18
# inverse of int2state
19
def state2int(L): return sum([(L[b]*(2**(15-b))) for b in range(16)],0)
20
21
# function to generate a list of 16 random bits
22
def randkey(): return int2state(getrandbits(16))
23
24
# permute bits in list of 16 bits as Pi_P in lecture notes
25
PP=[0,4,8,12,1,5,9,13,2,6,10,14,3,7,11,15]
26
def permbits(L): return [L[PP[i]] for i in range(16)]
27
28
# inverse of permbits is permbits itself
29
def permbitsinv(L): return permbits(L)
30
31
# function to split a state (list of 16 bits) into 4 words of 4 bits
32
def state2words(L): return [bits2word(L[0:4]), bits2word(L[4:8]),bits2word(L[8:12]), bits2word(L[12:16])]
33
34
# inverse of state2words
35
def words2state(L): return sum(map(word2bits, L),[])
36
37
# SBox and inverse SBox definitions
38
SB=SBox(14,4,13,1,2,15,11,8,3,10,6,12,5,9,0,7);
39
SBinv=SBox(14,3,4,8,1,12,10,15,7,13,9,6,11,2,0,5);
40
41
# apply SBox on state (list of 16 bits)
42
def substbits(L): return words2state(map(SB, state2words(L)))
43
44
# apply inverse SBox on state
45
def substbitsinv(L): return words2state(map(SBinv, state2words(L)))
46
47
# do one round of encryption given state L and round key K
48
def encryptround(L,K): return permbits(substbits(xor(L,K)))
49
50
# do final round of encryption given state L and round key K1 and final round key K2
51
def encryptfinalround(L,K1,K2): return xor(substbits(xor(L,K1)),K2)
52
53
# do encryption (4 rounds) with globally defined round keys: k1,k2,k3,k4,k5
54
def encrypt(L): return encryptfinalround(encryptround(encryptround(encryptround(L,k1),k2),k3),k4,k5)
55
56
# do decryption of one round
57
def decryptround(L,K): return xor(substbitsinv(permbitsinv(L)),K)
58
59
# do decryption of final round
60
def decryptfinalround(L,K1,K2): return xor(substbitsinv(xor(L,K2)),K1)
61
62
# do decryption with globally defined round keys: k1,k2,k3,k4,k5
63
def decrypt(L): return decryptround(decryptround(decryptround(decryptfinalround(L,k4,k5),k3),k2),k1)
64
65
66