Cryptography With Python 简明教程

Cryptography with Python - Affine Cipher

Affine 密码是乘法密码和凯撒密码算法的组合。Affine 密码的基本实现如下图所示−

Affine Cipher is the combination of Multiplicative Cipher and Caesar Cipher algorithm. The basic implementation of affine cipher is as shown in the image below −

affine cipher

在本章中,我们将通过创建对应的类来实现 Affine 密码,该类包括用于加密和解密的两个基本函数。

In this chapter, we will implement affine cipher by creating its corresponding class that includes two basic functions for encryption and decryption.

Code

您可以使用以下代码来实现 Affine 密码−

You can use the following code to implement an affine cipher −

class Affine(object):
   DIE = 128
   KEY = (7, 3, 55)
   def __init__(self):
      pass
   def encryptChar(self, char):
      K1, K2, kI = self.KEY
      return chr((K1 * ord(char) + K2) % self.DIE)

   def encrypt(self, string):
      return "".join(map(self.encryptChar, string))

   def decryptChar(self, char):
      K1, K2, KI = self.KEY
      return chr(KI * (ord(char) - K2) % self.DIE)

   def decrypt(self, string):
      return "".join(map(self.decryptChar, string))
		affine = Affine()
print affine.encrypt('Affine Cipher')
print affine.decrypt('*18?FMT')

Output

当您实现 Affine 密码时,可以看到以下输出−

You can observe the following output when you implement an affine cipher −

affine

输出显示了纯文本消息的加密消息 Affine Cipher 以及作为输入发送的消息的解密消息 abcdefg.

The output displays the encrypted message for the plain text message Affine Cipher and decrypted message for the message sent as input abcdefg.