维吉尼亚加密算法python
时间: 2024-10-08 13:04:16 浏览: 56
维吉尼亚加密算法(Vigenère cipher),又称为凯撒密码的一种变体,是一种古典的替换式加密技术,它通过将明文和一个密钥进行位移操作来进行加密。在Python中,你可以使用简单的循环和字母索引来实现维吉尼亚加密。下面是一个基本的Python代码示例:
```python
def vigenere_cipher(plaintext, key):
encrypted_text = ""
key_length = len(key) # Key length is taken as a modulus of the plaintext length if needed
for i in range(len(plaintext)):
char = plaintext[i]
if char.isalpha(): # Only encrypting alphabetic characters
shift = ord(key[(i % key_length)]) # Shift based on key's position in alphabet
new_char = chr((ord(char.lower()) + shift - ord('a')) % 26 + ord('a'))
if char.isupper():
new_char = new_char.upper()
encrypted_text += new_char
else:
encrypted_text += char
return encrypted_text
# Example usage
plaintext = "Hello, world!"
key = "secret"
encrypted = vigenere_cipher(plaintext, key)
print(f"Plaintext: {plaintext}\nEncrypted: {encrypted}\n")
阅读全文
相关推荐
















