置换密码python编程
时间: 2024-01-06 14:24:34 浏览: 21
置换密码是一种古典加密算法,它通过对明文中的字符进行重新排列来生成密文。在Python中,我们可以使用简单的编程技巧来实现置换密码。
下面是一个示例代码,演示了如何使用置换密码对明文进行加密和解密:
```python
def encrypt(plaintext, key):
ciphertext = ''
for char in plaintext:
if char.isalpha():
if char.isupper():
ciphertext += chr((ord(char) - 65 + key) % 26 + 65)
else:
ciphertext += chr((ord(char) - 97 + key) % 26 + 97)
else:
ciphertext += char
return ciphertext
def decrypt(ciphertext, key):
plaintext = ''
for char in ciphertext:
if char.isalpha():
if char.isupper():
plaintext += chr((ord(char) - 65 - key) % 26 + 65)
else:
plaintext += chr((ord(char) - 97 - key) % 26 + 97)
else:
plaintext += char
return plaintext
plaintext = "Hello, World!"
key = 3
ciphertext = encrypt(plaintext, key)
print("Encrypted text:", ciphertext)
decrypted_text = decrypt(ciphertext, key)
print("Decrypted text:", decrypted_text)
```
运行以上代码,输出结果如下:
```
Encrypted text: Khoor, Zruog!
Decrypted text: Hello, World!
```
这个示例代码实现了一个简单的置换密码算法,它将明文中的字母按照指定的密钥进行偏移,生成密文。解密过程则是将密文中的字母按照相反的偏移量进行还原,得到原始的明文。