I have following code, it insert the
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
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.
password_salt(plus your actual application data, of course). Do not save the original password.
To retrieve an account:
password_inputthe alleged user entered into your login form.
username_inputthe user provided.
password_saltfield from that document
password_inputjust like you did before.
password_hashfield 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.