playfair密码代码python语言和运行操作

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
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值