I want to generate my Python code in a setup.exe. The user stores an email password in the script. My question: Do I have to additionally encrypt this password, even though I create an * .exe file.
def load_settings(self):
# print(__file__)
# print(os.path.dirname(__file__))
pf = os.path.dirname(__file__)
pa = os.path.join(pf, "settings.json")
# print(pa)
if os.path.exists(pa):
# print("Pfad existiert")
with open(pa, "r") as infile:
data = json.load(infile)
self.ein.pfadbez.setText(data["pfad"])
self.ein.name.setText(data["name"])
self.ein.mail.setText(data["mail"])
self.ein.ausgangserver.setText(data["smtp"])
self.ein.port.setText(data["port"])
self.ein.login.setText(data["login"])
self.ein.passwort.setText(data["pw"])
From the way you worded your question, it sounds like you want a user to store a password within the code itself, or in a text file. Variables are called variables because they vary - a password won't be saved between executions unless stored in plain text, which is where encryption will be needed.
Further, generating Python code from a Windows executable will still require that Python code to be put somewhere for execution, and since Python is fundamentally open-source, hiding it in a compiled package won't do much.
Going about text encryption is simple - since you're on Windows, you could use Pycryptodomex, which will simplify the process of encrypting text. This tutorial could help.
Here's my code:
from cryptography.fernet import Fernet
import pyperclip
print("For this program to work, please send the file named 'pwkey' and the encrypted code to the other user.")
key = Fernet.generate_key()
file = open('pwkey', 'wb')
file.write(key)
file.close()
print('File Generated')
original = input('Enter message>>>')
message = original.encode()
f = Fernet(key)
encrypted = f.encrypt(message)
encrypted = encrypted.decode("ascii")
print('Encrypted:', encrypted)
pyperclip.copy(encrypted)
print('Please tell the other user to input the encrypted code in the Decrypt program')
print('(Code copied to Clipboard)')
print("Note: Please delete the 'pwkey' file after sending it to the other user. It
is for one-time use only.")
And decrypting
# Decrypt
from cryptography.fernet import Fernet
print("For this program to work, make sure you have the file named 'pwkey' in your Python folder and the encrypted "
"code.")
file = open('pwkey', 'rb')
key = file.read()
file.close()
print('Key Retrieved')
encrypted = input('Please input your encrypted code>>>')
encrypted = bytes(encrypted, 'utf-8')
f = Fernet(key)
decrypted = f.decrypt(encrypted)
decrypted = decrypted.decode()
print('Decrypted Message:')
print(decrypted)
print("Note: Please delete the 'pwkey' file after getting the decrypted message.")
Related
I am currently working with a login system and I want to decrypt a password that is stored in my database (It is encrypted from the beginning)
I've tried this:
from cryptography.fernet import Fernet
key = Fernet.generate_key()
cipher_suite = Fernet(key)
# THIS IS STORED IN MY DATABASE FOR EXAMPLE
password = "gAAAAABWC9P7-9RsxTz_dwxh9-O2VUB7Ih8UCQL1_Zk4suxnkCvb26Ie4i8HSUJ4caHZuiNtjLl3qfmCv_fS3_VpjL7HxCz7_Q=="
passwordChosen = password.decode('utf-8')
decryptedPasswordDB = cipher_suite.decrypt(passwordChosen)
print(decryptedPasswordDB)
I'm getting the error "InvalidToken"...
I want the decryptedPasswordDB varaible to print the actually password.
I appreciate all the help. Thanks.
First, decrypt then decode
passwordChosen = cipher.decrypt(password)
decryptedPasswordDB = passwordChosen.decode('utf-8')
Thanks in advance!
I am new to Python.
I want to PGP encrypt a file named "input.csv" using a downloaded "pgp_keys.asc" file.
Here is my attempt:
def encrypt(key, src):
import requests
r = requests.get(key)
with open("/home/zzz/.gnupg/pgp_keys.asc",'wb') as f:
f.write(r.content)
f.close()
import gnupg
gpg=gnupg.GPG(homedir='/home/zzz/.gnupg/')
f = open(src,'rb')
status = gpg.encrypt(f)
print(status.ok)
print(status.status)
print(status.stderr)
But code fails with
False
None
gpg: Sorry, no terminal at all requested - can't get input
My use case is given an input file and public key, encrypt that file.
I have the following code, where 'password' is a string which is passed into the function. The issue is such that when I attempt to read the file created in the first half of the code, Python interprets it as being empty (despite the fact that File Explorer and text editors tell me it contains content). The 4 print statements are to assist with debugging (found here).
def encryptcredentials(username, password):
# Create key randomly and save to file
key = get_random_bytes(16)
keyfile = open("key.bin", "wb").write(key)
password = password.encode('utf-8')
path = "encrypted.bin"
# The following code generates a new AES128 key and encrypts a piece of data into a file
cipher = AES.new(key, AES.MODE_EAX)
ciphertext, tag = cipher.encrypt_and_digest(password)
file_out = open(path, "wb")
[file_out.write(x) for x in (cipher.nonce, tag, ciphertext)]
print("the path is {!r}".format(path))
print("path exists: ", os.path.exists(path))
print("it is a file: ", os.path.isfile(path))
print("file size is: ", os.path.getsize(path))
# At the other end, the receiver can securely load the piece of data back, if they know the key.
file_in = open(path, "rb")
nonce, tag, ciphertext = [file_in.read(x) for x in (16, 16, -1)]
The console output is as such:
the path is 'encrypted.bin'
path exists: True
it is a file: True
file size is: 0
Here's an image of how the file is displayed in File Explorer.
It appears that there's content in the .bin file produced at [file_out.write(x) for x in (cipher.nonce, tag, ciphertext)], but I can't get Python to read it.
Welcoming all suggestions. I'm running Python 3.6, 32-bit.
You have to close or even flush the file after file_out.write(x), so your data are writing from buffer to the file.
[file_out.write(x) for x in (cipher.nonce, tag, ciphertext)]
file_out.close()
On my Linux Debian server, using python, I am trying to read a file of names line-by-line and encrypt it using the public RSA. Then I want to compare the encrypted line to another file that I have, which is also encrypted. If they are equal to each other I would like to print out the name in the decrypted and encrypted form. I have never used python before, so any help would be much appreciated.
#!/usr/bin/python
from Crypto.PublicKey import RSA
key = RSA.generate(2048)
names = open('names.txt')
cipher = open('ciphertext.txt',"r")
readname = names.readline()
readcipher = cipher.readlines()
while readname:
enc_name = pubkey.encrypt(names,0)
if enc_name == readcipher:
print readname
readname = names.readline()
names.close()
cipher.close()
I have no idea what your actual question is but maybe this will help?
for name_plaintext,name_encoded in zip(names,cipher):
if do_encode(name_plaintext) == name_encoded:
print name_decoded,"==>",name_encoded
i know how to save a users input to a text file but how do i encrypt it? here is what i have for saving a users input to text file. i tried f.encrypt("Passwords_log.txt" but had no results
import time
password1 = input("Please type a password: ")
print("Your password has passed the verification!")
time.sleep(1)
print("Saving and encrypting password...")
time.sleep(2)
f=open("Passwords_log.txt",'a')
f.write(password)
f.write('\n')
f.close()
print("Done!")
There are some Python packages worth checking out that deal with cryptography.
Cryptography
PyCrypto
A simple example from cryptography would be the following:
from cryptography.fernet import Fernet
key = Fernet.generate_key()
cipher_suite = Fernet(key)
cipher_text = cipher_suite.encrypt(b"A really secret message. Not for prying eyes.")
plain_text = cipher_suite.decrypt(cipher_text)
check out password hashing.
then i'd suggest you use https://pythonhosted.org/passlib/ or pycrypto; depending on what alorithm you choose.
this is just to store the encrypted password. to then encrypt data have a look at https://pypi.python.org/pypi/pycrypto/2.6.1.
I guess you want to get some sort of a hash for the password, but file objects have nothing to do with that. You may try to use base64 encoding (like here), or any other other algorithm of the kind.
Your code:
import time
import base64
password1 = raw_input("Please type a password: ")
print("Your password has passed the verification!")
time.sleep(1)
print("Saving and encrypting password...")
time.sleep(2)
f=open("Passwords_log.txt",'a')
password = base64.b64encode(password)
f.write(password)
f.write('\n')
f.close()
print("Done!")
You said, you tried base64 but it didn't work. Here is how you can make it work:
import base64
import time
password1 = input("Please type a password: ")
print("Your password has passed the verification!")
time.sleep(1)
print("Saving and encrypting password...")
time.sleep(2)
f=open("Passwords_log.txt",'a')
cr = base64.encodestring(password1)
f.write(cr)
f.write('\n')
f.close()
print("Done!")
This is not real encryption, I wouldn't recommend it for passwords, but since you said in your comment that you tried to use base64 and it didn't work, I thought I should show you how to use base64 in your code.