SoFunction
Updated on 2024-10-29

Python-based decryption of affine ciphers

There is a cryptography class in the new semester, and in the class the instructor assigned a cryptography problem with the following title.

Decrypts the ciphertext "DBUHU SPANO SMPUS STMIU SBAKN OSMPU SS" encrypted by the affine cipher.

To decrypt this ciphertext, you must first know what the affine cipher is.

An affine cipher is a substitution cipher with the following encryption and decryption formulas

Encryption: C=E([a,b],p)=(ap+b) mod 26C=E([a,b],p)=(ap+b) mod 26

Decryption: p=D([a,b],C)=((C-b)/a) mod 26p=D([a,b],C)=((C-b)/a) mod 26

Obviously can not be decrypted by human power, we have to resort to computer programs, the following is the code I wrote to decrypt with Python, the output results to be used with the knowledge of linguistics (naked eye observation) to identify which is the plaintext we need. In addition, the decryption process involves the process of finding the inverse element, which requires the definition of a function NI.

#encoding:utf-8

def NI(x,b): # Define the function NI that finds the inverse of x with respect to b, where (NI(x,b)*x) mod b = 1 The inverse found when x and b are mutually prime is unique.
  i = 1
  while (x*i)%b != 1:
    i = i + 1
  return i

c = "DBUHU SPANO SMPUS STMIU SBAKN OSMPU SS"
C = []

#The ciphertext is preprocessed and stored in a list in the form of the bit order of the corresponding letters in the 26 letters of the English alphabet.
for i in c:
  if i == ' ':
    (i)
  else:
    (ord(i)-65)

# Store the possible values of a in the encryption algorithm in a list
a = [3,5,7,9,11,15,17,19,21,23,25]
P = []

for keyb in range(0,26):
  for keya in a:
    ni_a = NI(keya,26)
    for s in C:
      if s == ' ':
        (' ')
      else:
        (((s-keyb)*ni_a)%26) # Add the bit codes corresponding to the plaintext letters to the plaintext list in sequence
    strP = ''
    for t in P:
      if t==' ':
        strP = strP + ' '
      else:
        strP = strP + chr(t+97) # Convert plaintext to a string and output it
    print(strP)
    P = []

Run the file and print out all possible plaintexts in turn. After searching, the following line is found to be the requested plaintext.

Reading the plaintext should betheres no business like show business。

This is the whole content of this article.