Python zero basic programming - 09 practical cryptology chapter - encryption and decryption of classical encryption algorithm

abstract

Book to previous:

1-Zero basic programming -- Python basic

2-Zero basic programming: basic theory of cryptography

In the previous part, we shared the basic theory of cryptography. Starting from Morse code, we analyzed Caesar encryption, transposition encryption, digital multiplication encryption, affine encryption, simple substitution, multi table substitution, symmetric encryption, asymmetric encryption RSA encryption and so on. This article continues to share the actual use of combat. For the classical encryption algorithm encryption and decryption, learn to encrypt and decrypt the plaintext in Python programming, as well as the password cracking practice.

 

content

1 - Caesar encryption programming practice
 2-reverse encryption programming practice
 3-transposition encryption programming practice
 4-multiplication encryption programming practice



0-Python cryptography library installation

The basic encryption algorithm for cryptography, in fact, can be written by yourself, but in order to not waste time, make full use of existing resources, stand on the shoulders of giants to learn.

We use cryptographic, pycipher and other libraries

#Source code reference
https://github.com/pyca/cryptography/tree/master/src/cryptography
https://github.com/jameslyons/pycipher


#Installation and use
pip install cryptography
pip install pycipher
 #Do not understand the use of children's shoes, please refer to our Python basic chapter

 

0-Python cryptography library installation

The basic encryption algorithm for cryptography, in fact, can be written by yourself, but in order to not waste time, make full use of existing resources, stand on the shoulders of giants to learn.

We use cryptographic, pycipher and other libraries

#Source code reference
https://github.com/pyca/cryptography/tree/master/src/cryptography
https://github.com/jameslyons/pycipher
#Installation and use
pip install cryptography
pip install pycipher
#Do not understand the use of children's shoes, please refer to our Python basic chapter

 

1 - Caesar encryption programming practice

  • Actual combat:
def encode(string, shift):
    cipher = ''
    for char in string:
        if char == ' ':
            cipher = cipher + char
        elif char.isupper():
            cipher = cipher + chr((ord(char) + shift - ord('A')) % 26 + ord('A'))
        else:
            cipher = cipher + chr((ord(char) + shift - ord('a')) % 26 + ord('a'))

    return cipher


def decode(text, s):
    result = ""
    for x in text:
        if(x == ' '):
            result += " "
        elif(ord(x)-ord('A')-s < 0):
            result += chr(ord(x)-s+26)
        else:
            result += chr(ord(x)-s)
    return result


text = 'Hello FreoStudio Welcome U '
print('Clear text:'+text)
text = encode(text, 4)  # encryption
print('Ciphertext:'+text)
decode(text, 4)

When we don't know the key Key=4, it will burst:

for key in range(0, 26):
    print('Key='+str(key))
    text = decode('Lipps JvisWxyhms Aipgsqi Y', key)
    print(text)
