引用文章 - Cryptography with Python - Quick Guide
https://www.tutorialspoint.com/cryptography_with_python/cryptography_with_python_quick_guide.htm
Cryptography with Python - Overview
Cryptography is the art of communication between two users via coded messages. The science of cryptography emerged with the basic motive of providing security to the confidential messages transferred from one party to another.
Cryptography is defined as the art and science of concealing the message to introduce privacy and secrecy as recognized in information security.
Terminologies of Cryptography
The frequently used terms in cryptography are explained here −
Plain Text
The plain text message is the text which is readable and can be understood by all users. The plain text is the message which undergoes cryptography.
Cipher Text
Cipher text is the message obtained after applying cryptography on plain text.
Encryption
The process of converting plain text to cipher text is called encryption. It is also called as encoding.
Decryption
The process of converting cipher text to plain text is called decryption. It is also termed as decoding.
The diagram given below shows an illustration of the complete process of cryptography −
Characteristics of Modern Cryptography
The basic characteristics of modern cryptography are as follows −
-
It operates on bit sequences.
-
It uses mathematical algorithms for securing the information.
-
It requires parties interested in secure communication channel to achieve privacy.
Double Strength Encryption
Double strength encryption, also called as multiple encryption, is the process of encrypting an already encrypted text one or more times, either with the same or different algorithm/pattern.
The other names for double strength encryption include cascade encryption or cascade ciphering.
Levels of Double Strength Encryption
Double strength encryption includes various levels of encryption that are explained here under −
First layer of encryption
The cipher text is generated from the original readable message using hash algorithms and symmetric keys. Later symmetric keys are encrypted with the help of asymmetric keys. The best illustration for this pattern is combining the hash digest of the cipher text into a capsule. The receiver will compute the digest first and later decrypt the text in order to verify that text is not tampered in between.
Second layer of encryption
Second layer of encryption is the process of adding one more layer to cipher text with same or different algorithm. Usually, a 32-bit character long symmetric password is used for the same.
Third layer of encryption
In this process, the encrypted capsule is transmitted via SSL/TLS connection to the communication partner.
The following diagram shows double encryption process pictorially −
Hybrid Cryptography
Hybrid cryptography is the process of using multiple ciphers of different types together by including benefits of each of the cipher. There is one common approach which is usually followed to generate a random secret key for a symmetric cipher and then encrypt this key via asymmetric key cryptography.
Due to this pattern, the original message itself is encrypted using the symmetric cipher and then using secret key. The receiver after receiving the message decrypts the message using secret key first, using his/her own private key and then uses the specified key to decrypt the message.
Python Overview and Installation
Python is an open source scripting language which is high-level, interpreted, interactive and object-oriented. It is designed to be highly readable. The syntax of Python language is easy to understand and uses English keywords frequently.
Features of Python Language
Python provides the following major features −
Interpreted
Python is processed at runtime using the interpreter. There is no need to compile a program before execution. It is similar to PERL and PHP.
Object-Oriented
Python follows object-oriented style and design patterns. It includes class definition with various features like encapsulation and polymorphism.
Key Points of Python Language
The key points of Python programming language are as follows −
-
It includes functional and structured programming and methods as well as object oriented programming methods.
-
It can be used as a scripting language or as a programming language.
-
It includes automatic garbage collection.
-
It includes high-level dynamic data types and supports various dynamic type checking.
-
Python includes a feature of integration with C, C++ and languages like Java.
The download link for Python language is as follows − www.python.org/downloadsIt includes packages for various operating systems like Windows, MacOS and Linux distributions.
Python Strings
The basic declaration of strings is shown below −
str = 'Hello World!'
Python Lists
The lists of python can be declared as compound data types, separated by commas and enclosed within square brackets ([]).
list = [ 'abcd', 786 , 2.23, 'john', 70.2 ] tinylist = [123, 'john']
Python Tuples
A tuple is dynamic data type of Python which consists of number of values separated by commas. Tuples are enclosed with parentheses.
tinytuple = (123, 'john')
Python Dictionary
Python dictionary is a type of hash table. A dictionary key can be almost any data type of Python, which are usually numbers or strings.
tinydict = {'name': 'omkar','code':6734, 'dept': 'sales'}
Cryptography Packages
Python includes a package called cryptography which provides cryptographic recipes and primitives. It supports Python 2.7, Python 3.4+, and PyPy 5.3+. The basic installation of cryptography package is achieved through following command −
pip install cryptography
There are various packages with both high level recipes and low level interfaces to common cryptographic algorithms such as symmetric ciphers, message digests and key derivation functions.
Throughout this tutorial, we will be using various packages of Python for implementation of cryptographic algorithms.
Cryptography with Python - Reverse Cipher
The previous chapter gave you an overview of installation of Python on your local computer. In this chapter you will learn in detail about reverse cipher and its coding.
Algorithm of Reverse Cipher
The algorithm of reverse cipher holds the following features −
-
Reverse Cipher uses a pattern of reversing the string of plain text to convert as cipher text.
-
The process of encryption and decryption is same.
-
To decrypt cipher text, the user simply needs to reverse the cipher text to get the plain text.
Drawback
The major drawback of reverse cipher is that it is very weak. A hacker can easily break the cipher text to get the original message. Hence, reverse cipher is not considered as good option to maintain secure communication channel,.
Example
Consider an example where the statement This is program to explain reverse cipher is to be implemented with reverse cipher algorithm. The following python code uses the algorithm to obtain the output.
message = 'This is program to explain reverse cipher.'
translated = '' #cipher text is stored in this variable
i = len(message) - 1
while i >= 0:
translated = translated + message[i]
i = i - 1
print(“The cipher text is : “, translated)
Output
You can see the reversed text, that is the output as shown in the following image −
Explanation
-
Plain text is stored in the variable message and the translated variable is used to store the cipher text created.
-
The length of plain text is calculated using for loop and with help of index number. The characters are stored in cipher text variable translated which is printed in the last line.
Cryptography with Python - Caesar Cipher
In the last chapter, we have dealt with reverse cipher. This chapter talks about Caesar cipher in detail.
Algorithm of Caesar Cipher
The algorithm of Caesar cipher holds the following features −
-
Caesar Cipher Technique is the simple and easy method of encryption technique.
-
It is simple type of substitution cipher.
-
Each letter of plain text is replaced by a letter with some fixed number of positions down with alphabet.
The following diagram depicts the working of Caesar cipher algorithm implementation −
The program implementation of Caesar cipher algorithm is as follows −
def encrypt(text,s):
result = ""
# transverse the plain text
for i in range(len(text)):
char = text[i]
# Encrypt uppercase characters in plain text
if (char.isupper()):
result += chr((ord(char) + s-65) % 26 + 65)
# Encrypt lowercase characters in plain text
else:
result += chr((ord(char) + s - 97) % 26 + 97)
return result
#check the above function
text = "CEASER CIPHER DEMO"
s = 4
print "Plain Text : " + text
print "Shift pattern : " + str(s)
print "Cipher: " + encrypt(text,s)
Output
You can see the Caesar cipher, that is the output as shown in the following image −
Explanation
The plain text character is traversed one at a time.
-
For each character in the given plain text, transform the given character as per the rule depending on the procedure of encryption and decryption of text.
-
After the steps is followed, a new string is generated which is referred as cipher text.
Hacking of Caesar Cipher Algorithm
The cipher text can be hacked with various possibilities. One of such possibility is Brute Force Technique, which involves trying every possible decryption key. This technique does not demand much effort and is relatively simple for a hacker.
The program implementation for hacking Caesar cipher algorithm is as follows −
message = 'GIEWIVrGMTLIVrHIQS' #encrypted message
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('Hacking key #%s: %s' % (key, translated))
Consider the cipher text encrypted in the previous example. Then, the output with possible hacking methods with the key and using brute force attack technique is as follows −
Cryptography with Python - ROT13 Algorithm
Till now, you have learnt about reverse cipher and Caesar cipher algorithms. Now, let us discuss the ROT13 algorithm and its implementation.
Explanation of ROT13 Algorithm
ROT13 cipher refers to the abbreviated form Rotate by 13 places. It is a special case of Caesar Cipher in which shift is always 13. Every letter is shifted by 13 places to encrypt or decrypt the message.
Example
The following diagram explains the ROT13 algorithm process pictorially −
Program Code
The program implementation of ROT13 algorithm is as follows −
from string import maketrans
rot13trans = maketrans('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz',
'NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm')
# Function to translate plain text
def rot13(text):
return text.translate(rot13trans)
def main():
txt = "ROT13 Algorithm"
print rot13(txt)
if __name__ == "__main__":
main()
You can see the ROT13 output as shown in the following image −
Drawback
The ROT13 algorithm uses 13 shifts. Therefore, it is very easy to shift the characters in the reverse manner to decrypt the cipher text.
Analysis of ROT13 Algorithm
ROT13 cipher algorithm is considered as special case of Caesar Cipher. It is not a very secure algorithm and can be broken easily with frequency analysis or by just trying possible 25 keys whereas ROT13 can be broken by shifting 13 places. Therefore, it does not include any practical use.
Transposition Cipher
Transposition Cipher is a cryptographic algorithm where the order of alphabets in the plaintext is rearranged to form a cipher text. In this process, the actual plain text alphabets are not included.
Example
A simple example for a transposition cipher is columnar transposition cipher where each character in the plain text is written horizontally with specified alphabet width. The cipher is written vertically, which creates an entirely different cipher text.
Consider the plain text hello world, and let us apply the simple columnar transposition technique as shown below
The plain text characters are placed horizontally and the cipher text is created with vertical format as : holewdlo lr. Now, the receiver has to use the same table to decrypt the cipher text to plain text.
Code
The following program code demonstrates the basic implementation of columnar transposition technique −
def split_len(seq, length):
return [seq[i:i + length] for i in range(0, len(seq), length)]
def encode(key, plaintext):
order = {
int(val): num for num, val in enumerate(key)
}
ciphertext = ''
for index in sorted(order.keys()):
for part in split_len(plaintext, len(key)):
try:ciphertext += part[order[index]]
except IndexError:
continue
return ciphertext
print(encode('3214', 'HELLO'))
Explanation
-
Using the function split_len(), we can split the plain text characters, which can be placed in columnar or row format.
-
encode method helps to create cipher text with key specifying the number of columns and prints the cipher text by reading characters through each column.
Output
The program code for the basic implementation of columnar transposition technique gives the following output −
Note − Cryptanalysts observed a significant improvement in crypto security when transposition technique is performed. They also noted that re-encrypting the cipher text using same transposition cipher creates better security.
Encryption of Transposition Cipher
In the previous chapter, we have learnt about Transposition Cipher. In this chapter, let us discuss its encryption.
Pyperclip
The main usage of pyperclip plugin in Python programming language is to perform cross platform module for copying and pasting text to the clipboard. You can install python pyperclip module using the command as shown
pip install pyperclip
If the requirement already exists in the system, you can see the following output −
Code
The python code for encrypting transposition cipher in which pyperclip is the main module is as shown below −
import pyperclip
def main():
myMessage = 'Transposition Cipher'
myKey = 10
ciphertext = encryptMessage(myKey, myMessage)
print("Cipher Text is")
print(ciphertext + '|')
pyperclip.copy(ciphertext)
def encryptMessage(key, message):
ciphertext = [''] * key
for col in range(key):
position = col
while position < len(message):
ciphertext[col] += message[position]
position += key
return ''.join(ciphertext) #Cipher text
if __name__ == '__main__':
main()
Output
The program code for encrypting transposition cipher in which pyperclip is the main module gives the following output −
Explanation
-
The function main() calls the encryptMessage() which includes the procedure for splitting the characters using len function and iterating them in a columnar format.
-
The main function is initialized at the end to get the appropriate output.
Decryption of Transposition Cipher
In this chapter, you will learn the procedure for decrypting the transposition cipher.
Code
Observe the following code for a better understanding of decrypting a transposition cipher. The cipher text for message Transposition Cipher with key as 6 is fetched as Toners raiCntisippoh.
import math, pyperclip
def main():
myMessage= 'Toners raiCntisippoh'
myKey = 6
plaintext = decryptMessage(myKey, myMessage)
print("The plain text is")
print('Transposition Cipher')
def decryptMessage(key, message):
numOfColumns = math.ceil(len(message) / key)
numOfRows = key
numOfShadedBoxes = (numOfColumns * numOfRows) - len(message)
plaintext = float('') * numOfColumns
col = 0
row = 0
for symbol in message:
plaintext[col] += symbol
col += 1
if (col == numOfColumns) or (col == numOfColumns - 1 and row >= numOfRows - numOfShadedBoxes):
col = 0 row += 1 return ''.join(plaintext)
if __name__ == '__main__':
main()
Explanation
The cipher text and the mentioned key are the two values taken as input parameters for decoding or decrypting the cipher text in reverse technique by placing characters in a column format and reading them in a horizontal manner.
You can place letters in a column format and later combined or concatenate them together using the following piece of code −
for symbol in message:
plaintext[col] += symbol
col += 1
if (col == numOfColumns) or (col == numOfColumns - 1 and row >= numOfRows - numOfShadedBoxes):
col = 0
row += 1
return ''.join(plaintext)
Output
The program code for decrypting transposition cipher gives the following output −
Encryption of files
In Python, it is possible to encrypt and decrypt files before transmitting to a communication channel. For this, you will have to use the plugin PyCrypto. You can installation this plugin using the command given below.
pip install pycrypto
Code
The program code for encrypting the file with password protector is mentioned below −
# =================Other Configuration================
# Usages :
usage = "usage: %prog [options] "
# Version
Version="%prog 0.0.1"
# ====================================================
# Import Modules
import optparse, sys,os
from toolkit import processor as ps
def main():
parser = optparse.OptionParser(usage = usage,version = Version)
parser.add_option(
'-i','--input',type = 'string',dest = 'inputfile',
help = "File Input Path For Encryption", default = None)
parser.add_option(
'-o','--output',type = "string",dest = 'outputfile',
help = "File Output Path For Saving Encrypter Cipher",default = ".")
parser.add_option(
'-p','--password',type = "string",dest = 'password',
help = "Provide Password For Encrypting File",default = None)
parser.add_option(
'-p','--password',type = "string",dest = 'password',
help = "Provide Password For Encrypting File",default = None)
(options, args)= parser.parse_args()
# Input Conditions Checkings
if not options.inputfile or not os.path.isfile(options.inputfile):
print " [Error] Please Specify Input File Path"
exit(0)
if not options.outputfile or not os.path.isdir(options.outputfile):
print " [Error] Please Specify Output Path"
exit(0)
if not options.password:
print