凯撒密码加密算法python
时间: 2023-05-28 18:01:52 浏览: 93
以下是凯撒密码加密算法的Python实现代码:
```
def caesar_cipher(plaintext, key):
ciphertext = ''
for char in plaintext:
if char.isalpha():
char_code = ord(char)
if char.isupper():
ciphertext += chr((char_code - 65 + key) % 26 + 65)
else:
ciphertext += chr((char_code - 97 + key) % 26 + 97)
else:
ciphertext += char
return ciphertext
```
其中,参数`plaintext`是要加密的明文,`key`是密钥。函数返回加密后的密文。该函数实现的凯撒密码算法是将明文中的所有字母按照字母表偏移`key`个位置进行替换,非字母字符不变。
相关问题
python凯撒密码加密算法
凯撒密码是一种古老的加密算法,它通过将明文中的每个字母按照一定的规则替换成密文中的字母来实现加密。下面是使用Python实现凯撒密码加密算法的代码:
```python
def caesar_encrypt(plaintext, key):
ciphertext = ""
for char in plaintext:
if char.isalpha():
if char.isupper():
ciphertext += chr((ord(char) + key - 65) % 26 + 65)
else:
ciphertext += chr((ord(char) + key - 97) % 26 + 97)
else:
ciphertext += char
return ciphertext
```
其中,`plaintext`是要加密的明文,`key`是密钥,表示每个字母向前移动的位数。这个函数会返回加密后的密文。
下面是一个例子,演示如何使用这个函数加密一个字符串:
```python
plaintext = "Hello, World!"
key = 3
ciphertext = caesar_encrypt(plaintext, key)
print(ciphertext) # 输出:Khoor, Zruog!
```
这个例子中,我们将明文字符串`"Hello, World!"`加密成了密文字符串`"Khoor, Zruog!"`,密钥为3。
凯撒密码加密解密算法Python
凯撒密码是一种简单的替换密码,它是通过将字母表中的每个字母向后(或向前)移动固定数量的位置来进行加密和解密的。这个固定的移动数量被称为偏移量或密钥。
下面是一个用Python实现凯撒密码加密和解密的示例代码:
```python
def caesar_encrypt(text, key):
encrypted_text = ""
for char in text:
if char.isalpha():
if char.isupper():
encrypted_text += chr((ord(char) - 65 + key) % 26 + 65)
else:
encrypted_text += chr((ord(char) - 97 + key) % 26 + 97)
else:
encrypted_text += char
return encrypted_text
def caesar_decrypt(encrypted_text, key):
decrypted_text = ""
for char in encrypted_text:
if char.isalpha():
if char.isupper():
decrypted_text += chr((ord(char) - 65 - key) % 26 + 65)
else:
decrypted_text += chr((ord(char) - 97 - key) % 26 + 97)
else:
decrypted_text += char
return decrypted_text
# 示例用法
text = "Hello, World!"
key = 3
encrypted_text = caesar_encrypt(text, key)
print("加密后的文本:", encrypted_text)
decrypted_text = caesar_decrypt(encrypted_text, key)
print("解密后的文本:", decrypted_text)
```
这段代码中,`caesar_encrypt`函数用于加密文本,`caesar_decrypt`函数用于解密文本。`text`是要加密或解密的文本,`key`是偏移量或密钥,表示字母向后(或向前)移动的位置数。