AES 实现

任务一

任意给定两个素数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

结果:


AES 实现_第1张图片
捕获.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") 

运行结果

你可能感兴趣的:(AES 实现)