Multiplicative Cipher ”; Previous Next While using Caesar cipher technique, encrypting and decrypting symbols involves converting the values into numbers with a simple basic procedure 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 as follows − (Alphabet Number * key)mod(total number of alphabets) The number fetched through output is mapped in the table mentioned above and the corresponding letter is taken as the encrypted letter. The basic modulation function of a multiplicative cipher in Python is as follows − def unshift(key, ch): offset = 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 work with very large keys like 8,953,851. It would take quite a long time for a computer to brute-force through a majority of nine million keys. Print Page Previous Next Advertisements ”;
Category: cryptography With Python
Base64 Encoding & Decoding
Base64 Encoding and Decoding ”; Previous Next Base64 encoding converts the binary data into text format, which is passed through communication channel where a user can handle text safely. Base64 is also called as Privacy enhanced Electronic mail (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 You can use the following piece of code to perform base64 encoding − import base64 encoded_data = base64.b64encode(“Encode this text”) print(“Encoded text with base 64 is”) print(encoded_data) Output The code for base64 encoding gives you the following output − Program for Decoding You can use the following piece of code 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 − Difference between ASCII and base64 You can observe the following differences when you work on ASCII and base64 for encoding data − When you encode text in ASCII, you start with a text string and convert it to a sequence of bytes. When you encode data in Base64, you start with a sequence of bytes and convert it to a text string. Drawback Base64 algorithm is usually used to store passwords in database. The major drawback is that each decoded word can be encoded easily through any online tool and intruders can easily get the information. Print Page Previous Next Advertisements ”;
Simple Substitution Cipher
Simple Substitution Cipher ”; Previous Next Simple substitution cipher is the most commonly used cipher and includes an algorithm of substituting every plain text character for every cipher text character. In this process, alphabets are jumbled in comparison with Caesar cipher algorithm. Example Keys for a simple substitution cipher usually consists of 26 letters. An example key is − plain alphabet : abcdefghijklmnopqrstuvwxyz cipher alphabet: phqgiumeaylnofdxjkrcvstzwb An example encryption using the above key is− plaintext : defend the east wall of the castle ciphertext: giuifg cei iprc tpnn du cei qprcni The following code shows a program to implement simple substitution cipher − import random, sys LETTERS = ”ABCDEFGHIJKLMNOPQRSTUVWXYZ” def main(): message = ”” if len(sys.argv) > 1: with open(sys.argv[1], ”r”) as f: message = f.read() else: message = raw_input(“Enter your message: “) mode = raw_input(“E for Encrypt, D for Decrypt: “) key = ”” while checkKey(key) is False: key = raw_input(“Enter 26 ALPHA key (leave blank for random key): “) if key == ””: key = getRandomKey() if checkKey(key) is False: print(”There is an error in the key or symbol set.”) translated = translateMessage(message, key, mode) print(”Using key: %s” % (key)) if len(sys.argv) > 1: fileOut = ”enc.” + sys.argv[1] with open(fileOut, ”w”) as f: f.write(translated) print(”Success! File written to: %s” % (fileOut)) else: print(”Result: ” + translated) # Store the key into list, sort it, convert back, compare to alphabet. def checkKey(key): keyString = ””.join(sorted(list(key))) return keyString == LETTERS def translateMessage(message, key, mode): translated = ”” charsA = LETTERS charsB = key # 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__”: main() Output You can observe the following output when you implement the code given above − Print Page Previous Next Advertisements ”;
Python Overview and Installation ”; Previous Next 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. Print Page Previous Next Advertisements ”;
Double Strength Encryption
Double Strength Encryption ”; Previous Next 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. Print Page Previous Next Advertisements ”;
Caesar Cipher
Cryptography with Python – Caesar Cipher ”; Previous Next 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 − Print Page Previous Next Advertisements ”;
Encryption of Transposition Cipher ”; Previous Next 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. Print Page Previous Next Advertisements ”;
Decryption of files
Decryption of files ”; Previous Next In this chapter, let us 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 following 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 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) (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 exit(0) inputfile = options.inputfile outputfile = options.outputfile password = options.password work = “D” ps.FileCipher(inputfile,outputfile,password,work) return if __name__ == ”__main__”: main() You can use the following command 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 after decryption, which keeps a note that the same file is encrypted and the process was successful. Print Page Previous Next Advertisements ”;
Transposition Cipher
Transposition Cipher ”; Previous Next 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. Print Page Previous Next Advertisements ”;
ROT13 Algorithm
Cryptography with Python – ROT13 Algorithm ”; Previous Next 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. Print Page Previous Next Advertisements ”;