什么是栅格密码
栅格密码的生成规则很简单。首先将明文 (Plaintext) 分成若干行书写,然后再逐行首尾连接起来。
比如对 “example” 一词进行 2 行的加密。
Groups | 1 | 2 | 3 | 4 |
---|---|---|---|---|
Group 1 | e | a | p | e |
Group 2 | x | m | l |
得到密文 (Cipher) :
Index | 0 | 1 | 2 | 3 | 4 | 5 | 6 |
---|---|---|---|---|---|---|---|
e | a | p | e | x | m | l |
如何生成密码
生成逻辑
可以先将密文视为一个列表 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"