5.2 Caesar cipher - decrypt python

Task for this level: Please program to calculate the offset, and use the obtained offset to decrypt the read ciphertext.

code show as below:

import string

def caesar_decrypt(text, offset):
    """接收一个加密的字符串text和一个整数offset为参数,采用字母表和数字中前面第offset个字符
    代替当前字符的方法对字符串中的字母和数字进行替换,实现解密效果,返回值为解密的字符串。"""
    ###############################Begin#############################################
    lower = string.ascii_lowercase          # 小写字母
    upper = string.ascii_uppercase          # 大写字母
    digit = string.digits                # 数字
    before = string.ascii_letters + digit
    after = lower[offset:] + lower[:offset] + upper[offset:] + upper[:offset] + digit[offset:] + digit[:offset]
    table = ''.maketrans(after, before)
    decrypt_text = text.translate(table)
    return decrypt_text  


    ################################End##############################################

def find_offset(key_text, ciphertext):
    """接收一个单词和一个加密字符串为参数,尝试用[0,25]之间的数为偏移量进行解密。
        如果key_text 在解密后的明文里,则说明解密成功。
    找出偏移量数值并返回这个整数偏移量。"""
    ###############################Begin#############################################
    for i in range(26):
        plain_text = caesar_decrypt(ciphertext, i) #使用i作为偏移量,尝试解密得到明文
        if key_text in plain_text : # 如果key_text在明文里,说明偏移值为i时能成功解密
            return i
    ################################End##############################################


if __name__ == '__main__':
    key_message = 'question'                                   #密文中的已知单词
    cipher_text = 'Yt gj,tw sty yt gj,ymfy nx f vzjxynts.'      #截获的密文
    secret_key = find_offset(key_message, cipher_text)   #破解密码,得到密匙
    print(f'密钥是{secret_key}')
    
    target_text = input() #读入新密文,进行解密
    #'Fyyfhp ts Ujfwq Mfwgtw ts Ijhjrgjw 2, 6496'   #新密文,需要解密
    print(caesar_decrypt(target_text, secret_key))  #解密,打印明文
    

caesar cipher

The Caesar encryption method can produce new changes according to different shifts. For example, by shifting each letter to the 19left , such a clear and secret comparison table (taking uppercase letters as an example):

明:A B C D E F G H I J K L M N O P Q R S T U V W X Y Z

密:T U V W X Y Z A B C D E F G H I J K L M N O P Q R S

Under this encryption table, the comparison relationship between plaintext and ciphertext becomes:

明文:THE FAULT, DEAR BRUTUS, LIES NOT IN OUR STARS BUT IN OURSELVES.

密文:MAX YTNEM, WXTK UKNMNL, EBXL GHM BG HNK LMTKL UNM BG HNKLXEOXL.

In this way, every time an offset value is changed, a different encryption result can be obtained, and this method can improve the encryption strength to a certain extent.

Python String module built-in attributes

  • string.ascii_lowercase Lower case letters
  • string.ascii_uppercase uppercase letter
  • string.digits numbers 0-9
def caesar_decrypt(text, offset):
"""接收一个加密的字符串text和一个整数offset为参数,采用字母表和数字中前面第offset个字符
代替当前字符的方法对字符串中的字母和数字进行替换,实现解密效果,返回值为解密的字符串。"""
lower = string.ascii_lowercase # 小写字母
upper = string.ascii_uppercase # 大写字母
digit = string.digits # 数字
before = string.ascii_letters + digit
after = lower[offset:] + lower[:offset] + upper[offset:] + upper[:offset] + digit[offset:] + digit[:offset]
table = ''.maketrans(after, before)
decrypt_text = text.translate(table)
return decrypt_text

Python common functions

(1)range

range()The function returns an iterable object (the type is object), not a list type, so the list will not be printed when printing.

grammar:

range(stop)
range(start, stop[, step])

Parameter Description

  • start: Counting starts from start. The default is to start from 0. For example range(3) is equivalent to range(0, 3);

  • stop: Count up to stop, but not including stop. For example: range (0, 3) is [0, 1, 2] without 3

  • step: step size, the default is 1. For example: range(0, 3) is equivalent to range(0, 3, 1)

    def find_offset(key_text, ciphertext):
    """接收一个单词和一个加密字符串为参数,尝试用[0,25]之间的数为偏移量进行解密。
    如果key_text 在解密后的明文里,则说明解密成功。
    找出偏移量数值并返回这个整数偏移量。"""
    for i in range(26):
    plain_text = caesar_decrypt(ciphertext, i) #使用i作为偏移量,尝试解密得到明文
    if key_text in plain_text : # 如果key_text在明文里,说明偏移值为i时能成功解密
    return i

(2)maketrans

maketrans()The method is used to create the conversion table of the character map. For the simplest calling method that accepts two parameters, the first parameter is a string, indicating the character to be converted, and the second parameter is also a string indicating the conversion target.

grammar:

str.maketrans(intab, outtab)

Parameter Description

  • intab -- A string of characters to substitute in the string.
  • outtab – A string of corresponding mapped characters.

Guess you like

Origin blog.csdn.net/m0_70456205/article/details/129778673