Python实现移位密码的解密
时间: 2024-03-06 17:05:55 浏览: 22
移位密码是一种简单的加密方式,它将明文中的每个字母按照一个固定的规律向左或向右移动若干个位置,然后输出密文。解密过程就是将密文中的每个字母按照相同的规律向左或向右移回原来的位置,还原出明文。
下面是Python代码实现移位密码的解密:
```python
def decrypt(message, key):
# 将密文中的每个字母向左移动key个位置
decrypted = ''
for c in message:
if c.isalpha():
shifted = ord(c) - key
if shifted < ord('A'):
shifted += 26
decrypted += chr(shifted)
else:
decrypted += c
return decrypted
```
其中,`message`是密文,`key`是移动的位数。`decrypt`函数将密文中的每个字母向左移动`key`个位置,还原出明文。
例如,假设密文为`Jgnnq`,移动的位数为2,那么可以调用`decrypt('Jgnnq', 2)`来解密,得到明文`Hello`。
相关问题
python移位密码解密
可以使用以下代码解密python移位密码:
```python
def decrypt(ciphertext, shift):
plaintext = ""
for char in ciphertext:
if char.isalpha():
char_code = ord(char) - shift
if char.isupper():
if char_code < ord('A'):
char_code += 26
else:
if char_code < ord('a'):
char_code += 26
plaintext += chr(char_code)
else:
plaintext += char
return plaintext
```
其中,ciphertext是密文,shift是移位数。使用该函数即可解密移位密码。
vigenere密码用Python实现加解密
Vigenere密码是一种古老的加密算法,它使用一个关键字来对明文进行加密,因此也被称为多表密码。下面是使用 Python 实现 Vigenere 加解密的代码:
```python
def vigenere_encrypt(plaintext, key):
"""
使用 Vigenere 密码加密明文
:param plaintext: 明文
:param key: 密钥
:return: 密文
"""
ciphertext = ""
key_len = len(key)
for i in range(len(plaintext)):
shift = ord(key[i % key_len]) - ord("a")
ciphertext += chr((ord(plaintext[i]) - ord("a") + shift) % 26 + ord("a"))
return ciphertext
def vigenere_decrypt(ciphertext, key):
"""
使用 Vigenere 密码解密密文
:param ciphertext: 密文
:param key: 密钥
:return: 明文
"""
plaintext = ""
key_len = len(key)
for i in range(len(ciphertext)):
shift = ord(key[i % key_len]) - ord("a")
plaintext += chr((ord(ciphertext[i]) - ord("a") - shift) % 26 + ord("a"))
return plaintext
```
使用示例:
```python
plaintext = "hello"
key = "world"
ciphertext = vigenere_encrypt(plaintext, key)
print(ciphertext) # 输出:dahit
decrypted_plaintext = vigenere_decrypt(ciphertext, key)
print(decrypted_plaintext) # 输出:hello
```
在上述代码中,`vigenere_encrypt` 函数接受明文和密钥作为输入,并返回加密后的密文。`vigenere_decrypt` 函数接受密文和密钥作为输入,并返回解密后的明文。在这两个函数中,我们使用了 `ord` 函数将字符转换成 ASCII 码,使用了 `chr` 函数将 ASCII 码转换成字符,使用了 `%` 运算符实现循环移位。