Quick Guide

Cryptography with Python – Quick Guide ”; Previous Next 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

Decryption of Simple Substitution Cipher

Decryption of Simple Substitution Cipher ”; Previous Next In this chapter, you can learn about simple implementation of substitution cipher which displays the encrypted and decrypted message as per the logic used in simple substitution cipher technique. This can be considered as an alternative approach of coding. Code You can use the following code to perform decryption using simple substitution cipher − import random chars = ”ABCDEFGHIJKLMNOPQRSTUVWXYZ” + ”abcdefghijklmnopqrstuvwxyz” + ”0123456789” + ”:.;,?!@#$%&()+=-*/_ []{}`~^””\” def generate_key(): “””Generate an key for our cipher””” shuffled = sorted(chars, key=lambda k: random.random()) return dict(zip(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””” key = generate_key() encrypted = encrypt(key, plaintext) decrypted = decrypt(key, encrypted) print ”Key: %s” % key print ”Plaintext: %s” % plaintext print ”Encrypted: %s” % encrypted print ”Decrypted: %s” % decrypted show_result(”Hello World. This is demo of substitution cipher”) Output The above code gives you the output as shown here − Print Page Previous Next Advertisements ”;

XOR Process

Cryptography with Python – XOR Process ”; Previous Next In this chapter, let us understand the XOR process along with its coding in Python. Algorithm XOR algorithm of encryption and decryption converts the plain text in the format ASCII bytes and uses XOR procedure to convert it to a specified byte. It offers the following advantages to its users − Fast computation No difference marked in left and right side Easy to understand and analyze Code You can use the following piece of code to perform XOR process − def xor_crypt_string(data, key = ”awesomepassword”, encode = False, decode = False): from itertools import izip, cycle import base64 if decode: data = base64.decodestring(data) xored = ””.join(chr(ord(x) ^ ord(y)) for (x,y) in izip(data, cycle(key))) if encode: return base64.encodestring(xored).strip() return xored secret_data = “XOR procedure” print(“The cipher text is”) print xor_crypt_string(secret_data, encode = True) print(“The plain text fetched”) print xor_crypt_string(xor_crypt_string(secret_data, encode = True), decode = True) Output The code for XOR process gives you the following output − Explanation The function xor_crypt_string() includes a parameter to specify mode of encode and decode and also the string value. The basic functions are taken with base64 modules which follows the XOR procedure/ operation to encrypt or decrypt the plain text/ cipher text. Note − XOR encryption is used to encrypt data and is hard to crack by brute-force method, that is by generating random encrypting keys to match with the correct cipher text. Print Page Previous Next Advertisements ”;

Decryption of Transposition Cipher

Decryption of Transposition Cipher ”; Previous Next 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 − Print Page Previous Next Advertisements ”;

Hacking Monoalphabetic Cipher

