I have following code, it insert the userName
and password
into database
but the password is stored in plain text format. I mean when I'll look into the db I can see the inserted password.
I want to store password
in encrypted
format
MongoClient client = new MongoClient("localhost",27017);
DB db = client.getDB("Test");
DBCollection collection = db.getCollection("EncryptionDemo");
BasicDBObject documentDetail = new BasicDBObject();
documentDetail.put("userName", "admin12");
documentDetail.put("password", "12345");
collection.insert(documentDetail);
How can I achieve this?
According to the conversation in the comments, what you mean is hashing passwords, not encrypting passwords. You usually would do this with a salt to prevent a rainbow table attack. Storing passwords as salted hashes is the best practice standard when it comes to storing passwords in databases.
As of version 3.2, MongoDB has no native support for password hashing like some SQL databases provide, so you will have to implement it in Java.
To generate a new account or change the password of an existing account:
java.security.SecureRandom
. This class works just like the standard random number generator java.util.Random
(it's a subclass) but trades performance for a much higher level of non-predictability which is required for a security-relevant context.javax.crypto.SecretKeyFactory
class.username
, password_hash
and password_salt
(plus your actual application data, of course). Do not save the original password.To retrieve an account:
username_input
and password_input
the alleged user entered into your login form.username
matches the username_input
the user provided.password_salt
field from that documentpassword_salt
and password_input
just like you did before.password_hash
field of the document. When it matches, the user entered the correct password.You could alternatively only retrieve the password_hash and password_salt fields of the document and not load the rest before the user is authenticated, but I would assume that in the real world it will cause more load than it would save. Successful logins will usually greatly outnumber the unsuccessful ones, unless you have an attacker who tries to brute-force an account. And in that case you would block the attacker with fail2ban or another login-limiting mechanism.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With