How to read encrypted data from notepad and decrypt - python

I'm attempting to read text from a file and decrypt it using the Fernet cryptography library in Python. So i'm running a For loop which prints all of the text, while it does that I attempt to make the loop decrypt.
from cryptography.fernet import Fernet
from inspect import currentframe
key = "kdQGjocgILOLXj6k_mkkOJOxHxXJji7kdRUTtrGZBTo="
f = Fernet(key)
def get_linenumber():
cf = currentframe()
return cf.f_back.f_lineno
def Main():
choice = input("1. Write Raw Data To File For Encryption\n2. Read Data From File For Decryption\n\nEnter Option Here: ")
if choice == "1":
print("Init Main Successfull On Line ", get_linenumber())
File = open(r"D:\Visual Studio Projects\Python Proj\Secure Note Storage Project\File.txt",mode="a")
FileToEncrypt = bytes(input("Input data to encrypt, Note it will be stored as a string, then heavily encrypted with SHA-256.\n"),'utf-8')
print("\nSuccesfully printed File To Encrypt data on line ",get_linenumber,"\nData From FileToEncrypt Var: ",FileToEncrypt)
FileEncrypted = f.encrypt(FileToEncrypt)
print("\n\n\Here is the final product: ",FileEncrypted)
EncryptionDescription = input("What Is The Data Entered. (Explain For Future Reference!!!)\n\nEnter Here: ")
File.write(f"{EncryptionDescription}\n" + str(FileEncrypted))
File.close()
elif choice == "2":
print("\n\nYou Have Chosen Decryption Method!\n")
File = open(r"D:\Visual Studio Projects\Python Proj\Secure Note Storage Project\File.txt",mode="r")
for line in File:
name = line.strip()
num = File.readline()
num = Fernet.decrypt(f,num)
print (num)
else:
print("Sorry, We Do Not Recognise What You Have Entered. Please look at the options and think...")
exit(0)
###Debug Shit
#print(Fernet.generate_key()) # so i can find one key and keep it static:)
# print(File.read())
# print("File Print Successfull On Line ", get_linenumber())
# File.write("\nRawrar")
if __name__ == "__main__":
Main()
I tried printing the data from the file, then when that worked. I attempted to convert the Num Variable to a decrypted version of the encrypted text. When that didn't work I messed with the parameters a bit. But I got no where, not to sure what Im doing.

The first problem in this case seems to be the fact that you correctly convert FileToEncrypt into bytes for encryption, but when you save it you simply cast it as a string using str(). What you want to do instead is use .decode()
Furthemore you'd probably want to add another linebreak when you write the data to the file. Otherwise you will face issues if you append multiple times to the same file
File.write(f"{EncryptionDescription}\n" + FileEncrypted + "\n") You'd also want to make sure that when loading this data that you convert it to bytes again using bytes(str, 'utf-8').
Now that your data is properly saved into the File.txt file, you are now ready to decode the data. However you will still face an error as you do not pass a timestamp in the decrypt function call, as per the documentation. Essentially I found two ways to do this. One would simply be to call the function with a very high number as the ttl paramater like this: print(Fernet.decrypt(f,bytes(num, "utf-8"), 1000000))
The proper way to do this is to use the function extract_timestamp() as per the documentation. I implemented it like this encryptionTimeStamp = Fernet.extract_timestamp(f, bytes(num, 'utf-8')) with success.
Doing this will get you the unix timestamp at the time of encryption. The ttl parameter is the number of seconds since encryption, you'd want to take the "current unix timestamp - unix timestamp at encryption" and pass that as the ttlparameter.
from cryptography.fernet import Fernet
from inspect import currentframe
import time
key = "kdQGjocgILOLXj6k_mkkOJOxHxXJji7kdRUTtrGZBTo="
f = Fernet(key)
def get_linenumber():
cf = currentframe()
return cf.f_back.f_lineno
def Main():
choice = input("1. Write Raw Data To File For Encryption\n2. Read Data From File For Decryption\n\nEnter Option Here: ")
if choice == "1":
print("Init Main Successfull On Line ", get_linenumber())
File = open(r"File.txt",mode="a")
FileToEncrypt = bytes(input("Input data to encrypt, Note it will be stored as a string, then heavily encrypted with SHA-256.\n"),'utf-8')
print("\nSuccesfully printed File To Encrypt data on line ",get_linenumber,"\nData From FileToEncrypt Var: ",FileToEncrypt)
FileEncrypted = f.encrypt(FileToEncrypt)
FileEncrypted = FileEncrypted.decode()
print("\n\n\Here is the final product: ",FileEncrypted)
EncryptionDescription = input("What Is The Data Entered. (Explain For Future Reference!!!)\n\nEnter Here: ")
File.write(f"{EncryptionDescription}\n" + FileEncrypted + "\n")
File.close()
elif choice == "2":
print("\n\nYou Have Chosen Decryption Method!\n")
File = open(r"File.txt",mode="r")
for line in File:
name = line.strip()
num = File.readline()
numBytes = bytes(num, 'utf-8')
encryptionTimeStamp = Fernet.extract_timestamp(f, numBytes)
currentTime = int(time.time())
timeElapsed = currentTime - encryptionTimeStamp
print( Fernet.decrypt(f,numBytes, timeElapsed))
else:
print("Sorry, We Do Not Recognise What You Have Entered. Please look at the options and think...")
exit(0)
###Debug Shit
#print(Fernet.generate_key()) # so i can find one key and keep it static:)
# print(File.read())
# print("File Print Successfull On Line ", get_linenumber())
# File.write("\nRawrar")
if __name__ == "__main__":
Main()

