一、任意给定两个素数p和q,p!= q,记 N = p * q ,构造Zn*,
问(编程解决):
1、是否每个元素都有inverse?是否成群?
2、这个集合有多少元素?
满足群的条件:
1、封闭性
2、结合律
3、存在单位元
4、存在逆元
# 判断是否为素数
def IsPrime():
flag =1
while (flag):
n =int(input("输入一个质数:"))
for iin range(2, n):
if n % i ==0:
print("不是质数" )
break
else:
return n
# 生成一个与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 IsClosed(list, n):
mark =1
for iin range(0,len(list)):
for jin range(0,len(list)):
flag =0
for kin range(0,len(list)):
if ((list[i] * list[j]) % n == list[k]):
flag =1
num = list[k]
if flag:
print("%s*%s封闭值为%s" % (list[i], list[j], num))
else:
print("%s*%s不封闭" % (list[i], list[j]))
mark =0
return mark
# 判断是否存在逆元
def IsInverse(list, n):
mark =1
for iin range(0,len(list)):
flag =1
for jin range(0,len(list)):
if ((list[i] * list[j]) % n ==1):
flag =0
print("%s存在逆元%s" % (list[i], list[j]),end=" ")
if flag:
print("%s不存在逆元" % (list[i]),end=" ")
mark =0
print()
if (mark):
print("任何元素都有逆元")
return mark
# 主函数
def main():
flag =1
p = IsPrime()
while (flag):
q = IsPrime()
if not q == p:
flag =0
else:
print("与第一个质数相同,请重新输入")
n = p * q
list = []
for iin range(1, n):
k = CommonFactor(i, n)
if k ==1:
list.append(i)
for iin range(0,len(list)):
print(list[i],end=" ")
print()
a = IsInverse(list, n)
b = IsClosed(list, n)
if a ==1 and b ==1:
print("每个元素都有逆元且运算封闭,成群,群元素个数:",len(list))
elif a ==0:
print("存在元素没有逆元,不成群")
elif b ==0:
print("运算不封闭,不成群")
main()
二、写一个程序,实现AES的S-box的构造。
#构造S-Box
import numpyas np
l_t = [0 for iin range(256)]
m_t = [0 for iin range(256)]
SBox = [0 for iin range(256)]
mid_t = [0 for iin range(256)]
b = [0xf1,0xe3,0xc7,0x8f,0x1f,0x3e,0x7c,0xf8]
p =1
for iin range(256):#求出0-255的逆元
l_t[i] = p
m_t[p] = i
if (p &0x80):
p = p ^ (p <<1) ^ (0x11b)# 8次不可约多项式16进制表示为11B
else:
p = p ^ (p <<1) ^0
#求出逆元后存放在mid_t中
for iin range(256):
if (i):
mid_t[i] = l_t[255 - m_t[i]]
else:
mid_t[i] =0
#对逆元进行变换,用上构造的b矩阵以及{63}这个值
for iin range(256):
t =0
m =0
mid =0
tab =0
for jin range(8):
m = mid = (b[j] & mid_t[i])
for kin range(8):
n = mid >>1
if (m != (n <<1)):
t +=1
mid = n
m = mid
if (t %2 >0):
temp =1
for kin range(j):
temp = temp <<1
tab += temp
t =0
SBox[i] = tab ^0x63
# 输出S-Box
print("S-Box如下")
SBox1=[]
for iin range(256):
SBox1.append(hex(SBox[i]))
SBox1=np.array(SBox1)
SBox1=SBox1.reshape((16,16))
print(SBox1)
运行结果:
网友评论