基于python的加密算法
python实现维吉尼亚加密法本文实例为大家分享了python实现维吉尼亚加密法的具体代码,供大家参考,具体内容如下
vigenere加密/解密时,把英文字母映射为0-25的数字再进行运算,并按n个字母为一组进行变换.算法定义如下:
设密钥 k =(k1,k2,k3…,kn),明文 m = (m1,m2,….mn),则加密算法为:
ek(m) = (c1,c2,…cn)
其中:c1 = (mi+ki)(mod 26),i=1,2,3…..n
解密算法为:
mi = (ci - ki)(mod 26), i = 1,2,…..n。
|
import string,os def vigenereencrypt(msg,key): size = len (key) result = [] cnt = 0 for i in msg: if i.upper() in string.uppercase: #offset相当于是 ki offset = string.uppercase.find(key[cnt % size]) t = string.uppercase[(string.uppercase.find(i.upper()) + offset) % 26 ] #这里相当于是c1 = (mi+ki)(mod 26) ,t = c1 if i.isupper(): result.append(t) else : result.append(t.lower()) cnt + = 1 else : result.append(i) return "".join(result) def main(): msg = "common sense is not so common" cipher = vigenereencrypt(msg, "pizza" ) #key = "pizza: print cipher if __name__ = = "__main__" : main() |
小编再为大家分享一段vigenere密码python实现代码:
|
##########vigenere密码############ letter_list = 'abcdefghijklmnopqrstuvwxyz' #字母表 #根据输入的key生成key列表 def get_keylist(key): key_list = [] for ch in key: key_list.append( ord (ch.upper()) - 65 ) return key_list #加密函数 def encrypt(plaintext,key_list): ciphertext = "" i = 0 for ch in plaintext: #遍历明文 if 0 = = i % len (key_list): i = 0 if ch.isalpha(): #明文是否为字母,如果是,则判断大小写,分别进行加密 if ch.isupper(): ciphertext + = letter_list[( ord (ch) - 65 + key_list[i]) % 26 ] i + = 1 else : ciphertext + = letter_list[( ord (ch) - 97 + key_list[i]) % 26 ].lower() i + = 1 else : #如果密文不为字母,直接添加到密文字符串里 ciphertext + = ch return ciphertext #解密函数 def decrypt(ciphertext,key): plaintext = "" i = 0 for ch in ciphertext: #遍历密文 if 0 = = i % len (key_list): i = 0 if ch.isalpha(): #密文为否为字母,如果是,则判断大小写,分别进行解密 if ch.isupper(): plaintext + = letter_list[( ord (ch) - 65 - key_list[i]) % 26 ] i + = 1 else : plaintext + = letter_list[( ord (ch) - 97 - key_list[i]) % 26 ].lower() i + = 1 else : #如果密文不为字母,直接添加到明文字符串里 plaintext + = ch return plaintext if __name__ = = '__main__' : print ( "加密请按d,解密请按e:" ) user_input = input (); while (user_input! = 'd' and user_input! = 'e' ): #输入合法性判断 print ( "输入有误!请重新输入:" ) user_input = input () print ( "请输入密钥:" ) key = input () while (false = = key.isalpha()): #输入合法性判断 print ( "输入有误!密钥为字母,请重新输入:" ) key = input () key_list = get_keylist(key) if user_input = = 'd' : #加密 print ( "请输入明文:" ) plaintext = input () ciphertext = encrypt(plaintext,key_list) print ( "密文为:\n%s" % ciphertext) else : #解密 print ( "请输入密文:" ) ciphertext = input () plaintext = decrypt(ciphertext,key_list) print ( "明文为:\n%s" % plaintext) |
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持开心学习网。
原文链接:https://blog.csdn.net/CosmopolitanMe/article/details/79498403