Hacking Monoalphabetic Cipher ”; Previous Next In this chapter, you will learn about monoalphabetic cipher and its hacking using Python. Monoalphabetic Cipher A Monoalphabetic cipher uses a fixed substitution for encrypting the entire message. A monoalphabetic cipher using a Python dictionary with JSON objects is shown here − monoalpha_cipher = { ”a”: ”m”, ”b”: ”n”, ”c”: ”b”, ”d”: ”v”, ”e”: ”c”, ”f”: ”x”, ”g”: ”z”, ”h”: ”a”, ”i”: ”s”, ”j”: ”d”, ”k”: ”f”, ”l”: ”g”, ”m”: ”h”, ”n”: ”j”, ”o”: ”k”, ”p”: ”l”, ”q”: ”p”, ”r”: ”o”, ”s”: ”i”, ”t”: ”u”, ”u”: ”y”, ”v”: ”t”, ”w”: ”r”, ”x”: ”e”, ”y”: ”w”, ”z”: ”q”, ” ”: ” ”, } With help of this dictionary, we can encrypt the letters with the associated letters as values in JSON object. The following program creates a monoalphabetic program as a class representation which includes all the functions of encryption and decryption. from string import letters, digits from random import shuffle def random_monoalpha_cipher(pool = None): if pool is None: pool = letters + 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(message, monoalpha_cipher): encrypted_message = [] for letter in message: encrypted_message.append(monoalpha_cipher.get(letter, 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 process of Monoalphabetic cipher which is mentioned as below − import monoalphabeticCipher as 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) print(encrypted) print(decrypted) Output You can observe the following output when you implement the code given above − Thus, you can hack a monoalphabetic cipher with specified key value pair which cracks the cipher text to actual plain text. Print Page Previous Next Advertisements ”;

One Time Pad Cipher

One Time Pad Cipher ”; Previous Next One-time pad cipher is a type of Vignere cipher which includes the following features − It is an unbreakable cipher. The key is exactly same as the length of message which is encrypted. The key is made up of random symbols. As the name suggests, key is used one time only and never used again for any other message to be encrypted. Due to this, encrypted message will be vulnerable to attack for a cryptanalyst. The key used for a one-time pad cipher is called pad, as it is printed on pads of paper. Why is it Unbreakable? The key is unbreakable owing to the following features − The key is as long as the given message. The key is truly random and specially auto-generated. Key and plain text calculated as modulo 10/26/2. Each key should be used once and destroyed by both sender and receiver. There should be two copies of key: one with the sender and other with the receiver. Encryption To encrypt a letter, a user needs to write a key underneath the plaintext. The plaintext letter is placed on the top and the key letter on the left. The cross section achieved between two letters is the plain text. It is described in the example below − Decryption To decrypt a letter, user takes the key letter on the left and finds cipher text letter in that row. The plain text letter is placed at the top of the column where the user can find the cipher text letter. Print Page Previous Next Advertisements ”;

Encryption of files

Encryption of files ”; Previous Next 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 ” [Error] No Password Input” exit(0) inputfile = options.inputfile outputfile = os.path.join( options.outputfile,os.path.basename(options.inputfile).split(”.”)[0]+”.ssb”) password = options.password base = os.path.basename(inputfile).split(”.”)[1] work = “E” ps.FileCipher(inputfile,outputfile,password,work) return if __name__ == ”__main__”: main() You can use the following 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 can observe the following output when you execute the code given above − Explanation The passwords are generated using MD5 hash algorithm and the values are stored in simply safe backup files in Windows system, which includes the values as displayed below − Print Page Previous Next Advertisements ”;

Implementing Vignere Cipher

Implementing Vignere Cipher ”; Previous Next In this chapter, let us understand how to implement Vignere cipher. Consider the text This is basic implementation of Vignere Cipher is to be encoded and the key used is PIZZA. Code You can use the following code to implement a Vignere cipher in Python − import pyperclip LETTERS = ”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) print(”%sed message:” % (myMode.title())) print(translated) print() def encryptMessage(key, message): return translateMessage(key, message, ”encrypt”) def decryptMessage(key, message): return translateMessage(key, message, ”decrypt”) def translateMessage(key, message, mode): translated = [] # stores the encrypted/decrypted message string keyIndex = 0 key = key.upper() for symbol in message: num = LETTERS.find(symbol.upper()) if num != -1: if mode == ”encrypt”: num += LETTERS.find(key[keyIndex]) elif mode == ”decrypt”: num -= LETTERS.find(key[keyIndex]) num %= len(LETTERS) if symbol.isupper(): translated.append(LETTERS[num]) elif symbol.islower(): translated.append(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 impossible. Hence, it is considered as a secure encryption mode. Print Page Previous Next Advertisements ”;

Implementation of One Time Pad Cipher

Implementation of One Time Pad Cipher ”; Previous Next Python includes a hacky implementation module for one-time-pad cipher implementation. The package name is called One-Time-Pad which includes a command line encryption tool that uses encryption mechanism similar to the one-time pad cipher algorithm. Installation You can use the following command to install this module − pip install onetimepad If you wish to use it from the command-line, run the following command − onetimepad Code The following code helps to generate a one-time pad cipher − import onetimepad cipher = onetimepad.encrypt(”One Time Cipher”, ”random”) print(“Cipher text is “) print(cipher) print(“Plain text is “) msg = onetimepad.decrypt(cipher, ”random”) print(msg) Output You can observe the following output when you run the code given above − 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 case, the key is not necessarily random, which makes one-time pad cipher as a worth tool. Print Page Previous Next Advertisements ”;

Testing of Simple Substitution Cipher

Testing of Simple Substitution Cipher ”; Previous Next In this chapter, we will focus on testing substitution cipher using various methods, which helps to generate random strings as given below − import random, string, substitution def main(): for i in range(1000): key = substitution.getRandomKey() message = random_string() print(”Test %s: String: “%s..”” % (i + 1, message[:50])) print(“Key: ” + key) encrypted = substitution.translateMessage(message, key, ”E”) decrypted = substitution.translateMessage(encrypted, key, ”D”) if decrypted != message: print(”ERROR: Decrypted: “%s” Key: %s” % (decrypted, key)) sys.exit() print(”Substutition test passed!”) def random_string(size = 5000, chars = string.ascii_letters + string.digits): return ””.join(random.choice(chars) for _ in range(size)) if __name__ == ”__main__”: main() Output You can observe the output as randomly generated strings which helps in generating random plain text messages, as shown below − After the test is successfully completed, we can observe the output message Substitution test passed!. Thus, you can hack a substitution cipher in the systematic manner. Print Page Previous Next Advertisements ”;