关键字密码(Nihilist)

关键字密码(Nihilist)

  • 加密对象:小写字母
  • 原理:
    • 是棋盘密码的变种,相对于棋盘密码,改密码的密码表是变化的,相对于关键字而变化

    • 关键字就是一种秘钥,由字母组成,由加密双方约定而成。密码表有25个位置,依次不重复的填入秘钥,在不重复的填入a~z.

    • 如:秘钥为linux,则密码表为:

      12345
      1linux
      2abcde
      3fghkm
      4opqrs
      5tvwyz
    • 在将明文的每个字符通过查表找出行号和列号,行号在前,列号在后就组成了密文,最后将所有字符的密文以空格隔开组成最后的密文

    • 如:在"linux"为关键字的情况下,加密"abc"

      • a -> 21
      • b -> 22
      • c -> 23
      • 故密文为: “21 22 23”
  • 代码
    # write by 2021/7/6
    # 关键字密码,一种棋盘密码的变种
    
    
    def create_table(key):
        key = key + "abcdefghiklmnopqrstuvwxyz"
        table = ""
        for i in key.replace("j", "i"):
            if i not in table:
                table += i
        return table
    
    
    def encrypt_nihilist(string, key):
        ciphertext = ""
        table = create_table(key)
        for i in string.replace("j", "i").replace(" ", ""):
            if i in table:
                index = table.index(i)
                ciphertext += str(index // 5 + 1) + str(index % 5 + 1) + " "
            else:
                return -1
        return ciphertext.strip()
    
    
    def decrypt_nihilist(string, key):
        plaintext = ""
        table = create_table(key)
        lis = string.split(" ")
        try:
            for i in lis:
                index = (int(i[0]) - 1) * 5 + int(i[1]) - 1
                plaintext += table[index]
                if table[index] == "i":
                    plaintext += "(j)"
        except:
            return -1
        return plaintext
    
    
    if __name__ == '__main__':
        ciphertext_ = encrypt_nihilist("linux", "linux")
        plaintext_ = decrypt_nihilist(ciphertext_, "linux")
        print(f"{plaintext_}: {ciphertext_}")
    
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值