Python 生成与破解栅格密码

什么是栅格密码

栅格密码的生成规则很简单。首先将明文 (Plaintext) 分成若干行书写,然后再逐行首尾连接起来。

比如对 “example” 一词进行 2 行的加密。

Groups1234
Group 1eape
Group 2xml

得到密文 (Cipher) :

Index0123456
eapexml

如何生成密码

生成逻辑

可以先将密文视为一个列表 group,并已知它将会被拆分成 groups 组。
因为 group 被拆为 groups 个部分,可以理解为 group 中有 groups 个小组。

for i in range(groups):
	group.append([])

接下来,将明文中的每一个字符依次放到列表中。

for i in range(len(plaintext)):
	if plaintext[i] != " ": # 忽略明文中的空格
		group[i % groups].append(plaintext[i])

最后将列表中所有的字符串重新连接在一起。

cipher = ""
for i in range(groups):
	for j in group[i]:
		cipher += j
return cipher
完整代码
def enFence(plaintext, groups):
    rPlaintext = plaintext.lower()
    group = []
    for i in range(groups):
        group.append([])
    for i in range(len(rPlaintext)):
        if rPlaintext[i] != " ":
            group[i % groups].append(rPlaintext[i])

    cipher = ""
    for i in range(groups):
        for j in group[i]:
            cipher += j
    return cipher

调用 enFence() 函数就可以生成加密后的密文。

如何破解密码

破解条件

破解的前提是已经知道密文被加密时是被拆分为 groups 组。

代码
def deFence(cipher, groups):
    # groups 表示明文被分成了几组
    if groups > len(cipher):
        return IndexError
    rC = cipher.lower()  # real cipher
    less = len(rC) % groups  # 获取有几项多出了 1 个元素 example.less = 1, letter = "e"[3]
    rItems = len(rC) // groups  # 获取标准的一项有多少个元素 example.rItems = 3
    # 没有添加项的 Cipher
    no_add_cipher = []  # e[0], a[1], p[2], x[4], m[5], l[6]
    ignore = []
    for i in range(len(rC)):
        if not (i % rItems) and len(ignore) < less and i > 0:
            ignore.append(i)
        else:
            no_add_cipher.append(rC[i])
    # 对 no_add_cipher 切片
    spl = []  # [[e, a, p], [x, m, l]]
    for i in range(groups):
        spl.append(no_add_cipher[i * rItems: (i + 1) * rItems])
    plaintext = ""
    for i in range(rItems):
        for j in range(groups):
            plaintext += spl[j][i]
    for i in range(len(ignore)):
        plaintext += rC[ignore[i]]
    return plaintext

调用 deFence() 函数就可以破解已知 groups 的栅格密码。

验证函数可行性
print(deFence(enFence("HelloWorld", 3), 3))
# 返回结果 "helloworld"
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值