#Operation result:
Key=0
Lipps JvisWxyhms Aipgsqi Y
Key=1
Khoor IuhrVwxglr Zhofrph X
Key=2
Jgnnq HtgqUvwfkq Ygneqog W
Key=3
Ifmmp GsfpTuvejp Xfmdpnf V
Key=4
Hello FreoStudio Welcome U
Key=5
Gdkkn EqdnRstchn Vdkbnld T
Key=6
Fcjjm DpcmQrsbgm Ucjamkc S
Key=7
Ebiil CoblPqrafl Tbi`ljb R
Key=8
Dahhk BnakOpq`ek Sah_kia Q
Key=9
C`ggj Am`jNop_dj R`g^jh` P
Key=10
B_ffi Zl_iMno^ci Q_f]ig_ O
Key=11
A^eeh Yk^hLmn]bh P^e\hf^ N
Key=12
Z]ddg Xj]gKlm\ag O]d[ge] M
Key=13
Y\ccf Wi\fJkl[`f N\cZfd\ L
Key=14
X[bbe Vh[eIjkZ_e M[bYec[ K
Key=15
WZaad UgZdHijY^d LZaXdbZ J
Key=16
VY``c TfYcGhiX]c KY`WcaY I
Key=17
UX__b SeXbFghW\b JX_Vb`X H
Key=18
TW^^a RdWaEfgV[a IW^Ua_W G
Key=19
SV]]` QcV`DefUZ` HV]T`^V F
Key=20
RU\\_ PbU_CdeTY_ GU\S_]U E
Key=21
QT[[^ OaT^BcdSX^ FT[R^\T D
Key=22
PSZZ] N`S]AbcRW] ESZQ][S C
Key=23
ORYY\ M_R\ZabQV\ DRYP\ZR B
Key=24
NQXX[ L^Q[Y`aPU[ CQXO[YQ A
Key=25
MPWWZ K]PZX_`OTZ BPWNZXP Z

In general, we have more than 25 clear text character sets. For example, there are more than 3000 common Chinese characters. Then we need to explode more than 3000 keys. But after the explosion, how do we know which one is the Key we want? It's not realistic to see one by one.

The dictionary can be used to check the validity of words. Python can use enchant or nltk library to judge whether words are valid. We can also download an English word book ourselves( words.txt )Match one by one:

def is_english_word(word):
    with open("./files/words.txt") as word_file:
        english_words = set(word.strip().lower() for word in word_file)
 
    return word.lower() in english_words

is_english_word('hellX')
#Run result: False

 

  • Burst, get the best Key
import tools

#Burst Caesar's encrypted ciphertext
def caesar_cracking(msg,len):
    relKey =0
    relCount =0
    print('Cracking, waiting patiently...')
    for key in range(0, len):
        print(key)
        text = caesar_decode(msg, key)
        count =0
        for word in text.split(" "):
            #print('====='+word)
            if tools.is_english_word(word):
                count+=1
        if count > relCount:
            relCount = count
            relKey = key
            if relKey >=100:#If the accuracy reaches 100, the task is to get the key
                break
            
    print('Crack complete...')
    print('The best key is: key='+str(relKey))

    return relKey

   
caesar_cracking('Lipps JvisWxyhms Aipgsqi Y',26)
#The operation results are as follows:

 

2-reverse encryption programming practice

 

  • actual combat
# Reverse encryption#The encryption algorithm is consistent with the decryption algorithm
def reverse_cipher(msg):
    i = len(msg) - 1
    result = ''  # Store and reverse information
    while i >= 0:
        result += msg[i]
        i = i - 1
    print("Reverse to:", result)
    return result

message = 'This is program to explain reverse cipher.'


text = reverse_cipher(message)#Reverse encryption
reverse_cipher(text)#Reverse and reverse to get clear text
  • The key is that you don't know if someone else's ciphertext uses inversion

 

3-Practice of transposition encryption programming

 

Sort 1, 2, 3 and 4 columns by column number after row column conversion

  • actual combat
# transposition cipher 

from pycipher import ColTrans
#encryption
def transposition_encode(key, msg):
    return ColTrans(key).encipher(msg)
#decrypt
def transposition_decode(key, msg):
    return ColTrans(key).decipher(msg)

text = transposition_encode("21334","Hello FreoStudio Welcome U")
transposition_decode("HELLO",text)

#Pycipher coltrans transposition encryption specific algorithm source code
#We stand on the shoulders of giants, innovate and create, not build wheels again
https://github.com/freostudio/pycipher/tree/master/pycipher/columnartransposition.py
  • cryptanalysis

Transposition encryption is usually called column conversion encryption, which transposes the plaintext according to the number of custom columns. Encryption strength itself is very weak, but it is usually combined with other encryption methods, such as alternative encryption, ADFGVX password is to use transposition encryption to greatly enhance security.

How to crack it? It's basically impossible to try one by one by blasting, because the number of columns that are transposed first can be countless, and there are many columns that are sorted and combined. After getting the result, you have to check the correctness of the words. General computers are basically difficult to explode.

It's hard to crack one by one after the basic length is 9

One by one, we can use the dictionary attack method to solve the hopelessness. Usually, the encryption Key is used to encrypt people's names and places. Then we build a dictionary and try one by one to improve the efficiency.

 

4-multiplication encryption programming practice

 

  • actual combat
# Data multiplication encryption

def multiplicative_encode(key,totol_num, text):
    result = ''  # Store and reverse information
    for x in text:
        if(x == ' '):
            result += " "
        else:
            offset = ord(x) - ord('A')
            result +=chr(((key* offset ) % totol_num) + ord('A'))
    return result


multiplicative_encode(7,26,"ABCDEFG")
##Output results:
# Data multiplication encryption
'AHOVCJQ'

 

5 - Summary

We aim at the actual combat of classical encryption algorithm, which is to better master the idea of classical encryption algorithm.

Part I-
 1 - Caesar encryption programming practice
 2-reverse encryption programming practice
 3-transposition encryption programming practice
 4-multiplication encryption programming practice
 Part 2-
5-affine encryption
 6-simple alternative encryption
 7-virginia encryption multi table alternative encryption
 one time pad cipher

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Tags: Programming Python github pip

Posted on Thu, 11 Jun 2020 22:57:56 -0400 by Zaxnyd