I. Overview
In the user module, the protection of the user's password is usually encrypted. We usually encrypt the password and store it in the database, and when the user logs in, it encrypts the password entered and compares it to the ciphertext stored in the database to verify that the user's password is correct.
At present, MD5 and Bcrypt are more popular. Relatively speaking, Bcrypt is more secure than MD5, but encryption is slower. Second, the use of bcrypt first, you can obtain the source code in the official website http://www.mindrot.org/projects/jBCrypt/and then through ant to compile. After compiling, get Jbcrypt.jar. It is also possible to use the Java file in the source code (itself only one file) without compiling it. Here is a demo of the official website.
Public classBcryptdemo { Public Static voidMain (string[] args) {//Hash A password for the first timeString password = "Testpassword"; String Hashed=bcrypt.hashpw (password, bcrypt.gensalt ()); System.out.println (hashed); //Gensalt ' s log_rounds parameter determines the complexity//the work factor are 2**log_rounds, and the default isString hashed2 = BCRYPT.HASHPW (password, Bcrypt.gensalt (12)); //Check that a unencrypted password matches one that has//previously been hashedString candidate = "Testpassword"; //String candidate = "Wrongtestpassword"; if(BCRYPT.CHECKPW (candidate, hashed)) System.out.println ("It matches"); ElseSystem.out.println ("It does not match"); }}
In this case,
BCrypt.hashpw(password, BCrypt.gensalt())
is the core. The password is encrypted by calling the static method of the Bcrypt class HASHPW. The second parameter is what we usually call salt.
BCrypt.checkpw(candidate, hashed)
The method is to compare the password entered by the user later. Returns true if it can match. Third, add salt if two or more people have the same password, the encryption saves the same result. Break one can break a piece of code. If a user named a can view the database, then he can observe that his password and other people's password encryption results are the same, then, others use and their own is the same password, so that you can use the identity of others to log in. In fact, as long as a little confusion can be prevented, which in the encryption term called "Add salt." In particular, in the original material (user-defined password) to add other components (usually the user's own and constant factors), in order to increase the complexity of the system. When the salt is combined with the user's password, the digest will be able to get a more hidden digest value.
Java encryption via Bcrypt