how to create a program that will read an encrypted text from a file and will create a new file with the decrypted one - python

i would like to know how to create 2 things please:
• To write a program that will read an encrypted text from a file and will create a new file with the decrypted one.
• To create a dictionary base of the decryption page
my decryption page looks like this and it has to be a LIST '' a=z, b=y, c=x, d=w...''
this translation working good, but i need to read the encrypted string from an existing file, translate it and to write the decrypted string in a new file
Example code

# ------- DEFs------------
def encrypt(text):
encrypted_text = ""
alphabet = 'abcdefghijklmnopqrstuvwxyz'
for char in text:
if char in alphabet:
encrypted_text+= alphabet[25-alphabet.find(char)]
else:
encrypted_text+= char
return encrypted_text
# ------- MAIN ------------
# alphabet
inttab = 'abcdefghijklmnopqrstuvwxyz'
# inverted alphabet
outtab = 'zyxwvutsrqponmlkjihgfedcba'
print(inttab.find('a'))
# > 0
print(outtab.find('a'))
# > 25
# cipher -> inttab = outtab - 25
text = 'hello world!'
encrypted_text = encrypt(text)
print(encrypted_text)
# > svool dliow!
decrypted_text = encrypt(encrypted_text)
print(decrypted_text)
# > hello world!

You should create a Dictionary to find for each encrypted char entry its corresponding translation.
## Create an empty dictionary
your_dictionary = {}
## Fill your_dictionary with the (key, values) couples
## With keys your key list, and values your values list
for key, value in zip(keys, values):
your_dictionary[key] = value
## Decrypt your encrypted message
## With enc_message the encrypted message
decrypted_message = ""
for c in enc_message:
decrypted_message = decrypted_message+your_dictionary[c]
Now you may want to play it a little bit more secure, because you may face some issues if you try to decrypt either a char you havent added as a key in the dictionary, or a space.
decrypted_message = ""
for c in enc_message:
if c.isspace():
decrypted_message = decrypted_message + c
elif c not in your_dictionary :
## Handle this case how you want. By default you can add it.
decrypted_message = decrypted_message + c
else :
decrypted_message=decrypted_message + your_dictionary[c]
So, as you requested the encrypted and decrypted message should come from a file and should be outputted as a file, you can use the following functions and instruction to perform the whole cycle :
## Decrypt a message with a specific dictionary
def decrypt_message(message, your_dict):
decrypted_message = ""
word = ""
for index, c in enumerate(enc_message):
print(c)
if c.isspace():
decrypted_message = decrypted_message + c
elif c not in your_dict :
decrypted_message = decrypted_message + c
else :
decrypted_message = decrypted_message + your_dict[c]
return decrypted_message
## Populate a dictionary with the given couples
def populate_dictionary(keys, values):
your_dictionary = {}
for key, value in zip(keys, values):
your_dictionary[key] = value
return your_dictionary
## Example keys
keys = ['a', 'b', 'c']
## Example values
values = ['d', 'e', 'f']
## Open the input file
with open('encryptedMessage.txt', 'r') as file:
enc_message = file.read().replace('\n', '')
## Populating the dictionary
dic = populate_dictionary(keys, values)
## Decrypting the message
dec_message = decrypt_message(enc_message, dic)
## Creating and saving the decrypted message in the output file.
text_file = open("decryptedMessage.txt", "w")
text_file.write(dec_message)
text_file.close()

Related

Python: Decrypting a file (have key)

I encrypted a file from ascii randomized key. I need to decrypt back into normal letters from and then put that into a new file
import random
lst = list(range(1,128)) #for key
numbersran = list()
while len(numbersran) < 128:
candidate = random.randint(1,128)
if candidate not in numbersran:
numbersran.append(candidate)
listsdict = dict(zip(lst,numbersran)) #makes key, changes every time
print("Encytption key=", listsdict)
print()
filename=input("Enter File: ")
with open(filename, "r") as file:
filetxt = file.read()
ascii_codes = [ord(c) for c in filetxt]
encrypted_codes = [listsdict[code] for code in ascii_codes]
print('\nEncrypted file: ',encrypted_codes)
cypher = "".join([chr(c) for c in encrypted_codes]) #encrypts from key
#decrypt below here into a file using the key to translate (should be original text from file)
I am not too sure how to reverse the process back to the original text in file. Must be decrypted back, can't just be copied from og file
The decryption process should be reverse of what has been done for encryption. Find below the code snippet.
decrypted_file = [ord(c) for c in cypher]
decrypted_key = list()
for value in decrypted_file:
for key in listsdict:
if listsdict[key] == value:
decrypted_key.append(key)
break
print(''.join([chr(c) for c in decrypted_key]))
There can be better ways to achieve the decryption but the solution in its naivest form should be like above.
easy way to replace this code snippet:
for value in decrypted_file:
for key in listsdict:
if listsdict[key] == value:
decrypted_key.append(key)
break
is to reverse listsdict keys with value as suggested by #scott hunter
decrypted_file = [ord(c) for c in cypher]
decrypted_key = list()
listsdict = dict(zip(numbersran,lst))
decrypted_key = [listsdict[code] for code in decrypted_file]
print(''.join([chr(c) for c in decrypted_key]))

