Tuple decryption problem using cryptography.fernet - python

ok so I'm trying to code a password manager in python and I'm using cyrptography.fernet to crypt the emails and passwords and then store them into a local SQLite database the problem is that when I try to get for example the emails in the database they are in this format: (b'encypted-email-here'), (b'and-so-on) so I thought since theres the b before the quotes it's in bytes format and I do not need to do anything in order to decrypt them but when I actually try to decrypt them I get an error saying: "TypeError: token must be bytes" here is my code so you can take a look at it
b_email = email.encode('utf-8')
b_pwd = pwd.encode('utf-8')
enc_email = f.encrypt(b_email)
enc_pwd = f.encrypt(b_pwd)
conn = sqlite3.connect('database.db')
execute = conn.cursor()
execute.execute('CREATE TABLE IF NOT EXISTS logins (website, email, password)')
execute.execute('INSERT INTO logins VALUES (:website, :email, :password)', {'website': website, 'email': enc_email, 'password': enc_pwd})
conn.commit()
conn.close()
def view():
con = sqlite3.connect('database.db')
cur = con.cursor()
iterable = cur.execute('SELECT email FROM logins')
for email in iterable:
dec_email = f.decrypt(email)
print(dec_email)```

cur.execute() returns a sequence of rows, each of them is a tuple. In your case, a tuple of just one element, but still you need to extract the email from it. The most elegant way would be unpacking (notice the comma after email):
for email, in cur.execute('SELECT email FROM logins'):
print(f.decrypt(email))

Related

Python SQLite Update Function not working

I'm using Python 3.7.5 and SQLite3 3.X as well as Tkinter (but that's irrelevant) and I can't seem to update my table called "Account"
try:
Cursor.execute("""CREATE TABLE Account (
Application text,
Username text,
Password text)""")
except sqlite3.OperationalError:
Cursor.execute("""UPDATE Account SET
Application = :NewApp,
Username = :NewUser,
Password = :NewPass
WHERE oid = :oid""",
{"NewApp": NewApplicationE.get(),
"NewUser": NewUsernameE.get(),
"NewPass": NewPasswordE.get(),
"oid": X[3]
})
The try bit is just to create the table if there's not already one and if there is it goes on to update the table
I know for a fact there's columns called Application, Username, Password and the variable.get() all returns the proper string
The oid being X[3] gives you an integer
The program runs but it doesn't actually seem to update anything.
Any help with the formatting or just in general would be appreciated
I think that you need just commit your change
I assume that you get cursor from a connectio,
For instance something like that should work:
import sqlite3
conn = sqlite3.connect('example.db')c = conn.cursor()
Cursor = conn.cursor()
try:
Cursor.execute("""CREATE TABLE Account (
Application text,
Username text,
Password text)""")
conn.commit()
except sqlite3.OperationalError:
Cursor.execute("""UPDATE Account SET
Application = :NewApp,
Username = :NewUser,
Password = :NewPass
WHERE oid = :oid""",
{"NewApp": NewApplicationE.get(),
"NewUser": NewUsernameE.get(),
"NewPass": NewPasswordE.get(),
"oid": X[3]
})
conn.commit()
conn.close()
Referece
https://docs.python.org/3/library/sqlite3.html

Register-Login system

I am trying to make a register-login system in Python 3, but when I check if the Email address already exists or not, it always says that it doesn't. I inserted an email and a password in the "users" table and when asked I used that same email address in this script but it still says that it doesn't exist. I have little to none experience in MySQL and thought that this may be a nice project to start with. Thank you.
import cymysql
from getpass import getpass
def get_user_info():
while True:
email = input("Input your Email address (max. 64 chars.): ")
password = getpass("Input a password (max. 64 chars.): ")
if len(email) < 64 and len(password) < 64:
return email, password
def check_account(cur, email, password):
if(cur.execute(f"SELECT * FROM `users` WHERE `Email`='{email}' LIMIT 1")):
print("exist")
else:
print("no exist")
def main():
conn = cymysql.connect(
host='192.168.0.109',
user='root',
passwd='',
db='database'
)
cur = conn.cursor()
email = ''
password = ''
email, password = get_user_info()
check_account(cur, email, password)
cur.close()
conn.close()
if __name__ == '__main__':
main()
Disclaimer: I have yet to use cymysql – any code attached below is untested.
First, note that CyMySQL is a forked project of PyMySQL[1] so I will refer to documentation from PyMySQL.
From pymysql.cursors.Cursor.execute documentation:
execute(query, args=None)
Execute a query
Parameters:
query (str) – Query to execute.
args (tuple, list or dict) – parameters used with query. (optional)
Returns: Number of affected rows
Return type: int
The important thing to consider is the execute function returns: the number of affected rows. A SELECT query will not affect any rows, thus the function will return 0 and your function will print no exist reasonably.
Use fetchone to check that at least one row was returned.
def check_account(cur, email, password):
cur.execute(f"SELECT * FROM `users` WHERE `email`=%s LIMIT 1", (email,))
row = cur.fetchone()
if row:
print("exist")
else:
print("no exist")
(I rewrote your cur.execute call in consideration of my earlier comment.)

MySQL/Python connector not being able to search [duplicate]

This question already has an answer here:
MySQL/Python -> Wrong Syntax for Placeholder in Statements?
(1 answer)
Closed 4 years ago.
import mysql.connector
config = {
'user': 'root',
'password': '*******',
'host': '127.0.0.1',
'database': 'mydb',
'raise_on_warnings': True
}
cnx = mysql.connector.connect(**config)
cursor = cnx.cursor()
find_user = ("SELECT * FROM HM_Login WHERE Username = '%s' ")
data_Pupil = {
'Username': "GJM"
}
cursor.execute(find_user, data_Pupil)
lit = cursor.fetchall()
print(lit)
cursor.close()
cnx.close()
I have a database that works and i am having a problem trying to search the database and pull one row of one column when i was inserting into the database the %S worked just fine but now it only works if i have a value inside the the query. this is using the mysql connector for python.
mysql.connector.errors.ProgrammingError: 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1
I am getting this error which is extremely insightful and not helpful at all if there is anything you can do to help it would mean a lot.
As the error statement says. You have an SQL error. You are trying to input a variable as a positional parameter but you've used a dictionary on a variables 'place'.
Instead you should use %s for variables and tuples with variables and then do the following:
find_user = "SELECT * FROM HM_Login WHERE Username = %s"
data_Pupil = ('GJM',)
cursor.execute(find_user, data_Pupil)
It is also possible to use dictionary - but you shouldn't. Despite that I'm still going to show it here as I had to dig into the explanation to understand why.
find_user = "SELECT * FROM HM_Login WHERE Username = '{Username}'".format(**data_Pupil)
data_Pupil = {
'Username': "GJM"
}
The above opens up for sql-injections, as I was told per the comments - and here is why; Say we have a username that is identical to the following:
username = "'MR SQL Injection');DROP TABLE HM_Login;"
That would result in an SQL Query that drops the table.
SELECT * FROM HM_Login WHERE Username = 'MR SQL Injection');DROP TABLE HM_Login;
To avoid sql-injection as above. Use the first solution
Your placeholder syntax is for positional parameters but you've used a dictionary. Replace that with a tuple:
find_user = ("SELECT * FROM HM_Login WHERE Username = %s")
data_pupil = ('GJM',)
cursor.execute(find_user, data_Pupil)

SQLite not accepting unique command

Python/Flask:
cur = conn.cursor()
cur.execute('CREATE TABLE IF NOT EXISTS users (email TEXT NOT NULL UNIQUE, password TEXT)')
print('Table created')
Then in another method
def create_user(email, hashedpw):
try:
cur.execute('INSERT INTO users VALUES (?, ?)', (email, hashedpw))
conn.commit()
return "works"
except:
print(str(sqlite3.Error))
return None
Even if I input the same email 10 times it still records the data in the database and doesn't give an error. I clearly set it to UNIQUE then why isnt it working?
Your syntax looks good so only explanation that comes to mind is:
You already have a table named users in your database which doesn't have the UNIQUE constraint and since you are using IF NOT EXISTS, that table remains as it is.

Filter python mysql result

I am running a mysql query from python using mysql.connector library as per code below
cnx = mysql.connector.connect(host=mysql_localhost, user=user, password=password, database=database)
cursor = cnx.cursor()
cursor.execute("select * from settings" )
results = cursor.fetchall()
ID, server, port, user, password, temp_min ,temp_max = results[0]
print(user)
cursor.close()
cnx.close()
the result is as follow
u'admin'
I noticed that values stored in the database as varchar display with u''
how can I get the value without the u'' so the desired output is
admin
u means that this is a unicode string. You should read Unicode HOWTO for better understanding.
You can use str() to get rid of the u:
print str(user)
FYI-the u means it is unicode.
The u in front of your variable means that it is a unicode string. Is that really a problem? If you really need to convert it to a regular string you can use str(user).

Categories

Resources