对字母与数字进行凯撒加密py
时间: 2024-03-15 14:42:58 浏览: 14
好的,以下是对字母和数字进行凯撒加密的Python实现:
```python
def caesar_cipher(text, shift):
result = ""
for char in text:
if char.isalpha():
if char.isupper():
result += chr((ord(char) + shift - 65) % 26 + 65)
else:
result += chr((ord(char) + shift - 97) % 26 + 97)
elif char.isdigit():
result += str((int(char) + shift) % 10)
else:
result += char
return result
```
其中,`text`是要加密的明文,`shift`是移位数。这个函数会将明文中的字母和数字按照移位数进行移动,并返回加密后的密文。对于其他字符,不做处理。
示例:
```python
text = "Hello, World! 123"
shift = 3
ciphertext = caesar_cipher(text, shift)
print(ciphertext) # "Khoor, Zruog! 456"
```
注意,同样由于凯撒密码的加密算法本身存在弱点,容易被破解,因此不适用于对安全性要求较高的加密场景。