#!/usr/bin/env python # -*- coding: cp936 -*- from numpy import* DEBUG = False Dim =4 def gcd(m,n): m, n = abs(m), abs(n) while n: m, n = n, m%n return m def iMod(a,m): a %= m t1, t2 = array([1,0]), array([0,1]) while a !=1: t1, t2 = t2 , t1 - t2 * (m/a) m, a = a, m%a return t2[1] def stain(m,n): c =1 while (m != 0) and (n != 0): if (m &1!= 0) and (n &1!= 0): c *=2 m, n= m>>1, n>>1 elif m &1!= 0: m >>=1 elif n &1!= 0: n >>=1 else: m, n = abs(m-n), min(m,n) return c*max(m,n) def finda(m,k): """ 找到输入列表中的第一个可逆元 m: 输入列 k: 模域 """ i = 0 for each in m: if gcd(each,k) ==1: return (i,iMod(each,k)) i +=1 return False def gen_dekey(m,k): """ 生成解密密钥 m: 加密密钥 k: 模域 """ I = identity(m.shape[0],int) end = m.shape[0] n = m.copy() n = hstack((n,I)) for i in range(end): a = finda(n[i:,i],k) #在该列中找到第一个可逆元 if isinstance(a, bool): print'Sorry! The Matrix is not invertible' return False j = i+a[0] n[i], n[j] = n[j].copy(), n[i].copy() #行交换 n[i] *= a[1] #该行乘模逆 n[i,i] =1 #将该列的其他元素置零 for c in range(end): if c != i: n[c] -= n[i]*n[c,i] return processMod(hsplit(n,2)[1],256) def matmul(substr,key): """ 根据密钥,对单组数据进行 加/解 密 """ a = array(substr) a = a.reshape(Dim,1) return mat(key) * mat(a) def encrypt(msg,enkey): """ 加密函数 msg :字符串列表 """ print len(msg) enc = [] i,j = 0, 0 temp = [] count = 0 while True: try: k = msg[i] i +=1 temp.append(k) except: if j == Dim -1: break j +=1 temp.append(32) if count == Dim -1: count = 0 a = matmul(temp,enkey) # 根据维数分组进行加密 for each in a.flat: enc.append(each) temp = [] continue count +=1 return processMod(enc,256) def decrypt(msg,dekey): """ 解密函数 msg :list形式的输入,数据成员为整形 """ print'Len(de_msg) = ',len(msg) dec = [] i,j = 0, 0 temp = [] count = 0 while True: try: k = msg[i] i +=1 temp.append(k) except: if j == Dim -1: break j +=1 temp.append(32) if count == Dim -1: count = 0 a = matmul(temp,dekey) # 根据维数分组进行解密 for each in a.flat: dec.append(each) temp = [] continue count +=1 return processMod(dec,256) def processMod(arr,Mod): if type(arr) == list: for i in range(len(arr)): arr[i] %= Mod else: for i in range(len(arr.flat)): arr.flat[i] %= Mod return arr if__name__=="__main__": n = int(raw_input('Enter the dimension of the Matrix:')) k = int(raw_input('Enter the Mod number:')) li = [] for i in range(n): str_list = raw_input('Enter the %d row:'% (i+1)) elem = (int(each) for each in str_list.split(',')) li += elem m = array(li).reshape(n,n) key = gen_dekey(m,k) if isinstance(key, bool): exit() print'The input is: ', m print'The output is: ', key print'The product of the two matrices is:' print mat(m) * mat(key)