编写Python代码实现Vigenere 密码算法和Hill密码算法
时间: 2024-09-29 10:08:36 浏览: 58
python实现经典密码学中Vigenere算法工程文件
Vigenère密码是一种简单的替换式加密技术,通过将明文和密钥按字符周期交替组合来达到加密目的。下面是一个简单的 Python 示例,展示了如何使用 Vigenère密码进行加密:
```python
def vigenere_encrypt(plaintext, key):
key_length = len(key)
encrypted_text = ""
for i in range(len(plaintext)):
char = plaintext[i]
if char.isalpha():
shift = ord(key[i % key_length].upper()) - ord('A')
shifted_char = chr(((ord(char.upper()) - ord('A') + shift) % 26) + ord('A'))
if char.islower():
encrypted_text += shifted_char.lower()
else:
encrypted_text += shifted_char
else:
encrypted_text += char
return encrypted_text
# 示例用法
plaintext = "Hello, World!"
key = "KEY"
encrypted = vigenere_encrypt(plaintext, key)
print(f"Encrypted text: {encrypted}")
```
至于 Hill密码,这是一种基于矩阵运算的块加密算法,用于加密固定长度的字符块(如3x3字母)。由于涉及到矩阵操作,需要更复杂的数学处理。以下是 Hill密码加密的一个基础示例:
```python
import numpy as np
def rotate_matrix(matrix, shift):
n = matrix.shape[0]
result = [[0] * n for _ in range(n)]
for i in range(n):
for j in range(n):
result[(i + shift) % n][(j + shift) % n] = matrix[i][j]
return result
def multiply_matrices(matrix1, matrix2):
result = np.zeros((matrix1.shape[0], matrix2.shape[1]), dtype=int)
for i in range(result.shape[0]):
for j in range(result.shape[1]):
for k in range(matrix1.shape[1]):
result[i][j] += (matrix1[i][k] * matrix2[k][j])
return result % 26
def hill_cipher_encrypt(text_blocks, key_matrix):
encrypted_blocks = []
for block in text_blocks:
# 字符转数字(小写字母)
block_num = [ord(c.lower()) - ord('a') for c in block]
# 将字符块扩展到矩阵大小,如果不足填充0
if len(block_num) < key_matrix.shape[0]:
pad = [(0, 0)] * ((key_matrix.shape[0] - len(block_num)) // 2) + [(len(block_num), 0)]
block_num.extend([pad[i][0] for i in range(len(pad))])
encrypted_block_num = multiply_matrices(np.array(block_num).reshape(key_matrix.shape), key_matrix)
encrypted_block = ''.join(chr(i + ord('a')) for i in encrypted_block_num.reshape(-1))
encrypted_blocks.append(encrypted_block)
return encrypted_blocks
# 示例用法
text = "Example text to encrypt"
key = "KRYPTOS"
key_matrix = generate_key_matrix(key) # 实现生成一个合适的密钥矩阵
blocks = chunks(text, 3) # 分割成3x3的字符块
encrypted_blocks = hill_cipher_encrypt(blocks, key_matrix)
```
注意,实际应用中你需要实现 `generate_key_matrix` 函数来生成适合的密钥矩阵,并确保文本块的分割、填充和矩阵乘法规则正确。
阅读全文