In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-20 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Network Security >
Share
Shulou(Shulou.com)05/31 Report--
What are the two methods of password encryption in Spring Boot? in order to solve this problem, this article introduces the corresponding analysis and solution in detail, hoping to help more partners who want to solve this problem to find a more simple and feasible method.
First of all, the password cannot be decrypted. Don't ask Songge how to decrypt the password in the micro-personnel project.
The password cannot be decrypted, or to ensure the security of the system. Today, Brother Song will come to talk to you about how to deal with passwords in order to ensure the security of our system to the greatest extent.
1. Why is it encrypted?
On December 21, 2011, someone made public on the Internet a database of 6 million CSDN users, all stored in clear text, including user names, passwords and registered mailboxes. After the incident, CSDN issued a statement on Weibo, the official website and other channels, explaining that the database was used for backup in 2009 and that the database had been reported to the police for an unknown reason, and then sent a public letter of apology on the official website. In the next ten days, Jinshan, NetEase, JD.com, Dangdang, Sina and other companies were involved in this incident. The most shocking thing in the whole incident is that CSDN stores users' passwords in plaintext. Because many users share a password on multiple websites, the disclosure of a website password will cause great security risks. With so many lessons from the past, when we do the system now, the passwords have to be encrypted.
This leak also left some interesting things, especially for the majority of programmers to set passwords. People found some interesting passwords in the files leaked by CSDN, such as the following:
The Chinese interpretation of the ppnn13%dkstFeb.1st password is: beautiful posture and light manner is exactly 13 years old, just like a cardamom flower in bud at the beginning of February.
The Chinese interpretation of the csbt34.ydhl12s password is: three or four points of blue moss on the pool and one or two orioles at the bottom of the leaves.
...
To name but a few, you will find that the humanistic literacy of many programmers is very high, which is amazing.
two。 Encryption scheme
Password encryption we generally use hash functions, also known as hash algorithms, hash functions, which is a way to create digital "fingerprints" from any data.
The hash function compresses the message or data into a summary, reducing the amount of data, fixing the format of the data, and then scrambling and mixing the data to recreate a hash value. Hash values are usually represented by a short string of random letters and numbers. Good hash functions rarely have hash conflicts in the input field. In hash tables and data processing, not suppressing conflicts to distinguish data will make database records more difficult to find.
Our commonly used hash functions are MD5 message digest algorithm and secure hash algorithm (Secure Hash Algorithm).
But only the use of hash function is not enough, simply use hash function, if two users password plaintext is the same, the generated ciphertext will be the same, which increases the risk of password leakage.
In order to increase the security of the password, salt is generally needed in the process of password encryption. The so-called salt can be a random number or a user name. After adding salt, the password ciphertext generated by users with the same plaintext is not the same, which can greatly improve the security of the password.
The traditional method of adding salt requires a special field in the database to record the salt value. This field may be a user name field (because the user name is unique), or it may be a special field to record the salt value.
Spring Security provides a variety of password encryption schemes. BCryptPasswordEncoder,BCryptPasswordEncoder is officially recommended to use the BCrypt strong hash function. Developers can choose to provide strength and SecureRandom instances when using it. The larger the strength, the more iterations of the key, and the number of iterations of the key is 2 ^ seconds. The value of strength is between 4 and 31, and the default is 10.
Unlike in Shiro, where you need to process your own password and add salt, in Spring Security, BCryptPasswordEncoder brings its own salt, which is very convenient to deal with.
3. Practice
3.1 codec encryption
Commons-codec is an open source project on Apache, which can be used to encrypt passwords easily. Brother Song adopted this scheme (https://github.com/lenve/VBlog)) in the V tribe project. Before Spring Security launched BCryptPasswordEncoder, commons-codec was still a common solution.
So, first of all, let me introduce you to the usage of commons-codec.
First, we need to introduce the dependency of commons-codec:
Commons-codec commons-codec 1.11
Then customize a PasswordEncoder:
@ Component public class MyPasswordEncoder implements PasswordEncoder {@ Override public String encode (CharSequence rawPassword) {return DigestUtils.md5DigestAsHex (rawPassword.toString (). GetBytes ());} @ Override public boolean matches (CharSequence rawPassword, String encodedPassword) {return encodedPassword.equals (DigestUtils.md5DigestAsHex (rawPassword.toString (). GetBytes ();}}
In Spring Security, PasswordEncoder is specially used to handle password encryption and comparison. If we customize MyPasswordEncoder and implement the PasswordEncoder interface, we also need to implement two methods in this interface:
The encode method means to encrypt the password. The parameter rawPassword is the plaintext password you passed in, and the encrypted ciphertext is returned. The encryption scheme here uses MD5.
The matches method indicates that the password is compared, and the parameter rawPassword is equivalent to the password passed in when the user logs in, and encodedPassword is equivalent to the encrypted password (queried from the database).
Finally, remember to mark MyPasswordEncoder as a component in the Spring container with the @ Component annotation.
In this way, when the user logs in, the matches method is automatically called for password comparison.
Of course, after using MyPasswordEncoder, when a user registers, the password needs to be encrypted and stored in the database as follows:
Public int reg (User user) {. / / insert the user, encrypt the password before inserting user.setPassword (passwordEncoder.encode (user.getPassword ()); result = userMapper.reg (user);...}
In fact, it is very simple, is to call the encode method to encrypt the password. You can refer to the V tribe (https://github.com/lenve/VBlog)) for the complete code, so I won't repeat it here.
3.2 BCryptPasswordEncoder encryption
But defining PasswordEncoder yourself is still a bit of a hassle, especially when dealing with password salting.
So BCryptPasswordEncoder is provided in Spring Security, which makes it very easy to encrypt passwords and add salt. You only need to provide an example of BCryptPasswordEncoder, a Bean. Micro personnel uses this solution (https://github.com/lenve/vhr), as shown below:
@ Bean PasswordEncoder passwordEncoder () {return new BCryptPasswordEncoder (10);}
The parameter 10 passed in when creating the BCryptPasswordEncoder is strength, that is, the number of iterations of the key (or it may not be configured, the default is 10). At the same time, the password of the configured memory user is no longer 123, as follows:
Auth.inMemoryAuthentication () .withUser ("admin") .password ("$2a$10 $RMuFXGQ5AtH4wOvkUqyvuecpqUSeoxZYqilXzbz50dceRsga.WYiq") .password ("ADMIN", "USER") .and () .withUser ("sang") .password ("$2a$10 $eUHbAOMq4bpxTvOVz33LIehLe3fu6NwqC9tdOcxJXEhyZ4simqXTC") .password ("USER")
The password here is the password encrypted with BCryptPasswordEncoder. Although the encrypted passwords of admin and sang are not the same, the plaintext is 123. After the configuration is complete, you can log in using admin/123 or sang/123.
This case uses a user configured in memory. In general, the user information is stored in the database, so the password needs to be encrypted when the user registers, as follows:
@ Service public class RegService {public int reg (String username, String password) {BCryptPasswordEncoder encoder = new BCryptPasswordEncoder (10); String encodePasswod = encoder.encode (password); return saveToDb (username, encodePasswod);}}
After passing the password from the front end, the user encrypts the password by calling the encode method in the BCryptPasswordEncoder instance. After the encryption is completed, the ciphertext is stored in the database.
4. Analysis of source code
Finally, let's take a look at PasswordEncoder.
Public interface PasswordEncoder {String encode (CharSequence rawPassword); boolean matches (CharSequence rawPassword, String encodedPassword); default boolean upgradeEncoding (String encodedPassword) {return false;}}
The encode method is used to encrypt passwords.
The matches method is used to compare passwords.
UpgradeEncoding indicates whether the password needs to be re-encrypted to make the password more secure, which defaults to false.
Spring Security provides many implementations for PasswordEncoder:
But to be honest, since BCryptPasswordEncoder, we have paid little attention to other implementation classes.
The encode method in PasswordEncoder is called manually when the user registers.
The matches method is called by the system and is called by default in the DaoAuthenticationProvider#additionalAuthenticationChecks method.
Protected void additionalAuthenticationChecks (UserDetails userDetails, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {if (authentication.getCredentials () = = null) {logger.debug ("Authentication failed: no credentials provided"); throw new BadCredentialsException (messages.getMessage ("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"));} String presentedPassword = authentication.getCredentials (). ToString (); if (! passwordEncoder.matches (presentedPassword, userDetails.getPassword () {logger.debug ("Authentication failed: password does not match stored value") Throw new BadCredentialsException (messages.getMessage ("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials");}}
As you can see, password alignment is done through the passwordEncoder.matches method.
The answers to the questions about the two methods of password encryption in Spring Boot are shared here. I hope the above content can be of some help to you. If you still have a lot of doubts to be solved, you can follow the industry information channel for more related knowledge.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.