On receiving a GET request in Flask, I connect to a backend database and send the response. Currently, the username and password of the database are stored in an ini file. What is the best way to encrypt the username and password? Also is it good practice to encrypt the username and password for REST calls ? as I need to decrypt every time on receiving a request
2 Answers
You never store plain password in you database. Instead, you want to store hashes -- the special sum, which can't be decoded, but will produce the same result on same data.
Therefore, you can just apply this function to plain password and compare it to the one on your database
Take a look at bcrypt
module:
https://flask-bcrypt.readthedocs.io/en/latest/
On your register method:
pw_hash = bcrypt.generate_password_hash('some_password')
And then you only store pw_hash in your db
On your login method just extract pw_hash
from db and compare it:
bcrypt.check_password_hash(pw_hash, 'password_from_request') # returns True or False
At the same time, you can store plain username in DB if you want, there's nothing wrong with it

- 850
- 8
- 17
-
1I guess there is a slight misunderstanding. My question is about encrypting the passwords which is used to "connect" to the database not stored in the database. Please suggest. – Chandru Jc Jul 21 '20 at 08:56
On your server, you cannot encrypt the username and password to access your database, otherwise you cannot access it.
Usually, you do not put them in a file, but in an environment variable.
Also see the twelve factor app:
https://en.wikipedia.org/wiki/Twelve-Factor_App_methodology
P.S.: For instance, I use batou
for deployment (similar to Ansible).
The username and password are both encrypted in a gpg file, so I can check them into version control. But of course, when I deploy the app to production, both values need to be un-encrypted.

- 5,366
- 3
- 20
- 37