Simple Caesar cipher implementation, very easy

Concept and Principle

According to the explanation on Baidu Encyclopedia, the Caesar cipher is an ancient encryption algorithm.

The use of ciphers can be traced back to ancient Roman times. The Gallic Wars describes that Caesar once used ciphers to transmit information, the so-called "Caesar cipher", which is an alternative cipher that pushes letters in sequence. The last 3 digits play an encryption role, such as replacing the letter A with the letter D, and replacing the letter B with the letter E. Because Caesar is said to be one of the first ancient generals to use encrypted letters, this encryption method is called the Caesar cipher. This is a simple encryption method. The density of this password is very low, and it can be deciphered by simply counting the word frequency. Now it is also called "shift cipher", but the number of moves is not necessarily 3 bits.

Cryptography can be roughly divided into two categories, namely translocation and substitution, and of course there are more complex methods that combine the two. In translocation, the letter does not change, but the position changes; in substitution, the letter changes, but the position does not change.

The first documented use of substitution ciphers for military use is Caesar's Book of Gallic. Caesar describes how he sent secret letters to Cicero, who was besieged and on the verge of surrender. The Roman letters were replaced with Greek letters so that the enemy could not understand the information at all.

One of the substitution ciphers used by Caesar is described in detail in Sutonius' "Biography of Caesar" written in the second century AD. Caesar simply replaced each letter in the message with the third letter in the alphabet after that letter. This cipher substitution is often called a Caesar shift cipher, or simply, a Caesar cipher.

In cryptography, the Caesar cipher (or Caesar encryption, Caesar transformation, transformation encryption) is the simplest and most widely known encryption technology. It is a technique to replace encryption. This encryption method is named after Caesar, who used this method to communicate with his generals. The Caesar cipher is often used as a step in other, more complex encryption methods, such as the Virginia cipher. The Caesar cipher is also used in modern ROT13 systems. But like all encryption techniques that use alphabets to replace, the Caesar cipher is very easy to crack, and it is impossible to guarantee communication security in practical applications.

Having said so much, I believe that everyone may be a little dizzy. The encryption method of the following picture is to implement the encryption function by wrong three bits.

(1) Design ideas:

  1. Since the input is a string of English characters, we use the String class to write, and the String class has many methods that can be called
  2. The dislocation needs to operate on each character. The string can be converted into a character array, and the toCharArray method of the string class is called.
  3. Since the string class also uses the Unicode character set, we only need to read one character when performing the dislocation operation, add it to the number 3, and then convert it to the char type to implement the wrong 3-bit encryption operation, and subtract 3 for decryption.
  4. In the encryption operation, if the encryption is the last three letters of the alphabet, a circular operation must be implemented, that is, X encryption is A, Y encryption is B, Z encryption is C, and ASCII code is used to achieve this. When XYZ is read, the encryption is converted to char type after subtracting 23. Of course, ABC plus 23 can be read when decrypting

(2) Program flow chart:

Implementation process

We define a key=13, at this time we encrypt the string This is my secret message

import pyperclip

message = 'This is my secret message'#保存加密或解密的字符串
key = 13#保存加密密钥的整数

mode = 'encrypt'

LETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'

translated = ''

message = message.upper()

for symbol in message:
    if symbol in LETTERS:
        num = LETTERS.find(symbol)
        if mode == 'encrypt':
            num = num + key
        elif mode == 'decrypt':
            num = num - key

        if num >= len(LETTERS):
            num = num - len(LETTERS)
        elif num < 0:
            num = num + len(LETTERS)

        translated = translated + LETTERS[num]

    else:
        translated = translated + symbol

print(translated)

pyperclip.copy(translated)

The print result is as follows:

GUVF VF ZL FRPERG ZRFFNTR
[Finished in 0.8s]

Let's analyze the above code

We can see that the first line calls a pyperclip module, we need to download this module, very simple, install a pip, directly enter pip install pyperclip to complete the installation

message = 'This is my secret message'#保存加密或解密的字符串
key = 13#保存加密密钥的整数

message specifies the string used to save encryption and decryption

The key is used to store the encryption key

message = message.upper()

An upper function is called to convert all encrypted and decrypted strings into uppercase letters

The following implementation process is very simple, judge whether the mode value is encrpy, and then shift the characters

Cracking principle and implementation

We will crack the encrypted string, and the implementation principle is as follows:

import pyperclip

message = 'GUVF VF ZL FRPERG ZRFFNTR'

LETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'

for key in range(len(LETTERS)):

    translated = ''

    for symbol in message:
        if symbol in LETTERS:
            num = LETTERS.find(symbol)
            num = num - key

            if num < 0:
                num = num + len(LETTERS)

            translated = translated + LETTERS[num]

        else:
            translated = translated + symbol

    print('Key #%s:%s'%(key,translated))

The print result is as follows:

Key #0:GUVF VF ZL FRPERG ZRFFNTR
Key #1:FTUE UE YK EQODQF YQEEMSQ
Key #2:ESTD TD XJ DPNCPE XPDDLRP
Key #3:DRSC SC WI COMBOD WOCCKQO
Key #4:CQRB RB VH BNLANC VNBBJPN
Key #5:BPQA QA UG AMKZMB UMAAIOM
Key #6:AOPZ PZ TF ZLJYLA TLZZHNL
Key #7:ZNOY OY SE YKIXKZ SKYYGMK
Key #8:YMNX NX RD XJHWJY RJXXFLJ
Key #9:XLMW MW QC WIGVIX QIWWEKI
Key #10:WKLV LV PB VHFUHW PHVVDJH
Key #11:VJKU KU OA UGETGV OGUUCIG
Key #12:UIJT JT NZ TFDSFU NFTTBHF
Key #13:THIS IS MY SECRET MESSAGE
Key #14:SGHR HR LX RDBQDS LDRRZFD
Key #15:RFGQ GQ KW QCAPCR KCQQYEC
Key #16:QEFP FP JV PBZOBQ JBPPXDB
Key #17:PDEO EO IU OAYNAP IAOOWCA
Key #18:OCDN DN HT NZXMZO HZNNVBZ
Key #19:NBCM CM GS MYWLYN GYMMUAY
Key #20:MABL BL FR LXVKXM FXLLTZX
Key #21:LZAK AK EQ KWUJWL EWKKSYW
Key #22:KYZJ ZJ DP JVTIVK DVJJRXV
Key #23:JXYI YI CO IUSHUJ CUIIQWU
Key #24:IWXH XH BN HTRGTI BTHHPVT
Key #25:HVWG WG AM GSQFSH ASGGOUS
[Finished in 0.2s]

We can see that Key#13 is the answer we are looking for.

Guess you like

Origin blog.csdn.net/qq_41701956/article/details/123455294