python密码学简单替代密码解密及测试教程
作者:菜鸟教程 时间:2023-09-30 08:13:00
简单替代密码
简单替换密码是最常用的密码,包括为每个密文文本字符替换每个纯文本字符的算法.在这个过程中,与凯撒密码算法相比,字母表是混乱的.
示例
简单替换密码的密钥通常由26个字母组成.一个示例键是 :
plain alphabet : abcdefghijklmnopqrstuvwxyz
cipher alphabet: phqgiumeaylnofdxjkrcvstzwb
使用上述密钥的示例加密是 :
plaintext : defend the east wall of the castle
ciphertext: giuifg cei iprc tpnn du cei qprcni
以下代码显示了一个实现简单替换密码的程序;
import random, sys
LETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
def main():
message = ''
if len(sys.argv) > 1:
with open(sys.argv[1], 'r') as f:
message = f.read()
else:
message = raw_input("Enter your message: ")
mode = raw_input("E for Encrypt, D for Decrypt: ")
key = ''
while checkKey(key) is False:
key = raw_input("Enter 26 ALPHA key (leave blank for random key): ")
if key == '':
key = getRandomKey()
if checkKey(key) is False:
print('There is an error in the key or symbol set.')
translated = translateMessage(message, key, mode)
print('Using key: %s' % (key))
if len(sys.argv) > 1:
fileOut = 'enc.' + sys.argv[1]
with open(fileOut, 'w') as f:
f.write(translated)
print('Success! File written to: %s' % (fileOut))
else: print('Result: ' + translated)
# Store the key into list, sort it, convert back, compare to alphabet.
def checkKey(key):
keyString = ''.join(sorted(list(key)))
return keyString == LETTERS
def translateMessage(message, key, mode):
translated = ''
charsA = LETTERS
charsB = key
# If decrypt mode is detected, swap A and B
if mode == 'D':
charsA, charsB = charsB, charsA
for symbol in message:
if symbol.upper() in charsA:
symIndex = charsA.find(symbol.upper())
if symbol.isupper():
translated += charsB[symIndex].upper()
else:
translated += charsB[symIndex].lower()
else:
translated += symbol
return translated
def getRandomKey():
randomList = list(LETTERS)
random.shuffle(randomList)
return ''.join(randomList)
if __name__ == '__main__':
main()
输出
您可以观察以下内容当你实现上面给出的代码时输出 :
简单替换密码测试
我们将重点介绍如何使用各种方法测试替换密码,这有助于生成随机字符串,如下面所示 :
import random, string, substitution
def main():
for i in range(1000):
key = substitution.getRandomKey()
message = random_string()
print('Test %s: String: "%s.."' % (i + 1, message[:50]))
print("Key: " + key)
encrypted = substitution.translateMessage(message, key, 'E')
decrypted = substitution.translateMessage(encrypted, key, 'D')
if decrypted != message:
print('ERROR: Decrypted: "%s" Key: %s' % (decrypted, key))
sys.exit()
print('Substutition test passed!')
def random_string(size = 5000, chars = string.ascii_letters + string.digits):
return ''.join(random.choice(chars) for _ in range(size))
if __name__ == '__main__':
main()
输出
您可以随机观察输出生成的字符串有助于生成随机纯文本消息,如下所示 :
测试成功完成后,我们可以观察输出消息替换测试通过!.
因此,您可以系统地破解替换密码.
简单替换密码解密
您可以了解替换密码的简单实现,它根据简单替换密码技术中使用的逻辑显示加密和解密的消息.这可以被视为一种替代编码方法.
代码
您可以使用以下代码使用简单替换密码来执行解密;
import random
chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' + \
'abcdefghijklmnopqrstuvwxyz' + \
'0123456789' + \
':.;,?!@#$%&()+=-*/_<> []{}`~^"\'\\'
def generate_key():
"""Generate an key for our cipher"""
shuffled = sorted(chars, key=lambda k: random.random())
return dict(zip(chars, shuffled))
def encrypt(key, plaintext):
"""Encrypt the string and return the ciphertext"""
return ''.join(key[l] for l in plaintext)
def decrypt(key, ciphertext):
"""Decrypt the string and return the plaintext"""
flipped = {v: k for k, v in key.items()}
return ''.join(flipped[l] for l in ciphertext)
def show_result(plaintext):
"""Generate a resulting cipher with elements shown"""
key = generate_key()
encrypted = encrypt(key, plaintext)
decrypted = decrypt(key, encrypted)
print 'Key: %s' % key
print 'Plaintext: %s' % plaintext
print 'Encrypted: %s' % encrypted
print 'Decrypted: %s' % decrypted
show_result('Hello World. This is demo of substitution cipher')
来源:https://www.it1352.com/OnLineTutorial/cryptography_with_python/cryptography_with_python_simple_substitution_cipher.html
标签:python,密码学,替代密码,测试,解密
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
mybatis连接MySQL8出现的问题解决方法
2024-01-22 08:27:59
最常用的SQL语句
2024-01-23 20:37:40
浅谈keras中loss与val_loss的关系
2021-12-12 08:41:22
pandas进行时间数据的转换和计算时间差并提取年月日
2021-03-14 02:22:22
![](https://img.aspxhome.com/file/2023/7/109477_0s.png)
Pycharm没有报错提示(误触ignore)的完美解决方案
2023-01-24 13:39:34
![](https://img.aspxhome.com/file/2023/0/92360_0s.png)
动态载入树 (ASP+数据库)
2010-05-27 12:20:00
python 判断参数为Nonetype类型或空的实例
2021-03-21 07:15:17
SQL中查找某几个字段完全一样的数据
2024-01-26 12:55:59
![](https://img.aspxhome.com/file/2023/5/122365_0s.jpg)
慢慢的网页
2009-11-12 12:53:00
![](https://img.aspxhome.com/file/UploadPic/200911/12/manmanwangye-95s.jpg)
python3 实现mysql数据库连接池的示例代码
2024-01-17 15:25:59
![](https://img.aspxhome.com/file/2023/4/101314_0s.png)
MySql采用GROUP_CONCAT合并多条数据显示的方法
2024-01-20 07:39:22
python 处理数字,把大于上限的数字置零实现方法
2022-11-13 09:20:56
MSSQL分页存储过程完整示例(支持多表分页存储)
2024-01-15 10:19:21
深入解析Python中的list列表及其切片和迭代操作
2023-03-24 04:20:40
ASP+SQLServer2000 经验积累
2008-02-03 15:16:00
python turtle库画一个方格和圆实例
2021-09-25 14:06:10
![](https://img.aspxhome.com/file/2023/9/93799_0s.png)
sqlserver 数据库压缩与数据库日志(ldf)压缩方法分享
2024-01-17 12:33:46
Python循环语句介绍
2021-04-19 20:04:42
![](https://img.aspxhome.com/file/2023/9/103219_0s.png)
很有意思的SQL多行数据拼接
2024-01-28 02:08:56
![](https://img.aspxhome.com/file/2023/2/110992_0s.jpg)
Pyhton中单行和多行注释的使用方法及规范
2021-11-21 12:13:00
![](https://img.aspxhome.com/file/2023/0/135310_0s.jpg)