An engineer who has noticed the emo of cryptography is trying to implement it in Python and defeat it

It is no exaggeration to say that the modern information society is supported by cryptographic technology. Nevertheless, we are benefiting from it without being particularly aware of cryptography. Moreover, cryptography has been around for a long time, about 100 BC. In addition, modern cryptography is trying to ensure high security by making full use of advanced mathematics, and eventually it will be derived from blockchain technology.

What is the length of this history and the breadth of defense! !!

So, I'm aware of the emo of cryptography, and I'm trying to implement and defeat cryptography in Python for knowledge maintenance and updates.

Basic concept of cryptography

Cryptography is largely made up of three elements: ** key generation **, ** encryption **, and ** decryption **.

In particular, keys are a very important factor in cryptography. Rather, I think that cryptography is a technology of how to generate this key. This is because this key is used for both encryption and decryption and is directly related to security.

Depending on how the key is handled, it can be classified into two types: ** common key cryptography ** and ** public key cryptography **.

Symmetric-key cryptography uses the same key in both the encryption and decryption processes. This was the mainstream for a while after the birth of cryptography, but it had the disadvantage of costly key management because the keys had to be exchanged only by the parties without being known to a third party.

In order to overcome the drawbacks of common key cryptography, public key cryptography creates two types of keys, a private key and a public key, and literally discloses the public key, which drastically reduces the cost of key management. You can do it. Public key cryptography is often used because it can be used by opening the public key, which is compatible with the exchange of information on the Internet. In the case of public key cryptography, the private key and the public key must have a correspondence relationship like a tally, and at the same time, the private key must not be inferred from the public key. Therefore, mathematics such as prime factorization of large numbers and discrete logarithm problems are used.

First from the classical cipher

Cryptography has changed since the first half of the 20th century. Until then, it was called classical cryptography, and cryptanalysis was mainly the job of linguists. This is because I used to make and decrypt the code while playing with the letters, such as shifting the alphabet by a few letters and using the correspondence table prepared in advance.

However, during World War II, the cryptographic war between Enigma developed by the German army and the cryptanalysis team led by British information scientist Turing became one of the triggers, and cryptography gradually became the work of mathematicians and informatics. It was becoming.

In addition, cryptography is a cat-and-mouse game of development and decipherment. In fact, the British troops who deciphered the Enigma hid the fact that they could decipher it for about 20 years. This is because if you announce that you have cracked it, you risk developing stronger ciphers.

This is just one way of looking at it, but because of this background, I think that cryptography can be understood relatively easily by learning from classical cryptography to modern cryptography. It is highly recommended to learn by tracing the genealogy of the development of cryptographic technology, because you can understand the differences such as which areas have been improved.

For example, Caesar cipher

The Caesar cipher is said to be the oldest cipher (?) In the world. As the name suggests, it is a code created by Julius Caesar, who was active around the 1st century BC. This is to convert the characters by shifting the characters by 3 characters when the characters are arranged in alphabetical order. If you implement the encryption part in Python, it will be as follows. ASCII code is used for the part that shifts the characters.

caesar-cipher.py


def enc(text):
    result = ""
    for i in range(len(text)):
        cha = text[i]
        if(cha.isupper()):
            result += chr((ord(cha) - 62) % 26 + 65)
        else:
            result += chr((ord(cha) - 94) % 26 + 97)
    return print(result)

When actually encrypted, it looks like this.

caesar-cipher.py


enc("Caesar")
#Ciphertext: Fdhvdu

When decrypting, the reverse of encryption can be done, so the implementation is as follows.

caesar-cipher.py


def dec(text):
    result = ""
    for i in range(len(text)):
        cha = text[i]
        if(cha.isupper()):
            result += chr((ord(cha) - 42) % 26 + 65)
        else:
            result += chr((ord(cha) - 74) % 26 + 97)
    return print(result)

When executed, it looks like this.

caesar-cipher.py


dec("Fdhvdu")
#Deciphered text: Caesar

Shift cipher

The key to Caesar cipher was to shift 3 characters. For example, if there is a spy and it is misaligned by 3 characters, that is the end of the volume. Therefore, a code was devised to change the third part, that is, the key part. That is what is called shift cryptography.

The encryption part is as follows. This time, the number of characters to shift is specified as an argument. You can create a function to generate the key, but I decided to specify it as an argument because it just returns the entered numerical value as it is.

shift-cipher.py


def enc(plaintext, rot):
    if(rot > 25):
        rot = rot % 26
    result = ""
    for i in range(len(plaintext)):
        cha = plaintext[i]
        if(cha.isupper()):
            result += chr((ord(cha) + rot - 65) % 26 + 65)
        else:
            result += chr((ord(cha) + rot - 97) % 26 + 97)
    return print(result)

Decryption is the reverse of encryption.

