This post is about create a demo Encryption and decryption algorithm using Python

We have two different files

Encryption - E-3B.py
Decryption - D-3B.py

The above two file has different purposes

the First One is to Encrypt the source or text file it has been given

the Second One is to Decrypt the Encrypted data with a password given by the user

Let me review the whole code.

1. E-3B.py - Encryptor

in the below line we will import the Python sys library in order to be able to accept Parameters from the user terminal

import sys

in the below line we have some variable that will be used to replace and store default values

encryptedFile = ""             # Variable To Assign The Encrypted File
sourceFile    = None		   # Source File To Be Encrypted
algChanger    = [0,0,0,0]      # Values To Change The Algorithm

# Special Strings Will Be Inserting In The Middle of Words and Letters
startString = "\e"      # Identifies The Starting of a Word
Space 		= "\*"      # Identifies Spaces Between Words
newLine 	= "\~"      # Identifies New Lines/End of Line 
tabLet 		= "\`"      # Identifies Tabs in One Line

And then we have some instructions the to let our users know how the input everything in a properway.

print "\n   [ * ] Simple 3xPinkyB Encrypter"

def __appUsage():
	print "   [ * ] Usage: python E-3B.py Test.java 12345678\n"
	print "   [ * ] Encryption Key Length Must be 8 and Must be Numeric\n"



and we have the below line which will be used in order to change an algorithm based on the conditions we have given it and return the encrypted value it generates.

def __changeAlgForEncryption(ASCIIValue, encKeyNum, firstAlg, secondAlg):
	global algChanger, startString
	if algChanger[encKeyNum] == 0:
		newVal = startString + firstAlg + str(ASCIIValue)
		algChanger[encKeyNum] = 1
	else:
		newVal = startString + secondAlg + str(ASCIIValue)
		algChanger[encKeyNum] = 0
	return newVal


The next line will add the encrypted value to the global variable we have created in line 10

def __addToEncryptedFile(stringToBeAdded):
	global encryptedFile
	encryptedFile = encryptedFile + stringToBeAdded
	

In the below code we make sure the given arguments are greater than two and then split the encryption key given by the user into 4 pics and then insert the splitter values into EncLetValue array.

# Check if The Given Arguments are Greater Than 2 (eg): python E-3B.py fileName.txt encryptionKey
if len(sys.argv) > 2:                              
	if len(str(sys.argv[2])) == 8:
		encKey      = str(sys.argv[2])       
		encKeyOne   = int(encKey[0] + encKey[1])
		encKeyTwo   = int(encKey[2] + encKey[3])
		encKeyThree = int(encKey[4] + encKey[5])
		encKeyFour  = int(encKey[6] + encKey[7])
		EncLetValue = [encKeyOne,encKeyTwo,encKeyThree,encKeyFour]
		print "   [ * ] Please Save Your Encryption Key in A Safe Place --[" + sys.argv[2] + "]--"

In the below code we try to open the file given by the user and iterate through every character of it

		try:
			openFile = open(sys.argv[1],"r")		# Try To Open File Specified in The First Argument
			sourceFile = openFile.read()            # Read All The Contents of The Source File
			print "   [ * ] Please Wait Encypting Source: " + sys.argv[1]
			i = 0
			while i < len(sourceFile): 

While iterating through the text we check if the current value is Space,New Line and Tab. if the current value is one of the above characters we replace them with an other value.

				ASCIIValue = ord(sourceFile[i])							 # Get The ASCII Value of The Current Character
				newVal = ""
				if ASCIIValue == 32:                                     # If The ASCII Value is Space
					__addToEncryptedFile("\\*")
				elif ASCIIValue == 10: 									 # Else If The ASCII Value is New Line
					__addToEncryptedFile("\\~")
				elif ASCIIValue == 9:									 # Else If The ASCII Value is Tab
					__addToEncryptedFile("\\`")
				else:	

