How to authenticate hashed(sha1) password in Python? - python

I am trying to retrieve the password and authenticate from the Galaxy framework. I successfully retrieve the password it's in hashed(sha1) format. How do I authenticate this with the password input by the user? My first guess would be converting hashed(sha1) into normal string and authenticating. Is that possible? If it is, how can I convert it into the string?

You can't. It would be extremely hard to get the plain text from its hash code, that's exactly the reason why we had invented hash. Try the opposite: convert the plain text to hash and then compare.
How to convert:
import hashlib
s = "plain"
h = hashlib.sha1(s).hexdigest()

... My first guess would be converting hashed(sha1) into normal string ...
That's what cryptographic hash functions try to prevent (among other things) - this property is called pre-image resistance.
The basic steps would be the other way around:
take user input
compute hash over user input
compare hashed user input to stored credentials/hashes

Related

How can I code a secure authentication system in Python?

I want to make a authentication system with a simple key (string). If the key is correctly inputed, start the program.
The problem is, that I have no idea how I code it so the program checks if the key is correct without a way seeing in as a user in the code.
Can someone help me?
An easy way of using secure passwords/hashes and authentication. Adapt this into your system and work with that as a base:
Generate a password:
>>> import b<rypt
>>> bcrypt.genpw(b"admin", salt=bcrypt.gensalt())
b'$2b$12$VQ/egr55zwN28OU8baZXlu.gLA3HjVJw5O2teDDmwcXyp3k1TR4dG
Store the output of bcrypt.genpw() in any kind of data storage (without the leading b and enclosing single quotes (').
Check password:
import getpass
import bcrypt
# Get your bcrypt hashed pw from any kind of data storage.
pwhash = open("hash.txt", "r", encoding="utf-8").strip()
# Read the users password/key/whatever
password = getpass.getpass("Enter your password: ")
# Check if entered password/key/whatever matches stored hash
authenticated = bcrypt.checkpw(password.encode(), pwhash.encode()
if authenticated:
print("You're autenticated!")
do_privileged_stuff(...)
else:
print("You're not allowed to be here!")
A fun, secure but maybe not very user-friendly addon to security would be MFA/2FA using totp/hotp algorithms (see here).

How can I store a dictionary in a file which I can encrypt?

I'm pretty new to Python and programming in general and am currently working on a little password manager. Thus far I have a script which can encode a txt file using the cryptography library. I am now wondering if it is possible to store information on a website or an account with a corresponding Password in the txt file or if I need to use something else than a txt file. What would you recommend?
The easiest way to do that is convert that dict to json and encrypt the string result.
It's easy convert to dict too. What I advise you to do if you're using this only for auth, is save like a key value store. Example:
{
"<user>": "<password>",
"<user2>" : "<password2>"
}
On this datastruct the code will be always O(1).
Yes, you can use a text file. That is not a problem. The text file will contain encrypted text.
Depending upon how secure and how many unique passwords, you probably want a salted encryption techique.
I would recommend passlib.
I will give as an example some code I recently made, and explain it (although I am not a cryptography expert):
from passlib.context import CryptContext
CRYPTO_CTX = CryptContext(schemes=["bcrypt"], deprecated="auto") # This means only use `'bcrypt'`.
#app.post("/login")
def login_user(user, db):
db_user = crud.get_user_by_username(db, username=user.username)
if db_user is None:
raise HTTPException(
status_code=400, detail=f"No username {user.username} found."
)
if not CRYPTO_CTX.verify(user.password, db_user.hashed_password): ## This is the essential portion
raise HTTPException(status_code=400, detail=f"Incorrect password.")
db_user = crud.update_user(db, db_user, {"last_visit": datetime.now(timezone.utc)})
return {"user": db_user}
This code is, as I said, for a website, and it is using FastAPI. I have removed some stuff for clarity while hopefully keeping enough context. Here is the breakdown:
You need to make a "Cryptographic context", which will know which hashing scheme(s) to use.
In my case, I am only using and allowing 'bcrypt', a best practice choice for 2020 (but you can choose others for flexibility).
I then create a '/login' web route, which is a URI endpoint that triggers a function.
That function receives user information from an HTTP POST that an end user submitted (and a database session).
The user is then searched on the database backend. Presuming she is found, the submitted password in the POST is compared to the password in the database, but that password is cryptographically protected.
Let's zoom in on that comparison:
if not CRYPTO_CTX.verify(user.password, db_user.hashed_password):
We are providing a plain text string (user.password) and a hashed string (db_user.hashed_password) to our CRYPTO_CTXs verify method. That is all that is needed, since the passlib library is doing all the heavy lifting.
How was the password encrypted? That was just as easy:
hashed_password = CRYPTO_CTX.hash(user.password)
And this does not just encrypt the password, it also salts it. In short, this means that if somehow the encryption were hacked, it would only work for that one entry. With salting, it's a two-step encryption process:
Create a password. Eg, 'Elderberries'
Add a salt to it: 'Elderberries34(*&#arst##!'
Hash that entire thing: 'B4B6603ABC670967E99C7E7F1389E40CD16E78AD38EB1468EC2AA1E62B8BED3A'

Hashing Password in .py file

how i said in the title, i want the password to be hashed when is saved. Its possible with this?
def __OnClickSaveLoginButton(self):
id = self.idEditLine.GetText()
pwd = self.pwdEditLine.GetText()
if (len(id) == 0 or len(pwd) == 0):
self.PopupNotifyMessage("ID and Password required",self.SetIDEditLineFocus)
return
file_object = open("account.cfg", "w")
file_object.write(id+"\n"+pwd)
self.PopupNotifyMessage("Saved.",self.SetIDEditLineFocus)
file_object.close()
You'll want to use the python hashlib. An example could look something like this:
import hashlib
def valid_password(userid, password):
user = get_user(userid)
pw_hash = hashlib.sha256(password).hexdigest()
if user.hash == pw_hash:
return True
return False
Also I recommend reviewing some password storage best practices noted in this SO
Edit: I used sh256 in this example, but that is more useful as a message digest. A better use would be hashlib.pbkdf2_hmac or another key derivation function. There is a good write up here.
If you're going to hash passwords in Python, as nudies mentioned, hashlib.pbkdf2_hmac is correct.
If you want to save the result in Base64, that's a reasonable option, as it turns it into a character string.
Just remember you also have to store the salt and the number of iterations; choose as high a number of iterations as your CPU can stand.
DO NOT request more bytes of output than the native hash function can support; for instance, PBKDF2-HMAC-SHA-512 caps out at 64 bytes for password hashing; the others less.
I have a fully working example at my github repository, including test vectors for all the normal SHA variants, of which the core piece is
import argparse,hashlib,base64,timeit
BinaryOutput = hashlib.pbkdf2_hmac('sha512',args.password, args.salt, args.iterations, args.outputBytes)
BinaryOutput.encode('base64')

Python with etc/Shadow

so I'm writing this program that needs to check the password hash in etc/shadow and compare it to the password the user entered. I tried encrypting the password with hashlib.sha512, but the result was not the same. I think it's salted some how, but I don't know if it uses a universal salt or how I can get the salt each time.
tldr; I need a way for a user to enter a password, then have the program hash it and check it against the etc/shadow. Any ideas?
Try this https://pypi.python.org/pypi/pam . First link in google by python pam.
Look at distribution package manager for python-pam if exists. Else install with pip or easy_install.
Small example:
>>> import pam
>>> pam.authenticate('fred', 'fredspassword')
False
>>> import crypt
>>> line = 'bob:$1$qda8YAO9$rBiov9uVJlH1/97cbcyEt.:15965:0:99999:7:::'
>>> encript = line.split(':')[1]
>>> encript
--> '$1$qda8YAO9$rBiov9uVJlH1/97cbcyEt.'
>>> i = encript.rfind('$')
>>> salt = encript[:i]
>>> salt
--> '$1$qda8YAO9'
>>> crypt.crypt('bob_password',salt)
--> '$1$qda8YAO9$rBiov9uVJlH1/97cbcyEt.'
>>> encript
--> '$1$qda8YAO9$rBiov9uVJlH1/97cbcyEt.'
The passwd field is not just a SHA-512 hash of the password.*
This is explained in the crypt manpage. The format is $id$salt$hash, where id specifies the hash method (1 for MD5, 2a for Blowfish, 5 for SHA-256, 6 for SHA-512), salt specifies the salt to use with that algorithm, and hash specifies what the result should be.
As the manpage implies, you can actually pass the whole $id$salt$ to the crypt function in place of the salt, and it will automatically use the appropriate algorithm. This wouldn't be too hard to do via, say, ctypes.
At any rate, what you're doing is almost certainly a bad idea. You'll need to run as root in order to have access to /etc/shadow, and you'll need to simulate more than just password verification if you actually want to verify that the user can log in, and of course you'll need to handle secure input and make sure you don't end up saving the password in plaintext somewhere and so on. It's a lot simpler and safer to just let PAM do the work for you.
* I believe that in theory, it can be—if it doesn't start with a $ it's interpreted as some legacy format… presumably meaning it's interpreted as POSIX crypt using the DES algorithm.

django, python and link encryption

I need to arrange some kind of encrpytion for generating user specific links. Users will be clicking this link and at some other view, related link with the crypted string will be decrypted and result will be returned.
For this, I need some kind of encryption function that consumes a number(or a string) that is the primary key of my selected item that is bound to the user account, also consuming some kind of seed and generating encryption code that will be decrypted at some other page.
so something like this
my_items_pk = 36 #primary key of an item
seed = "rsdjk324j23423j4j2" #some string for crypting
encrypted_string = encrypt(my_items_pk,seed)
#generates some crypted string such as "dsaj2j213jasas452k41k"
and at another page:
decrypt_input = encrypt(decypt,seed)
print decrypt_input
#gives 36
I want my "seed" to be some kind of primary variable (not some class) for this purpose (ie some number or string).
How can I achieve this under python and django ?
There are no encryption algorithms, per se, built in to Python. However, you might want to look at the Python Cryptography Toolkit (PyCrypt). I've only tinkered with it, but it's referenced in Python's documentation on cryptographic services. Here's an example of how you could encrypt a string with AES using PyCrypt:
from Crypto.Cipher import AES
from urllib import quote
# Note that for AES the key length must be either 16, 24, or 32 bytes
encryption_obj = AES.new('abcdefghijklmnop')
plain = "Testing"
# The plaintext must be a multiple of 16 bytes (for AES), so here we pad it
# with spaces if necessary.
mismatch = len(plain) % 16
if mismatch != 0:
padding = (16 - mismatch) * ' '
plain += padding
ciph = encryption_obj.encrypt(plain)
# Finally, to make the encrypted string safe to use in a URL we quote it
quoted_ciph = quote(ciph)
You would then make this part of your URL, perhaps as part of a GET request.
To decrypt, just reverse the process; assuming that encryption_obj is created as above, and that you've retrieved the relevant part of the URL, this would do it:
from urllib import unquote
# We've already created encryption_object as shown above
ciph = unquote(quoted_ciph)
plain = encryption_obj.decrypt(ciph)
You also might consider a different approach: one simple method would be to hash the primary key (with a salt, if you wish) and store the hash and pk in your database. Give the user the hash as part of their link, and when they return and present the hash, look up the corresponding pk and return the appropriate object. (If you want to go this route, check out the built-in library hashlib.)
As an example, you'd have something like this defined in models.py:
class Pk_lookup(models.Model):
# since we're using sha256, set the max_length of this field to 32
hashed_pk = models.CharField(primary_key=True, max_length=32)
key = models.IntegerField()
And you'd generate the hash in a view using something like the following:
import hashlib
import Pk_lookup
hash = hashlib.sha256()
hash.update(str(pk)) # pk has been defined previously
pk_digest = hash.digest()
lookup = Pk_lookup(hashed_pk=pk_digest,key=pk)
lookup.save()
Note that you'd have to quote this version as well; if you prefer, you can use hexdigest() instead of digest (you wouldn't have to quote the resulting string), but you'll have to adjust the length of the field to 64.
Django has features for this now. See https://docs.djangoproject.com/en/dev/topics/signing/
Quoting that page:
"Django provides both a low-level API for signing values and a high-level API for setting and reading signed cookies, one of the most common uses of signing in Web applications.
You may also find signing useful for the following:
Generating “recover my account” URLs for sending to users who have lost their password.
Ensuring data stored in hidden form fields has not been tampered with.
Generating one-time secret URLs for allowing temporary access to a protected resource, for - example a downloadable file that a user has paid for."

Categories

Resources