Trying to add elements to list but getting out of range errors

import re
sifrelenmisdizi = []
kelimeler = []
bulunankelimeler = []
input = input("Lütfen Şifrelenmiş Veriyi giriniz : ")
def sifrecoz(message): #im cracking password here
encrypted = ""
for i in range(25):
for char in message:
value = ord(char) + 1
valuex = value % 123
if (valuex <= 0):
valuex = 97
encrypted += chr(valuex)
elif (valuex == 33):
encrypted += chr(32)
else:
encrypted += chr(valuex)
message = encrypted
sifrelenmisdizi.append(encrypted)
encrypted = ""
def kelime_getir(dosya_adi): # here im taking words on "kelimeler.txt"
with open(dosya_adi, 'r', encoding='utf-8') as input_file:
dosya_icerigi = input_file.read()
kelime_listesi = dosya_icerigi.split()
index = 0
while index <= 1164053:
kelimeler.append(kelime_listesi[index]) #here im taking that issue
index += 1
return kelimeler
sifrecoz(input)
kelime_getir("kelimeler.txt")
for i in range(len(kelimeler)):
for j in range(len(sifrelenmisdizi)):
x = re.split("\s", sifrelenmisdizi[j])
for k in range(len(x)):
if (kelimeler[i] == x[k]):
bulunankelimeler.append(kelimeler[i])
print("Kırılmış şifreniz : ",bulunankelimeler)
# selam daktilo dalga = ugnco eblujmp ebmhb
Here I am coding a password cracking program with Caesar decryption of encrypted data and compare with "kelimeler" list.
I'm trying to add words to "kelimeler" list but I'm taking out of range error.
This is my word list:
[URL=https://dosya.co/31174l7qq8zh/kelimeler.txt.html]kelimeler.txt - 16.9 MB[/URL]
It appears that the function kelime_getir is expected to return a list of all the words in the file (which has one word per line).
Therefore:
def kelime_getir(dosya_adi):
with open(dosya_adi, encoding='utf-8') as txt:
return list(map(str.strip, txt))
...is all you need

How to get around "source code string cannot contain null bytes" when eval is run without removing the null bytes

I have a program where I encrypt class.__dict__ and save it to a file in an array so the file looks something like this -
{'some name':[1, 2, 3],
'data':'''𚶩9È𚵶𚶛𚵝X§Ë¡¡Ö©𚶕 î𚶣o𚶥[𚵶𚶎 y𚵽𚵮^𚵜𚶩5Ð¥"¢§«!𚵩𚶅𚶚𚵰fa¥𚶯m𚵬c𚶮^𚵵W𚵴𚶭''' #somthing like this but a lot longer
}
I then read it and need to decrypt data but before that, I need to get the data from the array that is currently a string which I did with eval(fileContent) and it gives me the error -
Traceback (most recent call last):
File "C:/Users/stemb/Documents/programing/python/programs/img editor/__init__.py", line 127, in
<module>
main()
File "C:/Users/stemb/Documents/programing/python/programs/img editor/__init__.py", line 102, in main
save_code.auto_save_load()
File "C:\Users\stemb\Documents\programing\python\programs\img editor\save_code.py", line 153, in
auto_save_load
data = eval(fileContent)
ValueError: source code string cannot contain null bytes
My reading function is this
data = open("./save." + GLOBAL.fileType, "r", encoding="utf-8").read()
json.loads gives json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)
My code is -
# imports
import json
import random
import time
print("Finished save_progress imports")
def encrypt(obj, log=0): #encrypt
# set data
data = str(obj.__dict__)
key = "codeAsciEightAndMabyA_Seven" + str(time.time()) # crate key
key = list(key)
random.shuffle(key) # randomize key
cryptionKeys = list()
encrypted = list()
iMinus = 0
for i in range(len(data)): # create a random + or - for extra security
cryptionKeys.append(random.choice(("+", "-")))
# encode part
for i, c in enumerate(data):
# set individual data
charAsci = ord(c)
cryptionKey = cryptionKeys[i]
done = 0
while done == 0:
try:
charKey = ord(key[i - iMinus])
done = 1
except IndexError:
iMinus += len(key)
if cryptionKey == "+":
encryptedOrd = charAsci + charKey
else:
encryptedOrd = charAsci - charKey
if encryptedOrd < 0:
encryptedOrd += 110000
cryptionKeys[i] = "="
cryptionKey = cryptionKeys[i]
encryptedChar = chr(encryptedOrd)
encrypted.append(encryptedChar)
if log == 1:
print("charNumb \/")
print(i)
print("charAsci \/")
print(charAsci)
print("cryptionKey \/")
print(cryptionKey)
print("charKey \/")
print(charKey)
print("encryptedOrd \/")
print(encryptedOrd)
print("encryptedChar \/")
print(encryptedChar)
print()
encrypted2 = encrypted
encrypted = ""
for c in encrypted2:
encrypted += c
return str(encrypted), str(key), str(cryptionKeys)
def auto_save(GLOBAL): # the save func
file = open("./save." + GLOBAL.fileType, "w", encoding="utf-8")
encryptedGLOBAL, key, cryptionKeys = encrypt(GLOBAL)
out = ("{'key':" + str(key) + ", 'cryptionKeys':" + str(cryptionKeys) + ", 'data':'''" + str(
encryptedGLOBAL) + "'''}")
print(out)
file.write(out)
file.close()
def auto_save_load(aclass): # the loading dunc
data = open("./save." + GLOBAL.fileType, "r", encoding="utf-8").read()
data = eval(data)
key = data["key"]
cryptionKeys = data["cryptionKeys"]
encryptedGLOBAL = data["data"]
print(key)
print()
print(cryptionKeys)
print()
print(encryptedGLOBAL)
Other answers have said to remove the null bytes but the encryption method needs them.
Please help.