If the current character is not one of the above characters we try to generate an algorithm based on the Passcode the user given above.

					sumOne = EncLetValue[2] + EncLetValue[3] 
					if ASCIIValue >= sumOne:
						sumOne = sumOne + EncLetValue[0]
						if ASCIIValue >= sumOne:
							sumOne = sumOne + EncLetValue[1]
							if ASCIIValue >= sumOne:
								ASCIIValue = ASCIIValue - sumOne
								newVal = __changeAlgForEncryption(ASCIIValue,0,"DcGae","HcBie")
							else:
								ASCIIValue = sumOne - ASCIIValue
								newVal = __changeAlgForEncryption(ASCIIValue,1,"DJgaf","hcBif")
						else:
							ASCIIValue = sumOne - ASCIIValue
							newVal = __changeAlgForEncryption(ASCIIValue,2,"Hjaf","dJif")
					else:
						ASCIIValue = sumOne - ASCIIValue
						newVal = __changeAlgForEncryption(ASCIIValue,3,"DJf","jHf")
					__addToEncryptedFile(newVal)

After we have finished with the characters we then try to close the opened file and then open an other file with the extension .3xPinkyB which will be used to store the encryption value.

			openFile.close()
			try:
				newFile = open(sys.argv[1] + ".3xPinkyB","a")
				y = 0
				while y < len(encryptedFile):
					if y >= 100:
						if y % 100 == 0:
							newFile.write("\n")
					newFile.write(encryptedFile[y])
					y = y + 1
				newFile.close()
				print "   [ * ] Encrypted File Sucessfully Saved in File: " + sys.argv[1] + ".3xPinkyB\n"
			except IOError:
				print "   [ * ] Unable To Save Encrypted File\n"


2. D-3B.py - Decryptor

The second and the last part of the app is the Decryption part.

as always in the below code we import the sys package and then declare some variables that will be used to store values and also define arrays used for decrytion.

import sys

encryptedFile = ""
sourceFile    = ""
isTerminated  = False
encValues     = ["a","b","c","d","e","f","g","h","i","j","A","B","C","D","G","H","I","J"]
i = 0

In the next lines of code we have some instruction for our user on how they will be able to enter their information.

print "\n   [ * ] Simple 3xPinkyB Decrypter"

def __appUsage():
	print "   [ * ] Usage: python D-3B.py Test.java.3xPinkyB 12345678\n"
	print "   [ * ] Encryption Key Length Must be 8 and Must Be Numeric\n"

In the next line we have _checkValidChar function which will check if the current character is in between encValues array we have created above.

__calculateLastNumbers which will check the last character we have is a space,new line and tab.

__checkASCIIValue which is responsible for checking if the given ascii value of a character is between 1 and 255.

__checkChar which will match the given character we have is in between the given characters to decrypt based on the keys given.

def __checkValidChar(charToBeChecked):
	z = 0
	isValidChar = False
	while z < len(encValues):
		if charToBeChecked == encValues[z]:
			isValidChar = True
		z = z + 1
	return isValidChar

def __calculateLastNumbers():
	global i, encryptedFile
	i = i + 1
	newVal = 0
	while (i < len(encryptedFile) and ord(encryptedFile[i]) >= 48 and ord(encryptedFile[i]) <= 57) or ord(encryptedFile[i]) == 10:
		if ord(encryptedFile[i]) != 10:
			newVal = (newVal * 10) + (ord(encryptedFile[i]) - 48)
		i = i + 1
	return newVal

def __checkASCIIValue(ASCIIValue):
	global sourceFile, isTerminated
	if ASCIIValue < 256 and ASCIIValue > 0:
		sourceFile = sourceFile + chr(ASCIIValue)
		isTerminated = False
	else:
		print "   [ * ] Invalid DeCryption Key Found Please Correct it" 
		__appUsage()
		isTerminated = True
		sourceFile = ""

def __checkChar(ch, fChar, sChar, tChar, foChar):
	if ch == fChar or ch == sChar or ch == tChar or ch == foChar:
		return True
	else:
		return False


In the below code we make sure the given arguments are greater than two and then split the encryption key given by the user in to 4 peaces and then insert the splitted values in to EncLetValue array.

if len(sys.argv) > 2:
	if len(str(sys.argv[2])) == 8:
		encKey      = str(sys.argv[2])    
		encKeyOne   = int(encKey[0] + encKey[1])
		encKeyTwo   = int(encKey[2] + encKey[3])
		encKeyThree = int(encKey[4] + encKey[5])
		encKeyFour  = int(encKey[6] + encKey[7])

We then try to open the encrypted file given in the first argument.

		try:
			openFile = open(sys.argv[1],"r")
			encryptedFile = openFile.read()
			print "   [ * ] Please Wait While Decypting Source: " + sys.argv[1]

The below code will iterate through every character and identify the special character we have given like e,f,*,~,`,\ and new line which is 10.

while i < len(encryptedFile) and isTerminated == False:
				if encryptedFile[i] == "\\":
					if ord(encryptedFile[i + 1]) == 10:
						i = i + 1
						
					if encryptedFile[i + 1] == "e":
						i = i + 2
						ASCIIValue = 0
						while i < len(encryptedFile) and encryptedFile[i] != "\\" and isTerminated == False:
							isValidChar = __checkValidChar(encryptedFile[i])
							
							a = encryptedFile[i]
							if isValidChar == True:
								if __checkChar(encryptedFile[i],'a','A','I','i'):
									ASCIIValue = ASCIIValue + encKeyOne
									i = i + 1
								elif __checkChar(encryptedFile[i],'b','B','G','g'):
									ASCIIValue = ASCIIValue + encKeyTwo
									i = i + 1
								elif __checkChar(encryptedFile[i],'c','C','J','j'):
									ASCIIValue = ASCIIValue + encKeyThree
									i = i + 1
								elif __checkChar(encryptedFile[i],'d','D','H','h'):
									ASCIIValue = ASCIIValue + encKeyFour
									i = i + 1
								elif a == 'e':
									ASCIIValue = ASCIIValue + __calculateLastNumbers()
									__checkASCIIValue(ASCIIValue)
								elif a == 'f':
									ASCIIValue = ASCIIValue - __calculateLastNumbers()
									__checkASCIIValue(ASCIIValue)
							elif ord(a) == 10:
								i = i + 1
							else:
								isTerminated = True
								sourceFile = ""
								print "   [ * ] Please Insert a Valid Encrypted File Now Exiting"
								__appUsage()
								exit(0)
					elif encryptedFile[i + 1] == "~":
						sourceFile = sourceFile + "\n"
						i = i + 2
					elif encryptedFile[i + 1] == "*":
						sourceFile = sourceFile + chr(32)
						i = i + 2
					elif encryptedFile[i + 1] == "`":
						sourceFile = sourceFile + chr(9)
						i = i + 2
					elif ord(encryptedFile[i + 1]) == 10:
						i = i + 2
					else:
						i = len(encryptedFile)
						sourceFile = ""
						print "   [ * ] Please Insert a Valid Encrypted File Now Exiting"
						__appUsage()
						exit(0)
						isTerminated = True
				elif ord(encryptedFile[i]) == 10:
					i = i + 1
				else:
					i = len(encryptedFile)
					sourceFile = ""
					print "   [ * ] Please Insert a Valid Encrypted File Now Exiting"
					__appUsage()
					exit(0)
					isTerminated = True

And finally we close the file we opened earlier and try to create a new file that will store the decrypted data.

openFile.close()
			try:
				newFile = open(sys.argv[1] + ".DCRPT","w")
				newFile.write(sourceFile)
				newFile.close()
				print "   [ * ] Decrypted File Sucessfully Saved in File: " + sys.argv[1] + ".DCRPT\n"
			except IOError:
				print "   [ * ] Unable To Save Decrypted File\n"