仿射密码(Affine)

本文介绍了仿射密码的加密和解密原理,利用模运算和乘法逆元对英文字母进行转换。给出了Python代码实现,包括加密函数`encrypt_affine`、解密函数`decrypt_affine`以及遍历解密函数`decrypt2_affine`,并展示了加密和解密的示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

仿射密码(Affine)

  • 加密对象: 英文字母
  • 原理:
    • 该密码运用了乘法逆元和模运算
    • a~z对应于0~25, 将明文的每个字符转为对应的数字
    abcdefghijklmnopqrstuvwxyz
    012345678910111213141516171819202122232425
    • 加密函数:D(x) = (a*x+b) (mod 26),这里a,b变量就是密钥,注意 a必须和26互质
    • 通过加密函数得到密文的数字,在查表,组合在一起就构成了密文。
    • 解密过程与加密类似
    • 解密函数: E(x) = a-1(x-b) (mod 26), 这里a-1是a关于26的乘法逆元。
  • 代码:
    # write by 2021/6/28
    
    DIC = "abcdefghijklmnopqrstuvwxyz"
    
    
    # 辗转相除法
    def gcd(a, b):
        a, b = b, a % b
        # print(a, b)
        if b == 0:
            return a
        else:
            return gcd(a, b)
    
    
    # 扩展欧几里得算法
    def exgcd(a, b):
        if b == 0:
            return 1, 0
        x, y = exgcd(b, a % b)
        return y, x-(a//b)*y
    
    
    def encrypt_affine(string, a, b):
        ciphertext = ""
        if gcd(a, 26) != 1 and gcd(a, 26) != -1:
            return -1
        for i in string.lower():
            if i not in DIC:
                ciphertext += i
            else:
                ciphertext += DIC[(a*DIC.index(i)+b) % 26]
        return ciphertext
    
    
    # 直接遍历所有26可能,找到为止
    def decrypt2_affine(string, a, b):
        plaintext = ""
        if gcd(a, 26) != 1 and gcd(a, 26) != -1:
            return -1
        for i in string.lower():
            if i not in DIC:
                plaintext += i
            # (x*7+3)%26 = 4
            else:
                for x in range(26):
                    if (x*a + b) % 26 == DIC.index(i):
                        # print("x=", x)
                        plaintext += DIC[x]
                        break
        return plaintext
    
    
    # 根据扩展欧几里得算法找到乘法逆元,在求解
    def decrypt_affine(string, a, b):
        plaintext = ""
        if gcd(a, 26) != 1 and gcd(a, 26) != -1:
            return -1
        a_26_inv = exgcd(a, 26)[0]
        for i in string:
            if i not in DIC:
                return -1
            plaintext += DIC[a_26_inv*(DIC.index(i)-b) % 26]
        return plaintext
    
    
    if __name__ == '__main__':
        # print(exgcd(3, 26))
        a, b = 2, 21
        ciphertext_ = encrypt_affine("AFFINECIPHER", a, b)
        plaintext_ = decrypt_affine(ciphertext_, a, b)
        plaintext_2 = decrypt2_affine(ciphertext_, a, b)
        print(f"{plaintext_}: {ciphertext_}")
        print(f"{plaintext_2}: {ciphertext_}")
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值