railfence栅栏密码加解密实现(python)

栅栏密码

原理

栅栏密码把要加密的明文分成 N 个一组,然后把每组的第 1 个字连起来,形成一段无规律的话。这里给出一个例子

明文:THERE IS A CIPHER

去掉空格后变为

THEREISACIPHER

分成两栏,两个一组得到

TH ER EI SA CI PH ER

先取出第一个字母,再取出第二个字母

TEESCPE
HRIAIHR

连在一起就是

TEESCPEHRIAIHR

上述明文也可以分为 2 栏。

THEREIS ACIPHER

组合得到密文

TAHCEIRPEHIESR

加解密脚本

from pycipher.railfence import Railfence


def railFence_encrypt(plaintext: str, key: int) -> str:
    """
    :param plaintext: 明文
    :param key:大于0的整数
    :return:
    """
    return Railfence(key).encipher(plaintext)


def railFence_decrypt(ciphertext: str, key: int) -> str:
    """

    :param ciphertext:密文
    :param key: 大于0的整数
    :return:
    """
    return Railfence(key).decipher(ciphertext)


def railfence_w_encrypt(plaintext: str, key: int) -> str:
    rails = [[] for _ in range(key)]
    rail, delta = 0, 1
    for ch in plaintext:
        rails[rail].append(ch)
        if rail == 0:
            delta = 1
        elif rail == key - 1:
            delta = -1
        rail += delta
    ciphertext = ''.join([ch for rail in rails for ch in rail])
    return ciphertext


def railfence_w_decrypt(ciphertext: str, key: int) -> str:
    fence = [[None] * len(ciphertext) for _ in range(key)]
    rail, delta = 0, 1
    for i in range(len(ciphertext)):
        fence[rail][i] = 1
        if rail == 0:
            delta = 1
        elif rail == key - 1:
            delta = -1
        rail += delta
    index = 0
    for i in range(key):
        for j in range(len(ciphertext)):
            if fence[i][j] == 1:
                fence[i][j] = ciphertext[index]
                index += 1
    rail, delta = 0, 1
    plaintext = ""
    for i in range(len(ciphertext)):
        plaintext += fence[rail][i]
        if rail == 0:
            delta = 1
        elif rail == key - 1:
            delta = -1
        rail += delta
    return plaintext


  • 5
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

bestkasscn

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值