您的位置:首页 > 编程语言 > Python开发

多码加密 vigenere算法 python 实现

2014-01-12 18:19 309 查看
转自:/article/9704214.html

基于我自己对 vigenere 的理解,另外vigenere 属于非常弱的一种加密,用于生产环境不是非常安全请注意

[python] view
plaincopy





# -*- coding:utf-8 -*-

##################################

# Vigenere 是一种多码加密法

# author vearne

# ***注意***:

# 1) 字母表中必须要包含明文中出现的字母

# 2) 密钥不能为空

#

##################################

class Vigenere(object):

def __init__(self, table='0123456789', key='apple'):

# 字母表

self.table = table

# 密钥

self.key = key

def genNum(self, curr):

if curr + 1 >= len(self.key):

return 0

else:

return curr + 1

def dict(self, chr, move):

index = self.table.index(chr)

return self.table[(index + move) % len(self.table)]

def encrypt(self, cleartext):

# i 指向明文, j 指向密钥

j = 0

ll = []

for i in range(len(cleartext)):

move = ord(self.key[j]) % len(self.table)

# print 'move', move

new_chr = self.dict(cleartext[i], move)

ll.append(new_chr)

j = self.genNum(j)

return ''.join(ll)

def decrypt(self, ciphertext):

# i 指向密文, j 指向密钥

j = 0

ll = []

for i in range(len(ciphertext)):

move = ord(self.key[j]) % len(self.table)

move = move * (-1)

# print 'move', move

new_chr = self.dict(ciphertext[i], move)

ll.append(new_chr)

j = self.genNum(j)

return ''.join(ll)

if __name__ == '__main__':

v = Vigenere(key='apple077226')

cleartext = '000000668'

print cleartext

ciphertext = v.encrypt(cleartext)

print ciphertext

print '----------------------------------'

cleartext = v.decrypt(ciphertext)

print cleartext

如果字母表中的字母出现不重复,则可以保证明文跟密文的一一映射,如果出现重复,则会出现明文跟密文的多对一映射。

打乱字母表中字母的顺序,可以使密文更具有欺骗性。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: