一、 Atbash密码
Atbash Cipher是一种简单的替换密码,与凯撒相类似,区别在于Atbash密码使用的一般是前后字母互换。例如:
- ABCDEFGHIJKLMNOPQRSTUVWXYZ
- ZYXWVUTSRQPONMLKJIHGFEDCBA
同样的可以利用ASCII表转回进行解密或者词频分析进行破解。
例题:wl blf pmld zgyzhs kzhhdliw
对此进行写加密解密算法,只需要注意这里用的是ord(Z) - 当前字母的码值然后加上ord(A),于是可以依照此思路写出加密解密算法。
点击查看代码
#加密
def atbash(text):#ord(A) <--> ord(Z)#ord(B) <--> ord(Y)#0 <--> 25#1 <--> 24#ord(Z) - ord(X) + ord(A)result = ""for char in text:if char.isalpha():# 处理大写字母if char.isupper():result += chr(ord("Z") - ord(char) + ord("A"))# 处理小写字母else:result += chr(ord("z") - ord(char) + ord("a"))else:# 非字母字符保持不变result += charreturn result#解密
def atbash_decrypt(text):return atbash(text)while True:print("1.加密")print("2.解密")print("3.退出")choice = input("请输入你的选择:")if choice == "1":text = input("请输入要加密的文本:")print("加密后的文本为:" + atbash(text))elif choice == "2":text = input("请输入要解密的文本:")print("解密后的文本为:" + atbash_decrypt(text))elif choice == "3":breakelse:print("输入错误,请重新输入")
二、摩斯密码
摩斯密码又叫摩尔斯电码,是由美国人在1836年发明的一种通过时断,以及不同的排列顺序来表达不同英文字母、数字和标点符号的信息代码,主要由点、划、字符间的停顿、单词间的停顿和句子之间的停顿构成。
莫斯码表如下所示,用python字典进行展示。
点击查看代码
MOSS_PASSWORD = {'A': '.-', 'B': '-...','C': '-.-.', 'D': '-..', 'E': '.','F': '..-.', 'G': '--.', 'H': '....','I': '..', 'J': '.---', 'K': '-.-','L': '.-..', 'M': '--', 'N': '-.','O': '---', 'P': '.--.', 'Q': '--.-','R': '.-.', 'S': '...', 'T': '-','U': '..-', 'V': '...-', 'W': '.--','X': '-..-', 'Y': '-.--', 'Z': '--..','1': '.----', '2': '..---', '3': '...--','4': '....-', '5': '.....', '6': '-....','7': '--...', '8': '---..', '9': '----.','0': '-----', ', ': '--..--', '.': '.-.-.-','?': '..--..', '/': '-..-.', '-': '-....-','(': '-.--.', ')': '-.--.-'}
点击查看代码
#创建密码本
MOSS_PASSWORD = {'A': '.-', 'B': '-...','C': '-.-.', 'D': '-..', 'E': '.','F': '..-.', 'G': '--.', 'H': '....','I': '..', 'J': '.---', 'K': '-.-','L': '.-..', 'M': '--', 'N': '-.','O': '---', 'P': '.--.', 'Q': '--.-','R': '.-.', 'S': '...', 'T': '-','U': '..-', 'V': '...-', 'W': '.--','X': '-..-', 'Y': '-.--', 'Z': '--..','1': '.----', '2': '..---', '3': '...--','4': '....-', '5': '.....', '6': '-....','7': '--...', '8': '---..', '9': '----.','0': '-----', ', ': '--..--', '.': '.-.-.-','?': '..--..', '/': '-..-.', '-': '-....-','(': '-.--.', ')': '-.--.-'}MOSS_key={".":'0',"-":'1'
}#加密
def moss_encrypt(text):result = ""content = ""for char in text:if char.isalpha() or char in MOSS_PASSWORD.keys():result += MOSS_PASSWORD[char.upper()] + " "else:result += charreturn result#解密
def moss_decrypt(text):result = ""for char in text.split():if char in MOSS_PASSWORD.values():result += list(MOSS_PASSWORD.keys())[list(MOSS_PASSWORD.values()).index(char)]else:result += charreturn resultwhile True:print("1.加密")print("2.解密")print("3.退出")choice = input("请输入你的选择:")if choice == "1":text = input("请输入要加密的文本:")print("加密后的文本为:" + moss_encrypt(text))elif choice == "2":text = input("请输入要解密的文本:")print("解密后的文本为:" + moss_decrypt(text))elif choice == "3":breakelse:print("输入错误,请重新输入")