查找FIPS197文档,我尝试编码生成S盒的方式,即有限域上的矩阵乘法。但是,我未能使函数产生正确的值。例如,当我将0x53作为输入时,应该将0xed作为输出。但是,它会生成0x74。
以下是我编写的代码:
irr=0x11b # irreducible polynomial
pir=irr.bit_length()-1 # floor(log2(irr)) that equals to 8
class rijndael:
def add(self,a,b):
""" Rijndael Addition
This operation can be also subtraction. """
return a^b
def mod(self,a):
if a<(1<<pir):
""" in case that it is already less than 256 """
return a
lna=int(a).bit_length() # bit LeNgth of A that is bigger than 8
for i in range(lna-1,pir-1,-1):
a=self.add(a,bool(a&(1<<i))*(irr<<(i-pir)))
""" continues XOR until the result reduces to less than 256. """
return a
def mul(self,a,b):
""" This operation performs
bit shift operation and Rijndael addition,
instead of the arithmetic one. """
t=0
for i in range(int(b).bit_length()):
t=self.add(t,a*(b&(1<<i)))
return self.mod(t)
def mmm(self,a,b):
""" Rijndael Matrix Multiplication
Each has to be a list of lists that consist of only integers. """
t=[]
for i in range(len(a)):
t.append([])
for j in range(len(b[0])):
u=0
for k in range(len(a[i])):
u=self.add(u,self.mul(a[i][k],b[k][j]))
t[i].append(u)
return t
def csb(self,a,b,n):
""" Circular Shift of {N} Bits """
b%=n
return ((a<<b)%(1<<n))|(a>>(n-b))
r=rijndael()
p=[
[1,0,0,0,1,1,1,1],
[1,1,0,0,0,1,1,1],
[1,1,1,0,0,0,1,1],
[1,1,1,1,0,0,0,1],
[1,1,1,1,1,0,0,0],
[0,1,1,1,1,1,0,0],
[0,0,1,1,1,1,1,0],
[0,0,0,1,1,1,1,1]]
q=[
[1],
[1],
[0],
[0],
[1],
[0],
[1],
[0]]
s=r.mmm(p,q)
t=0
for i in range(len(s)):
t|=(s[i][0]<<i)
print(hex(t^0x63))
"""circular shift method begins"""
t=[]
u=0
for i in range(5):
t.append(r.csb(0x52,i,8))
for i in range(5):
u^=t[i]
print(hex(u^0x63))
我确认add()
、mod()
、mul()
和mmm()
正常工作。但我仍然找不到是什么让它产生了错误的值。即使是“循环移位法”也会产生错误的值。我如何解决这个问题
目前没有回答
相关问题 更多 >
编程相关推荐