Converting Binary to ASCII, and ASCII to Binary

I'm currently writing an ascii-binary/binary-ascii converter in Python for a school project, and I have an issue with converting from ascii (String text) to binary. The idea is to print the outcome in the test() on the bottom of the code.
When running the code in WingIDE, an error occurs:
On the line starting with
bnary = bnary + binary[chnk]
KeyError: "Norway stun Poland 30:28 and spoil Bielecki's birthday party."
What I'm trying to do here is to convert the String of text stored in "text.txt" to a String of integers, and then print this binary string.
Any help is greatly appreciated. I tried looking at other ascii-binary vice-versa convertion related questions, but none seemed to work for me.
My code:
def code():
binary = {}
ascii = {}
# Generate ascii code
for i in range(0,128) :
ascii[format(i,'08b')] = chr(i)
# Reverse the ascii code, this will be binary
for k, v in ascii.iteritems():
binary[v] = binary.get(v, [])
binary[v].append(k)
return ascii
def encode(text,binary):
'''
Encode some text using text from a source
'''
bnary = ""
fi = open(text, mode='rb')
while True:
chnk = fi.read()
if chnk == '':
break
if chnk != '\n':
binry = ""
bnary = bnary + binary[chnk]
return bnary
def decode(sourcecode,n, ascii):
'''
Decode a sourcecode using chunks of size n
'''
sentence = ""
f = open(sourcecode, mode='rb') # Open a file with filename <sourcecode>
while True:
chunk = f.read(n) # Read n characters at time from an open file
if chunk == '': # This is one way to check for the End Of File in Python
break
if chunk != '\n':
setence = "" # The ascii sentence generated
# create a sentence
sentence = sentence + ascii[chunk]
return sentence
def test():
'''
A placeholder for some test cases.
It is recommended that you use some existing framework, like unittest,
but for a temporary testing in a development version can be done
directly in the module.
'''
print encode('text.txt', code())
print decode('sourcecode.txt', 8, code())
test()
If you want to decode and encode, have this solutions
Encode ascii to bin
def toBinary(string):
return "".join([format(ord(char),'#010b')[2:] for char in string])
Encode bin to ascii
def toString(binaryString):
return "".join([chr(int(binaryString[i:i+8],2)) for i in range(0,len(binaryString),8)])
fi.read() returns the whole document the first time and '' next times. So you should do
text = fi.read()
for char in text:
do_stuff()
Edit1
You can only read your file once. Thus you have to get your chars one by one. A file.read returns a string containing the whole document.
You can iterate over a string to get chars one by one.
The main error is your binary is {"a":['010001110'], "b":...} and you try to access with the key "azerty" where you should do it char by char:
string = "azer"
result = []
for c in string:
result += binary[c]
>>> result = [['11001'],[1001101'],...]
# Lets say your filename is stored in fname
def binary(n):
return '{0:08b}'.format(n)
with open(fname) as f:
content = f.readlines()
for i in content:
print(binary(ord(i)), end='')
print('')
This will give you the integer value(from ascii) of each character in the file, line by line

Use substitution cipher in python to encrypt and decrypt a .txt file and output to a new .txt file

I am able to open the rules file and create a dictionary to use for my encryption. I have to also create a dictionary to use for decrypting text. I assume it's basically the same function with minor changes. The encrypt works fine, but I can't get the decrypt to work. My second problem is that while I encrypted the file I took out all spaces and punctuation. I can't figure out how to get those back in the output file once I run the program. It just prints in a single column. Lastly I have to output this to a .txt file. I am able to create a .txt with a user assigned name, but can't get anything to print on the file.
Here is what I achieved so far.
#import clauses
import string
#function definitions
#encrypt dictionary
def createrulesdictencrypt(openFile):
rulesencrypt1 = {}
for line in openFile:
rulessplit = string.split(string.strip(line))
rulesencrypt1[rulessplit[0]] = rulessplit[1]
return rulesencrypt1
#decrypt dictionary
def createrulesdictdecrypt(openFile):
rulesdecrypt1 = {}
for line in openFile:
rulessplit = string.split(string.strip(line))
rulesdecrypt1[rulessplit[1]] = rulessplit[0]
return rulesdecrypt1
openFile = open('rules.txt', 'r')
rulesencrypt = createrulesdictencrypt(openFile)
rulesdecrypt = createrulesdictdecrypt(openFile)
#print rulesencrypt
#print rulesdecrypt
#function for encrypting file
def encryptfile(openFile2):
for line in openFile2:
for word in line.split():
empty = ''
for char in word:
if char not in string.punctuation:
char=char.lower()
empty = empty+char
if len(empty) == 2:
print rulesencrypt[empty]
empty = ''
if len(empty) == 1:
print rulesencrypt[empty]
#function for decrypting file
def decryptfile(openFile2):
for line in openFile2:
for word in line.split():
empty = ''
for char in word:
if char not in string.punctuation:
char=char.lower()
empty = empty+char
if len(empty) == 2:
print rulesdecrypt[empty]
empty = ''
if len(empty) == 1:
print rulesdecrypt[empty]
#main program
ende = raw_input("To encrypt a file, enter '0':\nTo decrypt a file, enter '1':")
filename = raw_input("Enter the name of the file to be processed:")
outfilename = raw_input("Enter the name of the file to save the result to:")
openFile2 = open(filename, 'r')
outputfile = open(outfilename, 'w')
fileencrypt = encryptfile(openFile2)
filedecrypt = decryptfile(openFile2)
if ende == "0":
print encryptfile(fileencrypt)
if ende == "1":
print decryptfile(filedecrypt)
This is what I am trying to encrypt
Sir Robin: "Oh, you liars!"
Minstrel: [singing] "Bravely taking to his feet, he beat a very brave
retreat. A brave retreat by brave Sir Robin."
Your first problem is that you're not actually writing your encrypted text to a file, instead you're just printing it to sys.stdout. Incidentally, print appends a \n to it's output by default.
You could rewrite your decrypt function as follows:
#function for decrypting file
def decryptfile(openFile2, outfile): # <- CHANGED to add outfile
for line in openFile2:
for word in line.split():
empty = ''
for char in word:
if char not in string.punctuation:
char=char.lower()
empty = empty+char
if len(empty) == 2:
outfile.write(rulesdecrypt[empty]) # <- CHANGED to write to file
empty = ''
if len(empty) == 1:
outfile.write(rulesdecrypt[empty]) # <- CHANGED to write to file
You will then need to invoke the decryptfile function with a file as its second argument. A similar change could be made to the encryptfile function.
With respect to punctuation and whitespace, either encrypt it or just leave it in place. Once you've removed it, there really isn't a good way to replace it.

Categories