def encrypt(plaintext, key):
# 生成Playfair密码矩阵
matrix = generate_matrix(key)
# 将明文分组并加密
ciphertext = ""
plaintext = plaintext.upper().replace("J", "I") # 将J替换为I
plaintext = "".join([i for i in plaintext if i.isalpha()]) # 去除非字母字符
plaintext += "X" * (len(plaintext) % 2) # 补齐成偶数长度
for i in range(0, len(plaintext), 2):
pair = plaintext[i:i + 2]
row1, col1 = find_position(matrix, pair[0])
row2, col2 = find_position(matrix, pair[1])
if row1 == row2:
ciphertext += matrix[row1][(col1 + 1) % 5] + matrix[row2][(col2 + 1) % 5]
elif col1 == col2:
ciphertext += matrix[(row1 + 1) % 5][col1] + matrix[(row2 + 1) % 5][col2]
else:
ciphertext += matrix[row1][col2] + matrix[row2][col1]
return ciphertext
playfair密码代码python语言和运行操作
最新推荐文章于 2024-09-21 11:33:05 发布