任务一
任意给定两个素数p和q,p!= q,记 N = p * q ,构造Zn
1.是否每个元素都有inverse?是否成群。
2.这个集合有多少元素?
代码
def isprime():
count = 1
while (count):
n = int(input("输入一个质数:"))
for i in range(2, n):
if n % i == 0:
print(" %d 这不是一个质数!" % n)
break
else:
return n
def CommonFactor(a,b):
if a<b:
t = a
a = b
b = t
while(a%b):
t = b
b = a % b
a = t
return b
def is_inverse(list,n):
mark=1
for i in range(0,len(list)):
count=1
for j in range(0,len(list)):
if((list[i]*list[j])%n==1):
count = 0
print("%s存在逆元%s"%(list[i],list[j]),end=" ")
if count:
print("%s不存在逆元"%(list[i]),end=" ")
mark=0
print()
if(mark):
print("任何元素都有逆元")
return mark
def is_closed(list,n):
mark=1
for i in range(0, len(list)):
for j in range(0, len(list)):
count=0
for k in range(0, len(list)):
if((list[i]*list[j])%n == list[k]):
count=1
num=list[k]
if count:
print("%s*%s封闭值为%s"%(list[i],list[j],num))
else:
print("%s*%s不封闭"%(list[i],list[j]))
mark=0
return mark
def main():
p=isprime()
count=1
while(count):
q=isprime()
if not q==p:
count=0
else:
print("与第一个质数相同,请重新输入")
n=p*q
list=[]
for i in range(1,n):
k=CommonFactor(i,n)
if k==1:
list.append(i)
for i in range(0,len(list)):
print(list[i],end=" ")
print()
a=is_inverse(list,n)
b=is_closed(list,n)
if a==1 and b==1:
print("任意元素都有逆元且运算封闭,成群")
print("群元素有%s个"%(len(list)))
elif a==0:
print("存在元素没有逆元,不成群")
elif b==0:
print("运算不封闭,不成群")
main()
结果:
捕获.PNG
任务二
写一个程序,实现AES的S-box的构造
代码
global r2
sbox = [[0 for col in range(16)] for row in range(16)]
def msb(num):
for i in range(0,8):
if not(num >> (i + 1)):
return i
def divide(a, b, r2):
a_msb = msb(a)
b_msb = msb(b)
if(a < b):
r = a
return 0;
bit = a_msb - b_msb
temp = b
temp = temp << bit
a = a ^ temp
return (1 << bit) | divide(a, b, r2)
def multiply(a, b): #GF(2^8)乘法
res = 0
if(b & 0x01):
res = a
for i in range(0,8):
if(b & (0x01 << i)):
temp = a
for j in range(0,i):
if not(temp & 0x80):
temp <<= 1
else:
temp <<= 1
temp = temp ^ 0x1B
res = res ^ temp
return res
def inverse(b):
if(b == 0):
return 0
r0 = 0x11B
r1 = b
w0 = 0
w1 = 1
q = divide(r0,r1,r2)
w2 = w0 ^ multiply(q, w1)
while(1):
if(r2 == 0):
break
r0 = r1
r1 = r2
q = divide(r0, r1, r2)
w0 = w1
w1 = w2
w2 = w0 ^ multiply(q, w1)
return w1
def initialize():
for i in range(0,0xF):
for j in range(0,0xF):
sbox[i][j] = inverse((i << 4) + j)
def map( a):
c = 0x63
res = 0x0
temp = 0x0
for i in range(0,8):
temp = temp ^ ((a >> i) & 0x1) ^ ((a >> ((i + 4) % 8)) & 0x1)
temp = temp ^ ((a >> ((i + 5) % 8)) & 0x1) ^ ((a >> ((i + 6) % 8)) & 0x1)
temp = temp ^ ((a >> ((i + 7) % 8)) & 0x1) ^ ((c >> i) & 0x1)
res = res | (temp << i)
temp = 0x0
return res
initialize()
for i in range(0, 0xF):
print()
for j in range(0, 0xF):
sbox[i][j] = map(sbox[i][j])
print('%-2d' % sbox[0][1], end=' ')
print("a")
运行结果
网友评论