Python 实现的HillCipher

   最近写什么都想用PYTHON,DES都不例外,结果被现实狠狠教训了一顿!! 真是一个"慢"字了得。

不过写的HillCipher作演示还是够了。

 

#!/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)

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值