Related

Python custom function reseting csv file

I am trying to make a login system sort of program but whenever there is more than 1 line of data the code resets the entire CVS file. I need someone to help me with why it's happening. It happens when I choose opt == 2 and search for the name entered 2nd onwards...
reading the CSV file:
try:
df = pd.read_csv('accounts.csv')
for i in range(len(df['name'])):
names.append(df['name'][i])
balances.append(df['balance'][i])
dec_pass = bytes(df['password'][i], 'utf-8')
f = Fernet(key)
decrypted = f.decrypt(dec_pass)
decrypted = decrypted.decode()
passwords.append(decrypted)
except:
with open('accounts.csv', 'w') as f:
f.write(',name,balance,password')
names = []
balances = []
passwords = []
def name_ser(name):
found = False
for i in range(len(names)):
if names[i] == name:
found = True
return found, names.index(name)
else:
found = False
return found
def main_menu():
print('Welcome!\nPlease Choose from the following options...')
print('1: Create an account\n2: Login ')
opt = int(input('Enter Your Choice: '))
if opt == 1:
name_search = input('Enter Name... ')
found, _ = name_ser(name_search)
if found == True:
print("Account Already excites!")
else:
acc_creation(name_search)
print('Account created!')
if opt == 2:
name_search = input('Enter your login name: ')
found, indx = name_ser(name_search)
if found == True:
password = input('Enter your password: ')
dec_pass = bytes(passwords[indx], 'utf-8')
f = Fernet(key)
decrypted = f.decrypt(dec_pass)
decrypted = decrypted.decode()
if password == decrypted:
print('Logged in!')
else:
print('Invalid username or password')
before:
after:
the other thing is when I try to create more than 2 accounts it gives an error and also resets the CSV file. it works fine for the first 2 accounts but gives an error on the second one.
def acc_creation(name):
names.append(name)
balances.append(0)
password_enter = input('Create a Password: ')
encry_p = password_enter.encode()
f = Fernet(key)
encry_pass = f.encrypt(encry_p)
encry_pass = encry_pass.decode('ascii')
passwords.append(encry_pass)
new_df = pd.DataFrame(np.column_stack([names, balances, passwords]),
columns=['name', 'balance', 'password'])
new_df.to_csv('accounts.csv', encoding='utf-8', sep=',',
header=True, na_rep=0, index=True)
Error:
Traceback (most recent call last):
File "/Users/darkmbs/VS-Code/FirstPythonProject/accounts.py", line 91, in <module>
main_menu()
File "/Users/darkmbs/VS-Code/FirstPythonProject/accounts.py", line 79, in main_menu
acc_creation(name_search)
File "/Users/darkmbs/VS-Code/FirstPythonProject/accounts.py", line 54, in acc_creation
new_df = pd.DataFrame(np.column_stack([names, balances, passwords]),
File "<__array_function__ internals>", line 5, in column_stack
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/numpy/lib/shape_base.py", line 656, in column_stack
return _nx.concatenate(arrays, 1)
File "<__array_function__ internals>", line 5, in concatenate
ValueError: all the input array dimensions for the concatenation axis must match exactly, but along dimension 0, the array at index 0 has size 2 and the array at index 2 has size 1
I believe this may possibly be tied to the name_ser method but cannot be totally sure without seeing what it is doing.
What CSV library are you using? CSV? Panda?
Also, you may want to try adding a return value to the name_ser method to return the index and not have to go through the list again to match it to the password.
Good luck!
--- Edit ---
Every time that you are executing it is opening up the file again and re-writing: ,name,balance,password
If you are wanting to execute more than once, you will need to either:
Write a while loop for main where it will continuously call main_menu()
Check to see if the CSV already exists. If it does, open in read and copy everything and paste it into a new writeable CSV. If it doesn't, move to create the new writeable CSV.
There are quite a few issues here we should address before we try to fix your problem:
your code sample is incomplete, the function name_ser as well as your names and passwords lists are missing
passwords must never be stored in plaintext (unless this code is just for yourself to learn stuff). Please read about Key derivation functions
CSV is not a database where you can easily edit entries inplace. The only safe way to handle this is to overwrite the entire CSV file each time you make a change or to use another data structure (which I would strongly recommend)

NameErorr name 'filename' not defined after returning 'filename' from another function

Hi I was writing a code for a simple Caesar cipher decrypting program with python 3 and I got this error message when I was trying to run the program. Here's the code and I've got some description of the situation I'm having after the code.
def main():
def getInputFile():
"""get the name of the file user wants to decrypt and check
if its extension is txt or not and return the file name"""
filename = input('Enter the input file name: ')
while not filename.endswith('.txt'):
filename = input('Invalid file name extension. Please re-enter the input file name: ')
return filename
def decrypt(filename):
"""open the secret message and decrypt the caesar cipher and
return original message"""
readSecretMessage = open(filename, "r")
lines = readSecretMessage.readline()
cipher_key = int(lines[0])
secret_message = lines[1]
decrypted = ""
for letter in secret_message:
if letter in alphabet:
# decrypting
letter_index = (alphabet.find(letter) - cipher_key) % 26
decrypted = decrypted + alphabet[letter_index]
else:
decrypted = decrypted + letter
return decrypted
getInputFile()
message_decrypted = decrypt(filename)
print('The decrypted message is: ')
print(message_decrypted)
main()
And I get this error message from the fourth last line when I try to run the decrypt function. I thought it's all good since I returned 'filename' value from the getInputFile function but I guess not. Can someone help me figure out why this doesn't work and how should I fix this?
Thanks for your time!
Returning a variable called filename from the function does not automatically create a variable called filename in the scope that the function was called in. You need to explicitly assign the returned value to a variable:
f_name = getInputFile()
message_decrypted = decrypt(f_name)

Error whilst trying to delete string from a 'txt' file - Contacts list program

I'm creating a Contact list/book program which can create new contacts for you. Save them in a 'txt' file. List all contacts, and delete existing contacts. Well sort of. In my delete function there is an error which happens and I can't quite tell why?. There isn't a error prompted on the shell when running. It's meant to ask the user which contact they want to delete, find what the user said in the 'txt' file. Then delete it. It can find it easily, however it just doesn't delete the string at all.
I have tried other methods including if/else statements, other online code (copied) - nothing works.
import os, time, random, sys, pyautogui
#function for creating a new contact.
def new_contact():
name = str(input("Clients name?\n:"))
name = name + " -"
info = str(input("Info about the client?\n:"))
#starts formatting clients name and info for injection into file.
total = "\n\n"
total = total + name
total = total + " "
total = total + info
total = total + "\n"
#Injects info into file.
with open("DATA.txt", "a") as file:
file.write(str(total))
file.close
main()
#function for listing ALL contacts made.
def list():
file = open("DATA.txt", "r")
read = file.read()
file.close
#detects whether there are any contacts at all. If there are none the only str in the file is "Clients:"
if read == "Clients:":
op = str(input("You havn't made any contacts yet..\nDo you wish to make one?\n:"))
if op == "y":
new_contact()
else:
main()
else:
print (read)
os.system('pause')
main()
#Function for deleting contact
def delete_contact():
file = open("DATA.txt", "r")
read = file.read()
file.close
#detects whether there are any contacts at all. If there are none the only str in the file is "Clients:"
if read == "Clients:":
op = str(input("You havn't made any contacts yet..\nDo you wish to make one?\n:"))
if op == "y":
new_contact()
else:
main()
else:
#tries to delete whatever was inputted by the user.
file = open("DATA.txt", "r")
read = file.read()
file.close
print (read, "\n")
op = input("copy the Clinets name and information you wish to delete\n:")
with open("DATA.txt") as f:
reptext=f.read().replace((op), '')
with open("FileName", "w") as f:
f.write(reptext)
main()
#Main Menu Basically.
def main():
list_contacts = str(input("List contacts? - L\n\n\nDo you want to make a new contact - N\n\n\nDo you want to delete a contact? - D\n:"))
if list_contacts in ("L", "l"):
list()
elif list_contacts in ("N", "n"):
new_contact()
elif list_contacts in ("D", "d"):
delete_contact()
else:
main()
main()
It is expected to delete everything the user inputs from the txt file. No errors show up on shell/console, it's as if the program thinks it's done it, but it hasn't. The content in the txt file contains:
Clients:
Erich - Developer
Bob - Test subject
In your delete function, instead of opening DATA.txt, you open "FileName"
When using “with”, a file handle doesn't need to be closed. Also, file.close() is a function, you didnt call the function, just its address.
In addition, in the delete function, you opened “fileName” instead of “DATA.txt”

Pickle module in Python and text files

I have recently asked a question and received an answer that I must 'pickle' my code. As a beginner, I have no idea how to do that.
This was my code:
users = []
users.append([username, password])
usersFile = open("users.txt","w+")
for users in users:
usersFile.write("%s" % users)
usersFile.close()
def loginFunction():
userEntry = ""
foundName = 0
while userEntry == "":
userEntry = raw_input("Enter your username: ")
usersFile = open("users.txt", "r")
lines = usersFile.readlines()
for i, user in enumerate(users):
if userEntry == users[index][0]:
foundName = 1
passwordEntry = raw_input("Enter your password: ")
if passwordEntry == users[index][1]:
print "Username and passwords are correct"
break
else:
print "incorrect"
userEntry = ""
if foundName == 0:
print "Username not recognised"
userEntry = ""
My problem was that I was never receiving an "Enter your password" despite knowing that the username I was entering was in fact in the text file in that list. I kept getting "Username not found back" even though I knew it was there. There was mention of not having referred back to lines but again, not sure how I would go about doing that. If someone could help me out by changing up my code and explaining that would be fantastic. I have been referred to documents trying to explain it and have done by own research on the topic but none of it makes sense to me. A written example in this context would help me out a lot.
So, if I understood correctly by looking at the other two questions (1 and 2) you made related to this, your problem has two parts:
One is generating a file with a list of user/passwords and the second is using that file to do a "login" system.
The problem with writing to files is that you can regard a file as just text... It doesn't really retain the concept of a Python list so you need to figure out a way to convert your fancy users list of lists to text and then back to a list of lists so you can actually use it.
There are many pre-made serializing formats. Here are a few: JSON, CSV, YAML, or the one another user recommended in another question, Pickle
Since in another post you mentioned that you're using this for learning purposes, let's try to keep it as simple as possible ok?
Let's split your exercise in two python files: One to just generate the passwords file and the other that tries to read and verify the username/password that the user entered.
Script 1: Generate the password file.
So... You have a list of username/password pairs, and you have to transform that to text so you can store it in a file. Let's just go through each entry in the list and write it to a file. How about using a bit of inspiration from Linux and use the semicolon character (;) to mark the separation between username and password on each line of the file? Like this:
sample_users = [
["user1", "password1"],
["user2", "password2"],
["user3", "password3"]
]
users_file = open("./users.txt", "w")
for sample_user in sample_users:
username = sample_user[0]
password = sample_user[1]
users_file.write(username + ';' + password + '\n')
users_file.close()
Put that in a .py file and run it. It should generate a file called users.txt right on the same directory where the script is located. I suggest you take a look to the file (any text editor will do). You'll see it looks like this:
user1;password1
user2;password2
user3;password3
By the way, it's a much better practice taking advantage of the "autoclosing" features provided by Python's context managers. You could write that script as:
with open("./users.txt", "w") as users_file:
for sample_user in sample_users:
username = sample_user[0]
password = sample_user[1]
users_file.write(username + ';' + password + '\n')
See? No call to .close() needed. If something happens while running the code, you will be assured that your file is closed after leaving the with block (when the interpreter reaches the end of the with block, a call to the File's special function __exit__ will be automatically run, and the file will be closed)
Script 2: Use the passwords file
Ok... So we have a file with username;password\n on each line. Let's use it.
For this part, you're gonna need to understand what the split (to separate username and password using the semicolon) and rstrip (to remove the newline symbol \n at the end) methods of the str objects do.
We're gonna need to "rebuild" two variables (username and password) from a line of text that has the shape username;password\n. Then see if the username is found in the file, and if so, prompt the user for the password (and verify it's correct):
def loginFunction():
userEntry = ""
foundName = False
while userEntry == "":
userEntry = raw_input("Enter your username: ")
usersFile = open("users.txt", "r")
for line in usersFile:
print("This is the line I read:%s", line,)
# Read line by line instead of loading the whole file into memory
# In this case, it won't matter, but it's a good practice to avoid
# running out of memory if you have reaaaally large files
line_without_newline = line.rstrip('\n') # Remove ending \n
user_record = line_without_newline.split(';') # Separate into username and password (make the line a list again)
userName = user_record[0]
password = user_record[1]
# Might as well do userName, password = line_without_newline.split(';')
if userName == userEntry:
foundName = True
print("User found. Verifying password.")
passwordEntry = raw_input("Enter your password: ")
if passwordEntry == password:
print "Username and passwords are correct"
break
else:
print "incorrect"
userEntry = ""
if not foundName:
print("Username not recognised")
userEntry = ""
if __name__ == "__main__":
loginFunction()
I believe this should do what you want? Put a comment in the answer if you have other questions.
And have fun coding!
PS: So... How about pickle?
Pickle is a module that serializes Python objects into files in a "safer" and more automated way. If you wanted to use it, here's how (one way, at least):
Generating the passwords file:
import pickle
sample_users = [
["user1", "password1"],
["user2", "password2"],
["user3", "password3"]
]
with open('./users.txt', 'w') as f:
pickler = pickle.Pickler(f)
for sample_user in sample_users:
pickler.dump(sample_user)
As before, at this point I would recommend you take a look to how the file users.txt looks like with a regular text editor. You'll see it's pretty different to the file before (the one with the username and password separated by semi colons). It's something like this:
(lp0
S'user1'
p1
aS'password1'
p2
a.(lp3
S'user2'
p4
aS'password2'
p5
a.(lp6
S'user3'
p7
aS'password3'
p8
a.%
Use the file:
import pickle
def loginFunction():
userEntry = ""
while userEntry == "":
userEntry = raw_input("Enter your username: ")
usersFile = open("users.txt", "r")
unpickler = pickle.Unpickler(usersFile)
while True:
try:
user_record = unpickler.load()
userName = user_record[0]
password = user_record[1]
if userName == userEntry:
print("User found. Verifying password.")
passwordEntry = raw_input("Enter your password: ")
if passwordEntry == password:
print "Username and passwords are correct"
else:
print "incorrect"
userEntry = ""
# Watch out for the indentation here!!
break # Break anyway if the username has been found
except EOFError:
# Oh oh... the call to `unpickler.load` broke
# because we reached the end of the file and
# there's nothing else to load...
print("Username not recognised")
userEntry = ""
break
if __name__ == "__main__":
loginFunction()
If you realize, when you do user_record = unpickler.load(), you already get a 2 items Python list in the user_record variable. There's no need for you to transform from text onto list: the unpickler has already done that for you. This is possible thanks to of all that "extra" information that was stored by picker.dump into the file, which allows the unpickler to "know" that the object that needs to be returned is a list.
This is the way you create a login system with pickle however i don't recommend this as there is lot of security issue.I would prefer connecting python to SQL server and storing password in the database.
import pickle
def register(username,password):
user_details = dict()
with open("users.txt",'rb') as f:
user_details = pickle.load(f)
if username in user_details:
print "User already exsits"
else:
user_details[username] = password
print "User added successfully"
with open("users.txt",'wb+') as f:
pickle.dump(user_details,f)
def login(username,password):
user_details = dict()
with open("users.txt",'rb') as f:
user_details = pickle.load(f)
if username in user_details:
if user_details[username] == password:
print "Correct Login successful"
else:
print "Incorrect Details"
def init():
user_details = dict()
with open("users.txt",'wb+') as f:
pickle.dump(user_details,f)
init()
register("s","s")
login("s","s")
To initialise call the init() function.

Encryption, encoding and Python (AES)

I'm trying to write an encryption/decryption program called P-Cypher in python (python-Cypher, rhymes with decypher). It uses the PyCrypto libraries to encode a file (using AES). Although I know Python, I do not know cryptography - I'm doing this because I thought it would be fun, so don't critique me on security.
This is how the program is supposed to work.
Asks for input file.
Asks whether you want it to encrypt or decrypt. (sets mode)
Asks for output file. Verifies it exists- if it does not, asks if you want it to create one.
Encrypts input file and tells you the key/Prompts you for the key, and decrypts the file with the key (Depending on mode)
Writes to output file.
Everything works except for number 4. (I know step 5 works as step 5 remains pretty much unchanged from the last stable version, v0.03d). On step 4 encoding, one of two things happen depending on which way I code it:
The thing successfully- YAY! encodes the file. However, the key it prints out is in the form of b'U\xxx\xxx\xxx\xxx\xxx' like that. When I enter it in step 4 decoding mode, with or without the b and 's, it doesn't work. So the program cannot decrypt the file, rendering half of my program useless.
I can use .decode(encoding) to turn it into a string. This is the method you see on the code below. However, here is this way's problem- no matter what encoding I use (ascii, ISO, windows-125x, EUR, Big5, utf-8, 16, and 32, etc...) there is always one or more bytes that the encoding cannot encode. And without encoding, there's no decoding, rendering the WHOLE program useless.
So I ask you for help. If you could figure out how to fix problem #1 or #2 (or maybe even both), I would be grateful.
CODE -- Updated
# P-Cypher-Dev
# Made in 2015 by Mateo Guynn
# v0.04d
# Using AES 16/32/64-bit encryption (Google standard)
# DEV VERSION: Possibly unstable, contains better code.
# Changelog:
"""
v0.02d
- Improved Caesar Cipher
- Added binary Cipher converter (fail)
-------------FILE BROKEN------------
"""
"""
v0.03d
- Added ability to create new output files
- Fixed code not quitting on abort
- DEL : binary Cipher converter
---------------STABLE---------------
"""
"""
v0.04d
- DEL : Caesar Cypher
- Added 16/32/64-byte AES encryption
- Binary and text now handled in same manner
-------------FILE BROKEN------------
(encryption works, decryption does not)
"""
"""
v0.05d
- Changed AES encryption to Google's way
- Fixed Key entry
"""
import os
import sys
from Crypto.Cipher import AES
from Crypto import Random
from Crypto.Util import randpool
import base64
import codecs
MAX_KEY_SIZE = 26 # Shows the number of available characters (26 in the alphabet)
#NOTES: Binary mode only works if the file is named binary.dat.
def getMode():
while True:
eOrD = input('\nDo you wish to encrypt or decrypt a message? ')
mode = eOrD.lower()
if mode in 'encrypt e decrypt d'.split():
return mode
else:
sys.exit('\nEnter either "encrypt" or "e" or "decrypt" or "d". Capital letters are allowed.\n')
def getMessage():
inputFile = open(input('\nPlease enter the name of the file you want to encrypt/decrypt. You may use relative or full paths. \nPlease, remember the file extension(s)! ')).read()
try:
print ('\nThe contents of the file are: \n%s\n' % inputFile)
return inputFile
except IOError as e:
sys.exit('Unable to open file (the file does not exist or P-Cypher does not have permission to view it).\n Aborting.')
except FileNotFoundError as e:
sys.exit('Unable to open file (the file does not exist or P-Cypher does not have permission to view it).\n Aborting.')
def getCipher(mode, message):
block_size = 16 # For AES, this is the only working value
key_size = 32 # Size of crypto key (possibly changes in getKey())
aesmode = AES.MODE_CBC # More secure mode
if mode[0] == 'e':
key_bytes = randpool.RandomPool(512).get_bytes(key_size)
open('decryption.key', 'wb+').write(key_bytes)
print('\nYour keyfile is: decryption.key\n')
pad = block_size - len(message) % block_size
data = message + pad * chr(pad)
iv_bytes = randpool.RandomPool(512).get_bytes(block_size)
encrypted_bytes = iv_bytes + AES.new(key_bytes,aesmode,iv_bytes).encrypt(data)
encrypted = base64.urlsafe_b64encode(encrypted_bytes)
return encrypted
else:
decryptb = base64.urlsafe_b64decode(message)
decrypted_ivbytes = decryptb[:block_size]
decrypt = decryptb[block_size:]
print('\nAuto-searching for decryption.key...')
try:
key_bytes = base64.urlsafe_b64decode(open('decryption.key', 'rb').read())
except IOError as io:
key_bytes = base64.urlsafe_b64decode(open(input('decryption.key not found. If you have an alternate keyfile, please enter its name now. ')), 'rb').read
except FileNotFoundError as fnf:
key_bytes = base64.urlsafe_b64decode(open(input('decryption.key not found. If you have an alternate keyfile, please enter its name now. '), 'rb').read())
decrypted = AES.new(key_bytes, aesmode, decrypted_ivbytes).decrypt(decryptb)
pad = ord(decrypted[-1])
decrypted = decrypted[:-pad]
return decrypted
def getOutput():
outputFile = input('\nPlease specify an output file. \nDon\'t forget the file extension! ')
outputCheck = input('\nYour message will be encrypted/decrypted into the following output file: %s\n\nIs this okay? (y/n) ' % outputFile).lower()
if outputCheck in 'y yes yeah ok'.split():
try:
return outputFile
except IOError as ioerror:
createNewFile = input('The file you specified does not exist. Shall I create one? (y/n) ')
if createNewFile in 'y_yes_yeah_yes please_ok'.split('_'):
oF = open(outputFile, 'w+')
oF.close()
return outputFile
else:
sys.exit('Aborting...')
elif outputCheck in 'n no'.split():
sys.exit('\nAborting...\n')
else:
sys.exit('\nAborting.\n')
print("\nP-Cypher Alpha starting up...\n\nv0.05 dev\nMateo Guynn\n2015\n")
mode = getMode()
message = getMessage()
try:
open(getOutput(), 'wb+').write(getCipher(mode,message))
except IOError:
sys.exit('Oh noes! Something has gone terribly wrong!')
except FileNotFoundError:
sys.exit('Your input file was not found.')
print('\nDone.')
one solution is to encode it as hex ... this is guaranteed to be ascii characters
import codecs
my_key = "U\x22\x54\x33"
print ("Your Key:", codecs.encode(my_key,"hex"))
...
my_decode_key = codecs.decode(input("enter key:"),"hex")
print( repr(my_decode_key))
print( my_decode_key == my_key )

Categories