凯撒密码用python实现
时间: 2023-09-19 21:12:14 浏览: 100
凯撒密码是一种简单的加密方法,它是通过将明文中的每个字母向后移动固定的位数来得到密文。例如,如果将明文中的每个字母向后移动3个位置,那么A就变成了D,B变成了E,以此类推。
下面是用Python实现凯撒密码的代码:
```python
def encrypt_caesar(plaintext, shift):
"""
Encrypts the plaintext using the Caesar cipher with the given shift.
"""
ciphertext = ""
for letter in plaintext:
if letter.isalpha():
# Shift the letter by the given amount, wrapping around if necessary
shifted_letter = chr((ord(letter.upper()) - 65 + shift) % 26 + 65)
ciphertext += shifted_letter
else:
# Leave non-alphabetic characters unchanged
ciphertext += letter
return ciphertext
def decrypt_caesar(ciphertext, shift):
"""
Decrypts the ciphertext using the Caesar cipher with the given shift.
"""
plaintext = ""
for letter in ciphertext:
if letter.isalpha():
# Shift the letter back by the given amount, wrapping around if necessary
shifted_letter = chr((ord(letter.upper()) - 65 - shift) % 26 + 65)
plaintext += shifted_letter
else:
# Leave non-alphabetic characters unchanged
plaintext += letter
return plaintext
```
这里定义了两个函数,一个用于加密明文,另一个用于解密密文。两个函数的实现方式基本相同,只是加密时是向后移动字母,解密时是向前移动字母。
使用示例:
```python
plaintext = "Hello, world!"
shift = 3
ciphertext = encrypt_caesar(plaintext, shift)
print(ciphertext) # "Khoor, zruog!"
decrypted_plaintext = decrypt_caesar(ciphertext, shift)
print(decrypted_plaintext) # "Hello, world!"
```
在这个示例中,将明文向后移动3个位置得到了密文,然后将密文向前移动3个位置得到了原始的明文。注意,这里只对字母进行了加密和解密,其他字符保持不变。
阅读全文