how to find the key for the hill cipher
Cryptography with Python - Quick Guide
Cryptography with Python - Overview
Cryptography is the art of communication between ii users via coded messages. The science of cryptography emerged with the basic motive of providing security to the confidential messages transferred from one political party to another.
Cryptography is defined as the art and scientific discipline of concealing the message to innovate privacy and secrecy as recognized in information security.
Terminologies of Cryptography
The frequently used terms in cryptography are explained hither −
Plain Text
The manifestly text bulletin is the text which is readable and tin be understood by all users. The plain text is the bulletin which undergoes cryptography.
Nada Text
Zilch text is the message obtained later applying cryptography on plain text.
Encryption
The procedure of converting plain text to cipher text is called encryption. It is also called as encoding.
Decryption
The process of converting null text to plain text is called decryption. Information technology is too termed as decoding.
The diagram given below shows an illustration of the consummate process of cryptography −
Characteristics of Modern Cryptography
The basic characteristics of modern cryptography are as follows −
-
It operates on chip sequences.
-
It uses mathematical algorithms for securing the information.
-
It requires parties interested in secure advice channel to accomplish privacy.
Double Force Encryption
Double strength encryption, likewise called as multiple encryption, is the process of encrypting an already encrypted text one or more times, either with the same or dissimilar algorithm/pattern.
The other names for double force encryption include cascade encryption or cascade ciphering.
Levels of Double Forcefulness Encryption
Double strength encryption includes various levels of encryption that are explained here nether −
Kickoff layer of encryption
The naught text is generated from the original readable bulletin using hash algorithms and symmetric keys. Later symmetric keys are encrypted with the help of asymmetric keys. The best analogy for this pattern is combining the hash digest of the cipher text into a sheathing. The receiver will compute the digest first and afterwards 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 nothing text with same or dissimilar algorithm. Ordinarily, a 32-bit character long symmetric password is used for the aforementioned.
Third layer of encryption
In this process, the encrypted sheathing 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 arroyo which is usually followed to generate a random undercover cardinal for a symmetric cipher and and so encrypt this key via asymmetric key cryptography.
Due to this design, the original message itself is encrypted using the symmetric cipher and then using surreptitious key. The receiver subsequently receiving the bulletin decrypts the message using hush-hush fundamental first, using his/her own private fundamental and so uses the specified key to decrypt the message.
Python Overview and Installation
Python is an open source scripting linguistic communication which is loftier-level, interpreted, interactive and object-oriented. Information technology is designed to be highly readable. The syntax of Python language is piece of cake to understand and uses English keywords oft.
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 earlier execution. It is like to PERL and PHP.
Object-Oriented
Python follows object-oriented style and design patterns. Information technology includes class definition with various features like encapsulation and polymorphism.
Key Points of Python Language
The fundamental points of Python programming language are as follows −
-
It includes functional and structured programming and methods every bit well as object oriented programming methods.
-
It tin 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 linguistic communication 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 = 'How-do-you-do World!'
Python Lists
The lists of python can be alleged equally compound data types, separated past commas and enclosed within square brackets ([]).
list = [ 'abcd', 786 , 2.23, 'john', seventy.2 ] tinylist = [123, 'john']
Python Tuples
A tuple is dynamic data type of Python which consists of number of values separated past commas. Tuples are enclosed with parentheses.
tinytuple = (123, 'john')
Python Dictionary
Python lexicon is a blazon of hash tabular array. A dictionary key can be almost whatever data type of Python, which are normally 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 bundle is achieved through post-obit command −
pip install cryptography
There are diverse packages with both high level recipes and depression level interfaces to common cryptographic algorithms such as symmetric ciphers, bulletin digests and key derivation functions.
Throughout this tutorial, we will exist using various packages of Python for implementation of cryptographic algorithms.
Cryptography with Python - Reverse Goose egg
The previous affiliate gave you lot an overview of installation of Python on your local estimator. In this chapter you volition learn in detail almost reverse cipher and its coding.
Algorithm of Contrary Zippo
The algorithm of reverse cipher holds the following features −
-
Reverse Cypher uses a pattern of reversing the string of plain text to catechumen equally cipher text.
-
The procedure of encryption and decryption is aforementioned.
-
To decrypt zippo text, the user simply needs to reverse the cipher text to get the plainly text.
Drawback
The major drawback of reverse cipher is that it is very weak. A hacker can easily pause the cipher text to become the original bulletin. Hence, reverse nada is not considered as expert pick to maintain secure communication aqueduct,.
Example
Consider an example where the statement This is program to explain opposite cipher is to be implemented with reverse goose egg algorithm. The post-obit python lawmaking uses the algorithm to obtain the output.
bulletin = 'This is program to explain opposite zippo.' translated = '' #cipher text is stored in this variable i = len(bulletin) - i while i >= 0: translated = translated + message[i] i = i - 1 print("The cipher text is : ", translated)
Output
You tin can run into the reversed text, that is the output as shown in the following image −
Caption
-
Plain text is stored in the variable bulletin and the translated variable is used to store the null text created.
-
The length of evidently text is calculated using for loop and with help of alphabetize number. The characters are stored in nada text variable translated which is printed in the last line.
Cryptography with Python - Caesar Cipher
In the terminal affiliate, we accept dealt with reverse cipher. This chapter talks virtually Caesar naught in item.
Algorithm of Caesar Zip
The algorithm of Caesar nix holds the following features −
-
Caesar Cipher Technique is the uncomplicated and easy method of encryption technique.
-
It is simple type of substitution cypher.
-
Each letter of the alphabet of evidently text is replaced by a alphabetic character with some stock-still 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 equally follows −
def encrypt(text,south): result = "" # transverse the plain text for i in range(len(text)): char = text[i] # Encrypt majuscule characters in plain text if (char.isupper()): upshot += chr((ord(char) + s-65) % 26 + 65) # Encrypt lowercase characters in plain text else: result += chr((ord(char) + south - 97) % 26 + 97) return outcome #check the above function text = "CEASER CIPHER DEMO" s = 4 print "Apparently Text : " + text print "Shift pattern : " + str(s) print "Cipher: " + encrypt(text,s)
Output
You can see the Caesar nil, that is the output as shown in the following paradigm −
Explanation
The patently text character is traversed one at a time.
-
For each character in the given plain text, transform the given character equally per the rule depending on the procedure of encryption and decryption of text.
-
Afterward the steps is followed, a new string is generated which is referred as cipher text.
Hacking of Caesar Nil Algorithm
The cipher text tin can be hacked with various possibilities. One of such possibility is Fauna Forcefulness Technique, which involves trying every possible decryption key. This technique does not demand much try and is relatively simple for a hacker.
The program implementation for hacking Caesar nil algorithm is as follows −
message = 'GIEWIVrGMTLIVrHIQS' #encrypted bulletin Messages = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' for key in range(len(Messages)): translated = '' for symbol in message: if symbol in LETTERS: num = Letters.discover(symbol) num = num - key if num < 0: num = num + len(Letters) translated = translated + LETTERS[num] else: translated = translated + symbol impress('Hacking cardinal #%s: %southward' % (central, translated))
Consider the goose egg text encrypted in the previous example. So, the output with possible hacking methods with the primal and using animal force attack technique is as follows −
Cryptography with Python - ROT13 Algorithm
Till now, you have learnt about reverse cipher and Caesar goose egg algorithms. Now, permit usa discuss the ROT13 algorithm and its implementation.
Explanation of ROT13 Algorithm
ROT13 cipher refers to the abbreviated form Rotate by 13 places. Information technology is a special case of Caesar Nothing in which shift is e'er 13. Every alphabetic character is shifted past 13 places to encrypt or decrypt the message.
Example
The post-obit diagram explains the ROT13 algorithm process pictorially −
Programme Lawmaking
The plan implementation of ROT13 algorithm is equally follows −
from string import maketrans rot13trans = maketrans('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz', 'NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm') # Part to translate evidently text def rot13(text): return text.translate(rot13trans) def master(): txt = "ROT13 Algorithm" print rot13(txt) if __name__ == "__main__": master()
You can come across the ROT13 output every bit shown in the following image −
Drawback
The ROT13 algorithm uses 13 shifts. Therefore, it is very piece of cake to shift the characters in the reverse manner to decrypt the zilch text.
Analysis of ROT13 Algorithm
ROT13 cipher algorithm is considered equally special instance of Caesar Nada. Information technology is non a very secure algorithm and can be cleaved easily with frequency analysis or by but trying possible 25 keys whereas ROT13 can exist broken by shifting 13 places. Therefore, it does non include any practical apply.
Transposition Nil
Transposition Aught is a cryptographic algorithm where the society of alphabets in the plaintext is rearranged to form a zilch text. In this process, the actual plain text alphabets are not included.
Example
A simple instance for a transposition cipher is columnar transposition cypher where each character in the plainly text is written horizontally with specified alphabet width. The cipher is written vertically, which creates an entirely unlike naught text.
Consider the evidently 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 tabular array to decrypt the goose egg text to patently text.
Code
The following program lawmaking 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(fundamental, plaintext): order = { int(val): num for num, val in enumerate(key) } ciphertext = '' for index in sorted(guild.keys()): for office in split_len(plaintext, len(key)): attempt:ciphertext += role[club[index]] except IndexError: continue return ciphertext print(encode('3214', 'HELLO'))
Caption
-
Using the function split_len(), we can split the evidently text characters, which tin 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 plan code for the basic implementation of columnar transposition technique gives the post-obit output −
Notation − 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 improve security.
Encryption of Transposition Cipher
In the previous chapter, we take 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 cantankerous platform module for copying and pasting text to the clipboard. You can install python pyperclip module using the command every bit shown
pip install pyperclip
If the requirement already exists in the system, you can see the following output −
Code
The python lawmaking for encrypting transposition zilch in which pyperclip is the main module is every bit shown below −
import pyperclip def principal(): myMessage = 'Transposition Goose egg' myKey = x ciphertext = encryptMessage(myKey, myMessage) print("Cipher Text is") print(ciphertext + '|') pyperclip.copy(ciphertext) def encryptMessage(central, message): ciphertext = [''] * central for col in range(primal): position = col while position < len(bulletin): ciphertext[col] += message[position] position += key render ''.join(ciphertext) #Cipher text if __name__ == '__main__': primary()
Output
The program lawmaking 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 role and iterating them in a columnar format.
-
The main part is initialized at the end to get the advisable output.
Decryption of Transposition Zilch
In this chapter, you will learn the procedure for decrypting the transposition cipher.
Lawmaking
Notice the post-obit code for a better understanding of decrypting a transposition cipher. The cipher text for bulletin Transposition Zilch with key every bit half-dozen is fetched every bit Toners raiCntisippoh.
import math, pyperclip def primary(): myMessage= 'Toners raiCntisippoh' myKey = vi plaintext = decryptMessage(myKey, myMessage) impress("The plain text is") print('Transposition Cipher') def decryptMessage(key, message): numOfColumns = math.ceil(len(bulletin) / primal) 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 += ane return ''.bring together(plaintext) if __name__ == '__main__': main()
Explanation
The cipher text and the mentioned cardinal are the two values taken as input parameters for decoding or decrypting the cipher text in contrary technique past placing characters in a column format and reading them in a horizontal mode.
You tin can place letters in a cavalcade format and later combined or concatenate them together using the following piece of code −
for symbol in message: plaintext[col] += symbol col += i if (col == numOfColumns) or (col == numOfColumns - 1 and row >= numOfRows - numOfShadedBoxes): col = 0 row += 1 render ''.join(plaintext)
Output
The programme 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 advice channel. For this, yous will have to utilize the plugin PyCrypto. Yous tin can installation this plugin using the control given beneath.
pip install pycrypto
Code
The plan code for encrypting the file with countersign protector is mentioned beneath −
# =================Other Configuration================ # Usages : usage = "usage: %prog [options] " # Version Version="%prog 0.0.ane" # ==================================================== # Import Modules import optparse, sys,os from toolkit import processor equally 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 = "cord",dest = 'outputfile', assistance = "File Output Path For Saving Encrypter Cipher",default = ".") parser.add_option( '-p','--password',type = "string",dest = 'countersign', help = "Provide Password For Encrypting File",default = None) parser.add_option( '-p','--password',blazon = "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): impress " [Fault] Please Specify Output Path" exit(0) if not options.password: print " [Mistake] No Password Input" leave(0) inputfile = options.inputfile outputfile = os.path.join( options.outputfile,os.path.basename(options.inputfile).split('.')[0]+'.ssb') password = options.password base of operations = os.path.basename(inputfile).split('.')[1] work = "E" ps.FileCipher(inputfile,outputfile,countersign,work) render if __name__ == '__main__': primary()
You lot can apply the post-obit command to execute the encryption process along with password −
python pyfilecipher-encrypt.py -i file_path_for_encryption -o output_path -p password
Output
You tin discover the post-obit output when you execute the code given in a higher place −
Explanation
The passwords are generated using MD5 hash algorithm and the values are stored in simply prophylactic backup files in Windows organisation, which includes the values as displayed below −
Decryption of files
In this chapter, allow united states of america discuss decryption of files in cryptography using Python. Note that for decryption process, we will follow the same procedure, but instead of specifying the output path, we will focus on input path or the necessary file which is encrypted.
Code
The post-obit is a sample code for decrypting files in cryptography using Python −
#!/usr/bin/python # ---------------- READ ME --------------------------------------------- # This Script is Created Only For Practise And Educational Purpose Only # This Script Is Created For http://bitforestinfo.blogspot.in # This Script is Written By # # ################################################## ######## Please Don't Remove Author Name ######### ############### Thanks ########################### ################################################## # # # =================Other Configuration================ # Usages : usage = "usage: %prog [options] " # Version Version="%prog 0.0.1" # ==================================================== # Import Modules import optparse, sys,os from toolkit import processor every bit ps def chief(): parser = optparse.OptionParser(usage = usage,version = Version) parser.add_option( '-i','--input',blazon = 'string',dest = 'inputfile', aid = "File Input Path For Encryption", default = None) parser.add_option( '-o','--output',type = "string",dest = 'outputfile', help = "File Output Path For Saving Encrypter Aught",default = ".") parser.add_option( '-p','--password',type = "string",dest = 'password', assist = "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] Delight Specify Input File Path" exit(0) if not options.outputfile or not bone.path.isdir(options.outputfile): print " [Error] Please Specify Output Path" exit(0) if not options.password: print " [Error] No exit(0) inputfile = options.inputfile outputfile = options.outputfile password = options.password work = "D" ps.FileCipher(inputfile,outputfile,password,work) render if __name__ == '__main__': main()
You tin employ the following control for executing the above code −
python pyfilecipher-decrypt.py -i encrypted_file_path -p password
Output
You can observe the following code when you execute the command shown above −
Note − The output specifies the hash values before encryption and later decryption, which keeps a annotation that the same file is encrypted and the process was successful.
Base64 Encoding and Decoding
Base64 encoding converts the binary data into text format, which is passed through communication channel where a user can handle text safely. Base64 is besides called equally Privacy enhanced Email (PEM) and is primarily used in email encryption process.
Python includes a module called BASE64 which includes two primary functions as given below −
-
base64.decode(input, output) − It decodes the input value parameter specified and stores the decoded output as an object.
-
Base64.encode(input, output) − It encodes the input value parameter specified and stores the decoded output as an object.
Program for Encoding
Y'all can use the post-obit piece of code to perform base64 encoding −
import base64 encoded_data = base64.b64encode("Encode this text") impress("Encoded text with base of operations 64 is") print(encoded_data)
Output
The lawmaking for base64 encoding gives you the following output −
Programme for Decoding
Yous can use the following piece of lawmaking to perform base64 decoding −
import base64 decoded_data = base64.b64decode("RW5jb2RlIHRoaXMgdGV4dA==") print("decoded text is ") print(decoded_data)
Output
The code for base64 decoding gives you the following output −
Deviation between ASCII and base64
You tin can notice the following differences when you work on ASCII and base64 for encoding data −
-
When yous encode text in ASCII, you kickoff with a text string and catechumen information technology to a sequence of bytes.
-
When you encode data in Base64, you start with a sequence of bytes and convert information technology to a text string.
Drawback
Base64 algorithm is usually used to shop passwords in database. The major drawback is that each decoded discussion can be encoded easily through any online tool and intruders tin can easily become the information.
Cryptography with Python - XOR Procedure
In this chapter, let the states empathise the XOR process along with its coding in Python.
Algorithm
XOR algorithm of encryption and decryption converts the apparently text in the format ASCII bytes and uses XOR procedure to catechumen it to a specified byte. It offers the following advantages to its users −
- Fast ciphering
- No difference marked in left and right side
- Like shooting fish in a barrel to understand and clarify
Code
You can use the following piece of lawmaking to perform XOR process −
def xor_crypt_string(data, key = 'awesomepassword', encode = False, decode = False): from itertools import izip, bike import base64 if decode: data = base64.decodestring(data) xored = ''.bring together(chr(ord(10) ^ ord(y)) for (x,y) in izip(data, wheel(central))) if encode: render base64.encodestring(xored).strip() return xored secret_data = "XOR process" impress("The cipher text is") print xor_crypt_string(secret_data, encode = Truthful) print("The plain text fetched") print xor_crypt_string(xor_crypt_string(secret_data, encode = True), decode = True)
Output
The code for XOR procedure gives you the following output −
Explanation
-
The part xor_crypt_string() includes a parameter to specify style of encode and decode and also the cord value.
-
The basic functions are taken with base64 modules which follows the XOR procedure/ operation to encrypt or decrypt the manifestly text/ cipher text.
Note − XOR encryption is used to encrypt data and is hard to scissure by animal-force method, that is past generating random encrypting keys to match with the correct cipher text.
Multiplicative Cipher
While using Caesar aught technique, encrypting and decrypting symbols involves converting the values into numbers with a simple basic process of addition or subtraction.
If multiplication is used to convert to cipher text, it is called a wrap-around situation. Consider the letters and the associated numbers to be used as shown below −
The numbers will be used for multiplication procedure and the associated key is 7. The basic formula to be used in such a scenario to generate a multiplicative cipher is every bit follows −
(Alphabet Number * key)modern(total number of alphabets)
The number fetched through output is mapped in the tabular array mentioned above and the corresponding alphabetic character is taken equally the encrypted letter.
The basic modulation function of a multiplicative aught in Python is as follows −
def unshift(key, ch): commencement = ord(ch) - ASC_A return chr(((key[0] * (offset + key[1])) % WIDTH) + ASC_A)
Note − The advantage with a multiplicative cipher is that it can piece of work with very large keys like 8,953,851. It would take quite a long time for a computer to animal-force through a majority of nine million keys.
Cryptography with Python - Affine Cipher
Affine Cipher is the combination of Multiplicative Nix and Caesar Zero algorithm. The basic implementation of affine cipher is as shown in the prototype below −
In this chapter, we will implement affine null by creating its corresponding grade that includes two basic functions for encryption and decryption.
Code
You tin employ the following lawmaking to implement an affine cypher −
class Affine(object): Die = 128 Cardinal = (seven, 3, 55) def __init__(self): laissez passer def encryptChar(self, char): K1, K2, kI = self.KEY render chr((K1 * ord(char) + K2) % self.DIE) def encrypt(cocky, string): render "".join(map(self.encryptChar, string)) def decryptChar(self, char): K1, K2, KI = self.Primal return chr(KI * (ord(char) - K2) % self.Dice) def decrypt(self, string): render "".join(map(self.decryptChar, string)) affine = Affine() print affine.encrypt('Affine Naught') print affine.decrypt('*18?FMT')
Output
You can discover the following output when yous implement an affine cipher −
The output displays the encrypted message for the plain text bulletin Affine Aught and decrypted message for the message sent as input abcdefg.
Hacking Monoalphabetic Null
In this affiliate, you lot volition larn about monoalphabetic cipher and its hacking using Python.
Monoalphabetic Nada
A Monoalphabetic cipher uses a fixed substitution for encrypting the unabridged bulletin. A monoalphabetic zilch using a Python lexicon with JSON objects is shown here −
monoalpha_cipher = { 'a': 'm', 'b': 'n', 'c': 'b', 'd': 'five', 'e': 'c', 'f': 'x', 'm': 'z', 'h': 'a', 'i': 's', 'j': 'd', 'k': 'f', 'l': 'g', 'yard': 'h', 'northward': 'j', 'o': '1000', 'p': 'l', 'q': 'p', 'r': 'o', 's': 'i', 't': 'u', 'u': 'y', 'v': 't', 'w': 'r', 'ten': 'e', 'y': 'w', 'z': 'q', ' ': ' ', }
With help of this dictionary, we tin encrypt the letters with the associated letters as values in JSON object. The following programme creates a monoalphabetic program as a grade representation which includes all the functions of encryption and decryption.
from string import messages, digits from random import shuffle def random_monoalpha_cipher(pool = None): if pool is None: pool = messages + digits original_pool = list(pool) shuffled_pool = list(pool) shuffle(shuffled_pool) return dict(zip(original_pool, shuffled_pool)) def inverse_monoalpha_cipher(monoalpha_cipher): inverse_monoalpha = {} for key, value in monoalpha_cipher.iteritems(): inverse_monoalpha[value] = key return inverse_monoalpha def encrypt_with_monoalpha(bulletin, monoalpha_cipher): encrypted_message = [] for letter in message: encrypted_message.append(monoalpha_cipher.become(alphabetic character, letter)) return ''.join(encrypted_message) def decrypt_with_monoalpha(encrypted_message, monoalpha_cipher): return encrypt_with_monoalpha( encrypted_message, inverse_monoalpha_cipher(monoalpha_cipher) )
This file is called later to implement the encryption and decryption procedure of Monoalphabetic cipher which is mentioned as beneath −
import monoalphabeticCipher every bit mc cipher = mc.random_monoalpha_cipher() print(cipher) encrypted = mc.encrypt_with_monoalpha('Hello all you hackers out there!', cipher) decrypted = mc.decrypt_with_monoalpha('sXGGt SGG Nt0 HSrLXFC t0U UHXFX!', cipher) impress(encrypted) print(decrypted)
Output
You lot can observe the following output when you implement the code given higher up −
Thus, y'all tin hack a monoalphabetic cipher with specified fundamental value pair which cracks the nada text to bodily plain text.
Simple Commutation Naught
Simple substitution cipher is the virtually commonly used cipher and includes an algorithm of substituting every plain text character for every zilch text character. In this process, alphabets are jumbled in comparison with Caesar zilch algorithm.
Case
Keys for a simple substitution cipher ordinarily consists of 26 letters. An example key is −
plain alphabet : abcdefghijklmnopqrstuvwxyz cypher alphabet: phqgiumeaylnofdxjkrcvstzwb
An instance encryption using the above primal is−
plaintext : defend the east wall of the castle ciphertext: giuifg cei iprc tpnn du cei qprcni
The following lawmaking shows a program to implement simple commutation goose egg −
import random, sys LETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' def main(): message = '' if len(sys.argv) > ane: with open up(sys.argv[ane], 'r') equally f: message = f.read() else: bulletin = raw_input("Enter your message: ") mode = raw_input("E for Encrypt, D for Decrypt: ") primal = '' while checkKey(key) is False: key = raw_input("Enter 26 Alpha key (leave blank for random central): ") if key == '': key = getRandomKey() if checkKey(key) is False: print('There is an mistake in the key or symbol fix.') translated = translateMessage(message, central, mode) print('Using primal: %due south' % (key)) if len(sys.argv) > 1: fileOut = 'enc.' + sys.argv[1] with open(fileOut, 'due west') equally f: f.write(translated) impress('Success! File written to: %s' % (fileOut)) else: print('Result: ' + translated) # Shop the cardinal into listing, sort it, convert back, compare to alphabet. def checkKey(key): keyString = ''.bring together(sorted(list(central))) return keyString == LETTERS def translateMessage(message, primal, style): translated = '' charsA = Messages charsB = central # If decrypt mode is detected, swap A and B if mode == 'D': charsA, charsB = charsB, charsA for symbol in message: if symbol.upper() in charsA: symIndex = charsA.find(symbol.upper()) if symbol.isupper(): translated += charsB[symIndex].upper() else: translated += charsB[symIndex].lower() else: translated += symbol return translated def getRandomKey(): randomList = list(Letters) random.shuffle(randomList) return ''.join(randomList) if __name__ == '__main__': master()
Output
You lot tin notice the following output when you implement the code given above −
Testing of Simple Substitution Zilch
In this chapter, we will focus on testing substitution cipher using various methods, which helps to generate random strings every bit given below −
import random, string, substitution def main(): for i in range(m): key = exchange.getRandomKey() message = random_string() impress('Test %s: String: "%due south.."' % (i + one, bulletin[:50])) print("Key: " + primal) encrypted = substitution.translateMessage(message, key, 'E') decrypted = substitution.translateMessage(encrypted, key, 'D') if decrypted != message: print('Fault: Decrypted: "%due south" Key: %due south' % (decrypted, key)) sys.leave() print('Substutition test passed!') def random_string(size = 5000, chars = string.ascii_letters + string.digits): render ''.join(random.option(chars) for _ in range(size)) if __name__ == '__main__': master()
Output
Y'all can observe the output equally randomly generated strings which helps in generating random patently text letters, every bit shown beneath −
After the examination is successfully completed, nosotros tin can observe the output message Commutation test passed!.
Thus, you can hack a substitution zero in the systematic fashion.
Decryption of Uncomplicated Exchange Cipher
In this affiliate, you can learn about simple implementation of substitution cipher which displays the encrypted and decrypted bulletin as per the logic used in simple exchange cipher technique. This tin be considered as an culling approach of coding.
Lawmaking
You can utilise the following code to perform decryption using elementary commutation nada −
import random chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' + \ 'abcdefghijklmnopqrstuvwxyz' + \ '0123456789' + \ ':.;,?!@#$%&()+=-*/_<> []{}`~^"\'\\' def generate_key(): """Generate an key for our aught""" shuffled = sorted(chars, central=lambda chiliad: random.random()) return dict(cipher(chars, shuffled)) def encrypt(key, plaintext): """Encrypt the string and return the ciphertext""" return ''.join(key[l] for l in plaintext) def decrypt(key, ciphertext): """Decrypt the string and return the plaintext""" flipped = {v: k for k, v in key.items()} return ''.join(flipped[l] for l in ciphertext) def show_result(plaintext): """Generate a resulting cipher with elements shown""" cardinal = generate_key() encrypted = encrypt(key, plaintext) decrypted = decrypt(key, encrypted) print 'Central: %s' % key impress 'Plaintext: %s' % plaintext print 'Encrypted: %s' % encrypted impress 'Decrypted: %s' % decrypted show_result('Hello World. This is demo of substitution goose egg')
Output
The higher up code gives you lot the output as shown here −
Python Modules of Cryptography
In this chapter, you will learn in detail nearly various modules of cryptography in Python.
Cryptography Module
It includes all the recipes and primitives, and provides a high level interface of coding in Python. You can install cryptography module using the following command −
pip install cryptography
Code
You can use the post-obit lawmaking to implement the cryptography module −
from cryptography.fernet import Fernet key = Fernet.generate_key() cipher_suite = Fernet(central) cipher_text = cipher_suite.encrypt("This example is used to demonstrate cryptography module") plain_text = cipher_suite.decrypt(cipher_text)
Output
The code given above produces the following output −
The code given hither is used to verify the countersign and creating its hash. It besides includes logic for verifying the countersign for hallmark purpose.
import uuid import hashlib def hash_password(password): # uuid is used to generate a random number of the specified password salt = uuid.uuid4().hex return hashlib.sha256(salt.encode() + password.encode()).hexdigest() + ':' + common salt def check_password(hashed_password, user_password): password, salt = hashed_password.split(':') return password == hashlib.sha256(table salt.encode() + user_password.encode()).hexdigest() new_pass = input('Delight enter a password: ') hashed_password = hash_password(new_pass) print('The string to store in the db is: ' + hashed_password) old_pass = input('Now please enter the countersign over again to bank check: ') if check_password(hashed_password, old_pass): impress('You entered the correct password') else: print('Passwords do not match')
Output
Scenario i − If you have entered a correct password, you tin find the following output −
Scenario ii − If we enter wrong countersign, yous can discover the post-obit output −
Caption
Hashlib package is used for storing passwords in a database. In this program, table salt is used which adds a random sequence to the password string before implementing the hash function.
Understanding Vignere Cipher
Vignere Zero includes a twist with Caesar Zip algorithm used for encryption and decryption. Vignere Cipher works similar to Caesar Aught algorithm with only i major stardom: Caesar Goose egg includes algorithm for ane-graphic symbol shift, whereas Vignere Cipher includes key with multiple alphabets shift.
Mathematical Equation
For encryption the mathematical equation is as follows −
$$E_{grand}\left ( M{_{i{}}} \correct ) = \left ( M_{i}+K_{i} \right )\;\;\; mod \;\; 26$$
For decryption the mathematical equation is as follows −
$$D_{k}\left ( C{_{i{}}} \correct ) = \left ( C_{i}-K_{i} \correct )\;\;\; mod \;\; 26$$
Vignere cipher uses more ane set of substitutions, and hence it is also referred every bit polyalphabetic cipher. Vignere Cipher will use a letter of the alphabet fundamental instead of a numeric key representation: Letter A will be used for fundamental 0, letter B for cardinal 1 and so on. Numbers of the messages before and later encryption process is shown below −
The possible combination of number of possible keys based on Vignere key length is given equally follows, which gives the result of how secure is Vignere Cypher Algorithm −
Vignere Tableau
The tableau used for Vignere zilch is equally shown below −
Implementing Vignere Cipher
In this chapter, permit u.s. empathize how to implement Vignere zilch. Consider the text This is bones implementation of Vignere Null is to exist encoded and the central used is PIZZA.
Code
You lot tin can utilise the post-obit code to implement a Vignere cipher in Python −
import pyperclip Messages = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' def main(): myMessage = "This is basic implementation of Vignere Cipher" myKey = 'PIZZA' myMode = 'encrypt' if myMode == 'encrypt': translated = encryptMessage(myKey, myMessage) elif myMode == 'decrypt': translated = decryptMessage(myKey, myMessage) impress('%sed message:' % (myMode.championship())) print(translated) impress() def encryptMessage(cardinal, message): render translateMessage(key, message, 'encrypt') def decryptMessage(primal, bulletin): return translateMessage(central, bulletin, 'decrypt') def translateMessage(key, message, mode): translated = [] # stores the encrypted/decrypted message cord keyIndex = 0 fundamental = key.upper() for symbol in message: num = Messages.observe(symbol.upper()) if num != -i: if mode == 'encrypt': num += LETTERS.observe(key[keyIndex]) elif mode == 'decrypt': num -= Letters.detect(key[keyIndex]) num %= len(Messages) if symbol.isupper(): translated.suspend(Letters[num]) elif symbol.islower(): translated.suspend(LETTERS[num].lower()) keyIndex += 1 if keyIndex == len(key): keyIndex = 0 else: translated.append(symbol) return ''.join(translated) if __name__ == '__main__': main()
Output
You can observe the following output when you implement the code given above −
The possible combinations of hacking the Vignere cipher is next to incommunicable. Hence, information technology is considered equally a secure encryption fashion.
Once Pad Zilch
Sometime pad cipher is a type of Vignere aught which includes the following features −
-
It is an unbreakable aught.
-
The key is exactly same as the length of message which is encrypted.
-
The key is fabricated up of random symbols.
-
As the name suggests, key is used i fourth dimension simply and never used again for whatsoever other message to exist encrypted.
Due to this, encrypted bulletin will exist vulnerable to attack for a cryptanalyst. The key used for a one-time pad cipher is called pad, as information technology is printed on pads of newspaper.
Why is information technology Unbreakable?
The key is unbreakable attributable to the post-obit features −
-
The central is as long equally the given bulletin.
-
The key is truly random and particularly automobile-generated.
-
Fundamental and plain text calculated as modulo ten/26/2.
-
Each key should exist used in one case and destroyed past both sender and receiver.
-
At that place should exist two copies of fundamental: i with the sender and other with the receiver.
Encryption
To encrypt a alphabetic character, a user needs to write a key underneath the plaintext. The plaintext alphabetic character is placed on the pinnacle and the key alphabetic character on the left. The cross section achieved between ii letters is the plain text. It is described in the case below −
Decryption
To decrypt a letter of the alphabet, user takes the primal letter on the left and finds nix text letter of the alphabet in that row. The plain text letter is placed at the top of the cavalcade where the user can find the cipher text letter.
Implementation of Once Pad Nix
Python includes a hacky implementation module for one-time-pad cipher implementation. The parcel proper name is called Ane-Time-Pad which includes a command line encryption tool that uses encryption machinery similar to the old pad cipher algorithm.
Installation
You tin use the following control to install this module −
pip install onetimepad
If you wish to use it from the control-line, run the following control −
onetimepad
Code
The following code helps to generate a 1-time pad cipher −
import onetimepad cipher = onetimepad.encrypt('In one case Cipher', 'random') print("Cipher text is ") print(zippo) print("Plain text is ") msg = onetimepad.decrypt(cipher, 'random') print(msg)
Output
Y'all can observe the following output when you run the lawmaking given to a higher place −
Note − The encrypted message is very easy to crack if the length of the key is less than the length of message (plain text).
In any instance, the primal is not necessarily random, which makes one-time pad cipher every bit a worth tool.
Symmetric and Asymmetric Cryptography
In this chapter, let us talk over in detail nearly symmetric and asymmetric cryptography.
Symmetric Cryptography
In this type, the encryption and decryption process uses the same cardinal. It is besides called as secret key cryptography. The master features of symmetric cryptography are as follows −
- Information technology is simpler and faster.
- The two parties exchange the key in a secure fashion.
Drawback
The major drawback of symmetric cryptography is that if the key is leaked to the intruder, the bulletin can be easily changed and this is considered as a risk factor.
Data Encryption Standard (DES)
The most popular symmetric key algorithm is Data Encryption Standard (DES) and Python includes a package which includes the logic behind DES algorithm.
Installation
The command for installation of DES package pyDES in Python is −
pip install pyDES
Simple plan implementation of DES algorithm is as follows −
import pyDes information = "DES Algorithm Implementation" k = pyDes.des("DESCRYPT", pyDes.CBC, "\0\0\0\0\0\0\0\0", pad=None, padmode=pyDes.PAD_PKCS5) d = k.encrypt(data) print "Encrypted: %r" % d print "Decrypted: %r" % k.decrypt(d) affirm k.decrypt(d) == data
It calls for the variable padmode which fetches all the packages as per DES algorithm implementation and follows encryption and decryption in a specified mode.
Output
Y'all can meet the post-obit output as a issue of the code given to a higher place −
Asymmetric Cryptography
It is also called as public fundamental cryptography. It works in the contrary mode of symmetric cryptography. This implies that it requires two keys: one for encryption and other for decryption. The public key is used for encrypting and the private key is used for decrypting.
Drawback
- Due to its cardinal length, information technology contributes lower encryption speed.
- Key management is crucial.
The following program lawmaking in Python illustrates the working of asymmetric cryptography using RSA algorithm and its implementation −
from Crypto import Random from Crypto.PublicKey import RSA import base64 def generate_keys(): # cardinal length must be a multiple of 256 and >= 1024 modulus_length = 256*four privatekey = RSA.generate(modulus_length, Random.new().read) publickey = privatekey.publickey() return privatekey, publickey def encrypt_message(a_message , publickey): encrypted_msg = publickey.encrypt(a_message, 32)[0] encoded_encrypted_msg = base64.b64encode(encrypted_msg) return encoded_encrypted_msg def decrypt_message(encoded_encrypted_msg, privatekey): decoded_encrypted_msg = base64.b64decode(encoded_encrypted_msg) decoded_decrypted_msg = privatekey.decrypt(decoded_encrypted_msg) render decoded_decrypted_msg a_message = "This is the illustration of RSA algorithm of disproportionate cryptography" privatekey , publickey = generate_keys() encrypted_msg = encrypt_message(a_message , publickey) decrypted_msg = decrypt_message(encrypted_msg, privatekey) print "%s - (%d)" % (privatekey.exportKey() , len(privatekey.exportKey())) impress "%s - (%d)" % (publickey.exportKey() , len(publickey.exportKey())) impress " Original content: %s - (%d)" % (a_message, len(a_message)) print "Encrypted message: %s - (%d)" % (encrypted_msg, len(encrypted_msg)) print "Decrypted message: %s - (%d)" % (decrypted_msg, len(decrypted_msg))
Output
You tin find the following output when you execute the lawmaking given above −
Understanding RSA Algorithm
RSA algorithm is a public primal encryption technique and is considered every bit the nearly secure mode of encryption. Information technology was invented by Rivest, Shamir and Adleman in year 1978 and hence name RSA algorithm.
Algorithm
The RSA algorithm holds the following features −
-
RSA algorithm is a popular exponentiation in a finite field over integers including prime numbers.
-
The integers used by this method are sufficiently large making it difficult to solve.
-
There are two sets of keys in this algorithm: private primal and public key.
You will have to go through the post-obit steps to work on RSA algorithm −
Stride one: Generate the RSA modulus
The initial process begins with selection of two prime numbers namely p and q, then calculating their product N, as shown −
N=p*q
Here, let N be the specified large number.
Step 2: Derived Number (eastward)
Consider number east every bit a derived number which should be greater than ane and less than (p-1) and (q-1). The primary condition will be that at that place should exist no common factor of (p-ane) and (q-1) except one
Step 3: Public key
The specified pair of numbers north and e forms the RSA public cardinal and information technology is made public.
Step 4: Private Central
Private Key d is calculated from the numbers p, q and due east. The mathematical human relationship between the numbers is equally follows −
ed = 1 mod (p-1) (q-1)
The to a higher place formula is the basic formula for Extended Euclidean Algorithm, which takes p and q every bit the input parameters.
Encryption Formula
Consider a sender who sends the manifestly text message to someone whose public fundamental is (due north,e). To encrypt the plain text message in the given scenario, use the post-obit syntax −
C = Pe mod due north
Decryption Formula
The decryption process is very straightforward and includes analytics for calculation in a systematic approach. Because receiver C has the individual key d, the upshot modulus will exist calculated as −
Plaintext = Cd mod n
Creating RSA Keys
In this affiliate, we will focus on footstep wise implementation of RSA algorithm using Python.
Generating RSA keys
The post-obit steps are involved in generating RSA keys −
-
Create two big prime numbers namely p and q. The product of these numbers volition exist called n, where n= p*q
-
Generate a random number which is relatively prime with (p-i) and (q-1). Allow the number exist called as e.
-
Calculate the modular inverse of e. The calculated inverse will be chosen every bit d.
Algorithms for generating RSA keys
Nosotros need two primary algorithms for generating RSA keys using Python − Cryptomath module and Rabin Miller module.
Cryptomath Module
The source code of cryptomath module which follows all the basic implementation of RSA algorithm is as follows −
def gcd(a, b): while a != 0: a, b = b % a, a return b def findModInverse(a, m): if gcd(a, m) != one: return None u1, u2, u3 = 1, 0, a v1, v2, v3 = 0, 1, one thousand while v3 != 0: q = u3 // v3 v1, v2, v3, u1, u2, u3 = (u1 - q * v1), (u2 - q * v2), (u3 - q * v3), v1, v2, v3 return u1 % thou
RabinMiller Module
The source code of RabinMiller module which follows all the basic implementation of RSA algorithm is as follows −
import random def rabinMiller(num): s = num - one t = 0 while south % two == 0: southward = s // 2 t += 1 for trials in range(v): a = random.randrange(ii, num - 1) v = prisoner of war(a, s, num) if 5 != i: i = 0 while v != (num - 1): if i == t - 1: return False else: i = i + one v = (five ** 2) % num return True def isPrime(num): if (num vii< 2): render False lowPrimes = [2, 3, 5, 7, eleven, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313,317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997] if num in lowPrimes: return True for prime number in lowPrimes: if (num % prime == 0): return Imitation return rabinMiller(num) def generateLargePrime(keysize = 1024): while True: num = random.randrange(ii**(keysize-1), two**(keysize)) if isPrime(num): return num
The complete code for generating RSA keys is as follows −
import random, sys, os, rabinMiller, cryptomath def chief(): makeKeyFiles('RSA_demo', 1024) def generateKey(keySize): # Pace 1: Create two prime numbers, p and q. Calculate n = p * q. print('Generating p prime number...') p = rabinMiller.generateLargePrime(keySize) print('Generating q prime...') q = rabinMiller.generateLargePrime(keySize) due north = p * q # Stride ii: Create a number due east that is relatively prime number to (p-i)*(q-ane). print('Generating due east that is relatively prime to (p-1)*(q-one)...') while Truthful: e = random.randrange(2 ** (keySize - ane), 2 ** (keySize)) if cryptomath.gcd(e, (p - i) * (q - ane)) == ane: pause # Step 3: Summate d, the mod inverse of e. impress('Calculating d that is mod changed of e...') d = cryptomath.findModInverse(e, (p - 1) * (q - 1)) publicKey = (due north, e) privateKey = (north, d) impress('Public key:', publicKey) print('Private key:', privateKey) return (publicKey, privateKey) def makeKeyFiles(name, keySize): # Creates 2 files 'x_pubkey.txt' and 'x_privkey.txt' (where x is the value in name) with the the n,east and d,e integers written in them, # delimited past a comma. if bone.path.exists('%s_pubkey.txt' % (proper name)) or os.path.exists('%s_privkey.txt' % (name)): sys.get out('WARNING: The file %s_pubkey.txt or %s_privkey.txt already exists! Use a dissimilar proper noun or delete these files and re-run this program.' % (name, proper noun)) publicKey, privateKey = generateKey(keySize) print() print('The public central is a %s and a %due south digit number.' % (len(str(publicKey[0])), len(str(publicKey[one])))) impress('Writing public key to file %s_pubkey.txt...' % (name)) fo = open up('%s_pubkey.txt' % (name), 'due west') fo.write('%southward,%s,%south' % (keySize, publicKey[0], publicKey[i])) fo.close() print() print('The private key is a %s and a %southward digit number.' % (len(str(publicKey[0])), len(str(publicKey[ane])))) print('Writing private key to file %s_privkey.txt...' % (proper name)) fo = open('%s_privkey.txt' % (name), 'westward') fo.write('%s,%s,%due south' % (keySize, privateKey[0], privateKey[1])) fo.close() # If makeRsaKeys.py is run (instead of imported as a module) call # the main() office. if __name__ == '__main__': main()
Output
The public fundamental and private keys are generated and saved in the respective files as shown in the following output.
RSA Zilch Encryption
In this chapter, we volition focus on different implementation of RSA cipher encryption and the functions involved for the aforementioned. You can refer or include this python file for implementing RSA cipher algorithm implementation.
The modules included for the encryption algorithm are as follows −
from Crypto.PublicKey import RSA from Crypto.Cipher import PKCS1_OAEP from Crypto.Signature import PKCS1_v1_5 from Crypto.Hash import SHA512, SHA384, SHA256, SHA, MD5 from Crypto import Random from base64 import b64encode, b64decode hash = "SHA-256"
We have initialized the hash value as SHA-256 for amend security purpose. We volition use a function to generate new keys or a pair of public and private primal using the following code.
def newkeys(keysize): random_generator = Random.new().read primal = RSA.generate(keysize, random_generator) individual, public = fundamental, key.publickey() return public, private def importKey(externKey): render RSA.importKey(externKey)
For encryption, the following role is used which follows the RSA algorithm −
def encrypt(message, pub_key): cipher = PKCS1_OAEP.new(pub_key) return zero.encrypt(message)
Two parameters are mandatory: message and pub_key which refers to Public key. A public key is used for encryption and private key is used for decryption.
The complete program for encryption procedure is mentioned below −
from Crypto.PublicKey import RSA from Crypto.Zippo import PKCS1_OAEP from Crypto.Signature import PKCS1_v1_5 from Crypto.Hash import SHA512, SHA384, SHA256, SHA, MD5 from Crypto import Random from base64 import b64encode, b64decode hash = "SHA-256" def newkeys(keysize): random_generator = Random.new().read central = RSA.generate(keysize, random_generator) private, public = key, key.publickey() return public, private def importKey(externKey): render RSA.importKey(externKey) def getpublickey(priv_key): return priv_key.publickey() def encrypt(message, pub_key): nix = PKCS1_OAEP.new(pub_key) render cypher.encrypt(message)
RSA Nil Decryption
This chapter is a continuation of the previous chapter where nosotros followed step wise implementation of encryption using RSA algorithm and discusses in particular about it.
The function used to decrypt cipher text is as follows −
def decrypt(ciphertext, priv_key): cipher = PKCS1_OAEP.new(priv_key) return naught.decrypt(ciphertext)
For public central cryptography or asymmetric primal cryptography, it is of import to maintain two important features namely Authentication and Authorization.
Authorization
Authorization is the process to confirm that the sender is the only one who accept transmitted the bulletin. The following code explains this −
def sign(message, priv_key, hashAlg="SHA-256"): global hash hash = hashAlg signer = PKCS1_v1_5.new(priv_key) if (hash == "SHA-512"): digest = SHA512.new() elif (hash == "SHA-384"): digest = SHA384.new() elif (hash == "SHA-256"): digest = SHA256.new() elif (hash == "SHA-1"): assimilate = SHA.new() else: digest = MD5.new() digest.update(message) return signer.sign(assimilate)
Hallmark
Authentication is possible by verification method which is explained as below −
def verify(message, signature, pub_key): signer = PKCS1_v1_5.new(pub_key) if (hash == "SHA-512"): digest = SHA512.new() elif (hash == "SHA-384"): digest = SHA384.new() elif (hash == "SHA-256"): digest = SHA256.new() elif (hash == "SHA-ane"): digest = SHA.new() else: digest = MD5.new() digest.update(message) return signer.verify(assimilate, signature)
The digital signature is verified along with the details of sender and recipient. This adds more weight historic period for security purposes.
RSA Nada Decryption
Y'all can use the following code for RSA cipher decryption −
from Crypto.PublicKey import RSA from Crypto.Cipher import PKCS1_OAEP from Crypto.Signature import PKCS1_v1_5 from Crypto.Hash import SHA512, SHA384, SHA256, SHA, MD5 from Crypto import Random from base64 import b64encode, b64decode hash = "SHA-256" def newkeys(keysize): random_generator = Random.new().read key = RSA.generate(keysize, random_generator) private, public = central, cardinal.publickey() return public, private def importKey(externKey): render RSA.importKey(externKey) def getpublickey(priv_key): return priv_key.publickey() def encrypt(message, pub_key): nil = PKCS1_OAEP.new(pub_key) return naught.encrypt(message) def decrypt(ciphertext, priv_key): cipher = PKCS1_OAEP.new(priv_key) return nada.decrypt(ciphertext) def sign(bulletin, priv_key, hashAlg = "SHA-256"): global hash hash = hashAlg signer = PKCS1_v1_5.new(priv_key) if (hash == "SHA-512"): digest = SHA512.new() elif (hash == "SHA-384"): assimilate = SHA384.new() elif (hash == "SHA-256"): digest = SHA256.new() elif (hash == "SHA-1"): digest = SHA.new() else: digest = MD5.new() digest.update(bulletin) return signer.sign(digest) def verify(message, signature, pub_key): signer = PKCS1_v1_5.new(pub_key) if (hash == "SHA-512"): digest = SHA512.new() elif (hash == "SHA-384"): assimilate = SHA384.new() elif (hash == "SHA-256"): digest = SHA256.new() elif (hash == "SHA-1"): digest = SHA.new() else: digest = MD5.new() digest.update(message) return signer.verify(assimilate, signature)
Hacking RSA Cipher
Hacking RSA cipher is possible with small-scale prime numbers, but information technology is considered impossible if it is used with large numbers. The reasons which specify why information technology is difficult to hack RSA zip are as follows −
-
Creature force assault would not work as in that location are too many possible keys to work through. Likewise, this consumes a lot of time.
-
Lexicon set on volition not work in RSA algorithm equally the keys are numeric and does not include any characters in it.
-
Frequency analysis of the characters is very difficult to follow equally a single encrypted block represents various characters.
-
There are no specific mathematical tricks to hack RSA cipher.
The RSA decryption equation is −
M = C^d modernistic n
With the help of modest prime number numbers, we can try hacking RSA cipher and the sample code for the aforementioned is mentioned beneath −
def p_and_q(due north): information = [] for i in range(two, due north): if n % i == 0: information.append(i) return tuple(data) def euler(p, q): render (p - 1) * (q - 1) def private_index(e, euler_v): for i in range(2, euler_v): if i * e % euler_v == one: return i def decipher(d, n, c): render c ** d % n def main(): eastward = int(input("input e: ")) n = int(input("input due north: ")) c = int(input("input c: ")) # t = 123 # private key = (103, 143) p_and_q_v = p_and_q(n) # print("[p_and_q]: ", p_and_q_v) euler_v = euler(p_and_q_v[0], p_and_q_v[1]) # print("[euler]: ", euler_v) d = private_index(e, euler_v) plain = decipher(d, n, c) print("plain: ", plain) if __name__ == "__main__": main()
Output
The higher up code produces the following output −
Useful Video Courses
Video
Video
Source: https://www.tutorialspoint.com/cryptography_with_python/cryptography_with_python_quick_guide.htm
Posted by: farrellsymeave.blogspot.com
0 Response to "how to find the key for the hill cipher"
Post a Comment