Decrypt with Fernet [Python] - python

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')

Related

Python, fernet decrypt turn my file read only

I'm with a personal proyect using python and sqlite3, the case is that i use fernet to encrypt the db file, but at decrypt the db it turn in a read only db and give me error at try do an INSERT.
sqlite3.OperationalError: attempt to write a readonly database
I try edit the linux permissions using chmod 664 and 777 but nothing seems work it still as only read db
----- EDIT WITH MORE INFO
I use local file and connect using sqlite3, i create a clase for manage the db
class DataBaseManager(object):
def __init__(self,db):
self.con = sqlite3.connect(db)
self.cur = self.con.cursor()
def inicializar(self):
checkTableStore = self.cur.execute(
"""SELECT name FROM sqlite_master WHERE type='table' AND name='store'; """
).fetchall()
if checkTableStore == []:
self.cur.execute(
"""create table store(
........
)"""
)
def __del__(self):
self.con.close
if in the first execution and the db file doesn't exist create it with the DataBaseManager(dbfile) and after check if the table that i need is created or not and create if not exist with DataBaseManager.inicializar()
keyfile = input("keyfile: ")
dbfile = "pstore.db"
dbencrypt = "pstore.enc"
dbm = DataBaseManager(dbfile)
DataBaseManager.inicializar()
For encrypt and decrypt i use a key generated with fernet
def encryptdb(keyfile, dbfile, dbencrypt):
with open(keyfile, "rb") as openkeyfile:
key = openkeyfile.read()
fernet = Fernet(key)
with open (dbfile, "rb") as opendbfile:
decrypteddb = opendbfile.read()
encrypted = fernet.encrypt(decrypteddb)
with open (dbencrypt, "wb") as encrypteddb:
encrypteddb.write(encrypted)
def decryptdb(keyfile, dbfile, dbencrypt):
with open(keyfile, "rb") as openkeyfile:
key = openkeyfile.read()
fernet = Fernet(key)
with open (dbencrypt, "rb") as openenc:
encrypteddb = openenc.read()
decrypted = fernet.decrypt(encrypteddb)
with open (dbfile, "wb") as decrypteddb:
decrypteddb.write(decrypted)
Before than made the encrypt i can do inserts without problem, but after encrypt and decrypt i got the problem that the database is only read
Ok, solved.
I tryed use a second file to save the db encrypted. But i proved save the encrypted output of fernet in the sabe db file that existed, it don't give to me the ro error after decrypt.

Getting error "AttributeError: 'list' object has no attribute 'encrypt'" when trying to encrypt text

I was trying to make a fun little program with Python:
#secret text be like:
from cryptography.fernet import Fernet
g = open("ygr.data")
message = g.readlines()
key = Fernet.generate_key()
# Instance the Fernet class with the key
fernet = Fernet(key)
h = open("key.keysbois", "w")
h.write(str(key))
# then use the Fernet class instance
# to encrypt the string string must must
# be encoded to byte string before encryption
encMessage = fernet.encrypt(message.encrypt())
f = open("totallysecrettext.rushe", "w")
f.write(encMessage)
I might be being dumb, but I get the error AttributeError: 'list' object has no attribute 'encrypt' when I try to run it. Any suggestions?
Also, is it ok to use weird file extensions (i.e. file.rushe, file.data, file.key)
You're reading in the file's content by using readlines(). This returns a list of lines from the file.
message = g.readlines()
You then try to call encrypt on this list, which doesn't make sense - since you're already calling it on the fernet object:
fernet.encrypt(message.encrypt())
^-- this is a list of lines from the file - not what you want
Instead, read the file's content using just read(). You also have to make sure you read the file in binary format, so that you get bytes you can send to fernet:
g = open("ygr.data", "rb")
message = g.read()
.. then encrypt the content:
encMessage = fernet.encrypt(message)

encrypt password in python

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.")

PGP encrypt an input file in Python given a public key

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.

writing a variable to a text file and encrypting it?

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.

Categories

Resources