我们需要批量读取文件,并且分析每个帧内1024bit模数N | 1024bit加密指数e | 1024bit密文me mod N是否存在相互关系
1 2 3 4
import os from pyexpat.errors import messages
import gmpy2
首先我们设置4个列表,分别存储N,e,c,m
1 2 3 4 5
n_list = {} e_list = {} c_list = {} m_list = {}
其次我们需要读取文件,然后分析每个帧内的N,e,c,m
1 2 3 4 5 6 7 8 9 10
defread_file(): for i inrange(21): filename = f'Frame{i}' withopen(filename, 'r') as f: n = int(f.read(256).strip(), 16) n_list[i] = n e = int(f.read(256).strip(), 16) e_list[i] = e c = int(f.read(256).strip(), 16) c_list[i] = c
分析是否有相同的参数e和N
1 2 3 4 5 6 7 8 9 10
if __name__ == "__main__": read_file() # 输出e for i, e_1 in e_list.items(): print(f'e{i}:{e_1}'.format(i, e_1)) # 输出相同的n for i, n_1 in n_list.items(): for j, n_2 in n_list.items(): if i < j and n_1 == n_2: print(f'n{i} = n{j} = {n_1}'.format(i, j, n_1))
defcrt(a,m): M = 1 for i in m: M *= i Mi = [M//i for i in m] Mi_ = [gmpy2.invert(M//i, i) for i in m] x = 0 for i inrange(len(m)): x += a[i]*Mi[i]*Mi_[i] return x % M
根据中国剩余定理,我们可以解出密文m,再对答案求5次方根得到明文
1 2 3 4 5 6 7 8
c5_list = [c_list[3], c_list[8], c_list[12], c_list[16], c_list[20]] n5_list = [n_list[3], n_list[8], n_list[12], n_list[16], n_list[20]] m = crt(c5_list, n5_list) m = gmpy2.iroot(m, 5)[0] byte = bytes.fromhex(hex(m)[-16:]).decode('utf-8') print(f'3,8,12,16,20的明文是:{byte}') for i in [3, 8, 12, 16, 20]: m_list[i] = byte
3,8,12,16,20的明文是:t is a f
接下来我们来探寻N里面是否有不相同且不互素的情况,这样就能够求出相应的大素数p和q。
1 2 3 4
for i, n_1 in n_list.items(): for j, n_2 in n_list.items(): if i < j and gmpy2.gcd(n_1, n_2) != 1and n_1 != n_2: print(f'n{i}和n{j}不相同且不互素')
defpollard_rho(n): x = 2 for i inrange(2, 1000000): x = pow(x, i, n) y = gmpy2.gcd(x-1, n) if y != 1and y != n: return y
接下来我们调用函数进行解密
1 2 3 4 5 6 7 8
for i in [2, 6, 19]: p = pollard_rho(n_list[i]) q = n_list[i] // p d = gmpy2.invert(e_list[i], (p - 1) * (q - 1)) m = gmpy2.powmod(c_list[i], d, n_list[i]) byte = bytes.fromhex(hex(m)[-16:]).decode('utf-8') print(f'{i}的明文是:{byte}') m_list[i] = byte
2的明文是: That is
6的明文是: "Logic
19的明文是:instein.
1 2
for i, byte in m_list.items(): print(f'明文{i}:{byte}'.format(i, byte))
明文0:My secre
明文4:My secre
明文3:t is a f
明文8:t is a f
明文12:t is a f
明文16:t is a f
明文20:t is a f
明文1:. Imagin
明文18:m A to B
明文10:will get
明文14: you fro
明文2: That is
明文6: "Logic
明文19:instein.
通过这些帧的明文我们能够猜出明文是b’My secret is a famous saying of Albert Einstein. That is “Logic will get you from A to B. Imagination will take you everywhere.”’