单字母替换加密方法——单表置换密码 算法python加输入
时间: 2023-11-13 20:03:28 浏览: 107
单表置换密码是一种简单的加密方法,它通过将明文中的每个字母替换为密文中的另一个字母来实现加密。具体操作是先创建一个密文表,将明文中的每个字母替换为密文表中对应的字母,然后输出密文。
下面是一个简单的单表置换密码算法的 Python 代码实现:
```python
def substitution_cipher(plaintext, cipher_table):
ciphertext = ""
for char in plaintext:
if char.isalpha():
index = ord(char.lower()) - ord('a')
ciphertext += cipher_table[index]
else:
ciphertext += char
return ciphertext
# 示例
plaintext = "Hello, world!"
cipher_table = "qazwsxedcrfvtgbyhnujmikolp"
ciphertext = substitution_cipher(plaintext, cipher_table)
print(ciphertext)
```
在上面的代码中,`substitution_cipher` 函数接收明文和密文表作为参数,返回加密后的密文。该函数首先遍历明文中的每个字符,如果是字母,则计算其在字母表中的索引,然后使用密文表中相应的字母替换明文中的字母;否则直接将该字符加入密文字符串中。
使用示例中的密文表,对明文 "Hello, world!" 进行加密,得到的密文为 "itssb, hfygs!"。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)