Python實現換位加密
阿新 • • 發佈:2019-01-10
import math
def transpostionEncrypt(msg,key):#加密
size = len(msg)
result = []
for i in range(key):
t = i
while t<size:
result.append(msg[t])
t+=key
return ''.join(result)
def transpostionDecrypt(msg,key) :#解密
numOfColums = int(math.ceil(len(msg)/float(key)))
numOfRows = key
sharedBox = numOfColums*numOfRows - len(msg)
row = 0
col = 0
result = ['']*numOfColums
for i in msg:
result[col] += i
col+=1
if col==numOfColums or (col==numOfColums-1 and row>=numOfRows-sharedBox):
col=0
row+=1
return ''.join(result)
def main():
cipher = transpostionEncrypt("Common sense is not so common.",8)
print cipher#密文
print transpostionDecrypt(cipher,8)
if __name__=="__main__" :
main()