移位加密算法python
时间: 2024-03-26 19:33:13 浏览: 22
移位加密算法(也称为凯撒密码)是一种简单的替换密码算法,它通过将字母按照一定的位移量进行替换来实现加密和解密。在Python中,可以使用以下代码实现移位加密算法:
```python
def shift_encrypt(text, shift):
encrypted_text = ""
for char in text:
if char.isalpha():
ascii_offset = ord('A') if char.isupper() else ord('a')
encrypted_char = chr((ord(char) - ascii_offset + shift) % 26 + ascii_offset)
encrypted_text += encrypted_char
else:
encrypted_text += char
return encrypted_text
def shift_decrypt(encrypted_text, shift):
decrypted_text = ""
for char in encrypted_text:
if char.isalpha():
ascii_offset = ord('A') if char.isupper() else ord('a')
decrypted_char = chr((ord(char) - ascii_offset - shift) % 26 + ascii_offset)
decrypted_text += decrypted_char
else:
decrypted_text += char
return decrypted_text
```
以上代码中,`shift_encrypt`函数用于加密文本,`shift_decrypt`函数用于解密文本。`text`参数是要加密或解密的文本,`shift`参数是位移量,表示字母要向后移动的位置数。
示例用法:
```python
text = "Hello, World!"
shift = 3
encrypted_text = shift_encrypt(text, shift)
print("加密后的文本:", encrypted_text)
decrypted_text = shift_decrypt(encrypted_text, shift)
print("解密后的文本:", decrypted_text)
```
输出结果:
```
加密后的文本: Khoor, Zruog!
解密后的文本: Hello, World!
```