shift-cipher.py


def dec(encryptedtext, rot):
    if(rot > 25):
        rot = rot % 26
    result = ""
    for i in range(len(encryptedtext)):
        cha = encryptedtext[i]
        if(cha.isupper()):
            result += chr((ord(cha) - rot - 39) % 26 + 65)
        else:
            result += chr((ord(cha) - rot - 71) % 26 + 97)
    return print(result)

from now on

I'm planning to implement and defeat the classical ciphers of BC to the most advanced ciphers of today in Python, which also serves as maintenance and update of knowledge. When I tried it, I began to see the history of cryptography and the struggles of our predecessors, and it became unexpectedly fun.

For the time being, our immediate goal is to reach the zero-knowledge proof system and secret sharing that often appear in the blockchain area.

Recommended Posts

An engineer who has noticed the emo of cryptography is trying to implement it in Python and defeat it
It is easy to execute SQL with Python and output the result in Excel
An easy way to view the time taken in Python and a smarter way to improve it
How to know the internal structure of an object in Python
Convert the result of python optparse to dict and utilize it
[Python] The role of the asterisk in front of the variable. Divide the input value and assign it to a variable
[Python / Jupyter] Translate the comment of the program copied to the clipboard and insert it in a new cell
[Python] Sweet Is it sweet? About suites and expressions in the official documentation
Comparing the basic grammar of Python and Go in an easy-to-understand manner
Open an Excel file in Python and color the map of Japan
How to use is and == in Python
How to input a character string in Python and output it as it is or in the opposite direction.
An example of the answer to the reference question of the study session. In python.
How to save the feature point information of an image in a file and use it for matching
You will be an engineer in 100 days --Day 29 --Python --Basics of the Python language 5
You will be an engineer in 100 days --Day 33 --Python --Basics of the Python language 8
You will be an engineer in 100 days --Day 26 --Python --Basics of the Python language 3
Tips for those who are wondering how to use is and == in Python
python Binary search It is surprisingly easy to implement bisect.bisect_left and bisect.bisect_right from 0
In Python, change the behavior of the method depending on how it is called
You will be an engineer in 100 days --Day 32 --Python --Basics of the Python language 7
You will be an engineer in 100 days --Day 28 --Python --Basics of the Python language 4
The answer of "1/2" is different between python2 and 3
About the difference between "==" and "is" in python
The first step for those who are amateurs of statistics but want to implement machine learning models in Python
An introduction to cross-platform GUI software made with Python / Tkinter! (And many Try and Error)! (In the middle of writing)
The background of the characters in the text image is overexposed to make it easier to read.
The first step of machine learning ~ For those who want to implement with python ~
The result of making a map album of Italy honeymoon in Python and sharing it
What to do if the progress bar is not displayed in tqdm of python
I want to replace the variables in the python template file and mass-produce it in another file.
How to check in Python if one of the elements of a list is in another list
A story about trying to introduce Linter in the middle of a Python (Flask) project
How to get the number of digits in Python
To do the equivalent of Ruby's ObjectSpace._id2ref in Python
How to do "Lending and borrowing JS methods (the one who uses apply)" in Python
Recursively get the Excel list in a specific folder with python and write it to Excel.
[Super easy! ] How to display the contents of dictionaries and lists including Japanese in Python
Return the image data with Flask of Python and draw it to the canvas element of HTML
If you want to put an argument in the closure function and execute it later
[Python] The status of each prefecture of the new coronavirus is only published in PDF, but I tried to scrape it without downloading it.
Try to make it using GUI and PyQt in Python
How to swap elements in an array in Python, and how to reverse an array.
Comparison of how to use higher-order functions in Python 2 and 3
The process of making Python code object-oriented and improving it
I tried to implement the mail sending function in Python
Object-oriented in C: Refactored "○ ✕ game" and ported it to Python
[Tips] Problems and solutions in the development of python + kivy
A story about trying to implement a private variable in Python.
I tried to implement blackjack of card game in Python
Overview of Python virtual environment and how to create it
[Python] What is a slice? An easy-to-understand explanation of how to use it with a concrete example.
Write a script in Shell and Python to notify you in Slack when the process is finished
[Python] What is pip? Explain the command list and how to use it with actual examples
Scraping the list of Go To EAT member stores in Fukuoka prefecture and converting it to CSV
Process the gzip file UNLOADed with Redshift with Python of Lambda, gzip it again and upload it to S3
Find the white Christmas rate by prefecture with Python and map it to a map of Japan
It is surprisingly troublesome to get a list of the last login date and time of Workspaces
The story of returning to the front line for the first time in 5 years and refactoring Python Django
Scraping the list of Go To EAT member stores in Niigata prefecture and converting it to CSV
Memo to switch between python2 series and 3 series in anaconda environment of mac (win is also added)