Home  >  Article  >  Java  >  How to achieve secure login with Java double MD5 encryption

How to achieve secure login with Java double MD5 encryption

WBOY
WBOYforward
2023-05-17 17:31:351328browse

1: Introduction to the problem

Decrypt the password stored in the database:

How to achieve secure login with Java double MD5 encryption

How to achieve secure login with Java double MD5 encryption

You can see I was surprised to successfully decrypt my password, because we all know that the MD5 algorithm is irreversible because it is a hash function and uses a hash algorithm. During the calculation process, part of the original information is is lost. So why can my password be decrypted on the website?

After some searching, I found that the decryption principle of the online decryption tool is very simple. The principle is to collect simple passwords commonly used by users to form a password dictionary, and then encrypt the passwords in the dictionary with MD5 and store them. , during the so-called "decryption", the ciphertext of the real user password encryption is compared with the stored password. If the ciphertext exists in the dictionary, it can be "decrypted". Therefore, simply using MD5 to encrypt user passwords is not safe. When we set passwords, we usually have complexity detection. For example, the password must contain English numbers and so on, just for security reasons.

After knowing the decryption principle, we try a more complex password to see if it can be "decrypted". First, encrypt the password "qweasd666":

How to achieve secure login with Java double MD5 encryption

After encryption, we select 32-bit lowercase ciphertext for decryption:

How to achieve secure login with Java double MD5 encryption

Failure to decrypt indicates that the principle is to collect commonly used ciphertexts for matching and cracking. Since the "qweasd666" password cannot be cracked, it should be safe and you can all use this password (doge).

Getting back to the subject, this website successfully cracked my carefully set password, which made me feel very insecure, and I felt that I was losing face. I must improve my login security level. .

In addition to the decryption operation mentioned above, another big problem is that when the front end transmits data, http uses plain text transmission. If the transmission data packet is intercepted, then even if your back end No matter how complex the encryption algorithm is, your password will be known to others.

Two: Solution

2.1: First Encryption

After finding the problem, we can prescribe the right medicine. First of all, I think we need to solve the problem of http plaintext transmission. , because this is the highest risk. Passwords can be captured by ordinary packet capture. Isn't this a scary thing? Since there are security issues in plain text transmission, we can ensure transmission security through encryption

I still use the MD5 encryption scheme, but add a fixed salt value before encrypting the password. salt? Is it adding salt? In fact, it’s almost the same. It’s better to say it’s adding some “seasonings”. The basic idea is this: when a user provides a password for the first time (usually when registering), the program sprinkles some "sauce" into the password. In order to reduce development pressure, this seasoning is the same for every user. Then hash again. This will prevent the leakage of clear text passwords during transmission.

2.2: Second encryption

Note that what I mentioned above is to prevent the leakage of plaintext passwords, but this does not mean that the ciphertext will not be leaked. If a hacker intercepts your password transmitted through http The encrypted password, or the database leak causes the encrypted password to be stolen by a hacker. The hacker obtains the front-end fixed salt value by parsing the front-end js file. Then the hacker may be able to perform a reverse query through the rainbow table to obtain the original password. At this time, the importance of secondary encryption comes out. The principle of secondary encryption is to combine the encrypted password passed from the front end with a random Salt value and then encrypt it (note that this time it is random). The salt value will It is randomly generated when the user logs in and stored in the database.

At this time, you may have the same doubt as I did at the beginning, that is, you have saved the random salt value in the database, so if the database leaks, what will your random salt value do? Wouldn't it be possible for a hacker to obtain the password by decrypting the encrypted data and removing the salt value? Yes, it is possible for a hacker to obtain the password through such means, but only if he can decrypt it. What you need to know is that MD5 cannot be cracked directly and can only be decrypted through the exhaustive method. Even if a hacker obtains the encrypted password in the database, but does not know the back-end encryption process, he will not be able to parse it. Even if the hacker knows the encryption process at the same time, due to the secondary salting and secondary encryption, the ciphertext at this time is difficult to It is difficult to parse out. As the complexity of encrypted data increases, the cost of cracking increases exponentially. In the face of such a huge cost, I believe no hacker is willing to try it. Of course, salt does not have to be added at the front or at the end. It can also be inserted in the middle, separately, or in reverse order. It can be flexibly adjusted during program design, which can exponentially increase the difficulty of cracking.

2.3: Specific implementation

2.3.1: User registration

  • The front end performs md5 encryption on the password entered by the user (fixed salt)

  • Pass the encrypted password to the backend

  • The backend randomly generates a salt

  • Use Generate salt to encrypt the password passed from the front end, and then save the encrypted password and salt to the db

2.3.2: User login

  • The front end performs md5 encryption on the password entered by the user (fixed salt)

  • Passes the encrypted password to the back end

  • The backend uses the user account to retrieve the user information

  • The backend performs md5 encryption on the encrypted password (removing the salt), and then compares it with the password stored in the database

  • If the match matches, the login is successful, otherwise the login fails

3: Code implementation

3.1: First encryption

3.1 .1: Front-end

const params = {
    ...this.ruleForm,
    sex: this.ruleForm.sex === '女' ? '0' : '1',
    //设置密码加密(加上固定salt值)
    password: md5(this.ruleForm.password + this.salt)
}
addEmployee(params).then(res => {
    if (res.code === 1) {
        this.$message.success('员工添加成功!')
        if (!st) {
            this.goBack()
        } else {
            this.ruleForm = {
                username: '',
                'name': '',
                'phone': '',
                password: '',
                // 'rePassword': '',/
                'sex': '男',
                'idNumber': ''
            }
        }
    } else {
        this.$message.error(res.msg || '操作失败')
    }
}

3.1.2: Back-end

/**
* 添加员工
*/
@PostMapping
public R<String> save(@RequestBody Employee employee){
    //生成随机salt值
    String salt = RandomStringUtils.randomAlphanumeric(5);
    //设置随机盐值
    employee.setSalt(salt);
    //设置密码二次加密
    employee.setPassword(DigestUtils.md5DigestAsHex((salt + employee.getPassword()).getBytes()));
 
    boolean save = employeeService.save(employee);
    if(save){
        return R.success("添加成功!");
    }
    return R.error("添加失败!");
}

3.2: Second encryption

3.2.1: Front-end

const params = {
    ...this.loginForm,
    //登录密码加上固定盐值后发送
    password: md5(this.loginForm.password + this.salt),
}
let res = await loginApi(params)
if (String(res.code) === &#39;1&#39;) {
    localStorage.setItem(&#39;userInfo&#39;, JSON.stringify(res.data))
    window.location.href = &#39;/backend/index.html&#39;
} else {
    this.$message.error(res.msg)
    this.loading = false
}

3.2. 2: Backend

/**
 * 员工登录
 */
@PostMapping("/login")
public R<Employee> login(HttpServletRequest request, @RequestBody Employee employee){
    //1.获取传输过来的加密后的密码值
    String encryPassword = employee.getPassword();
 
    //2.从数据库中获取用户信息
    LambdaQueryWrapper<Employee> lqw = new LambdaQueryWrapper<>();
    lqw.eq(Employee::getUsername,employee.getUsername());
    Employee emp = employeeService.getOne(lqw);
 
    //3.如果没有查询到则返回登陆失败查询结果
    if(emp == null){
        return R.error("没有查询到该用户信息!");
    }
 
    //4.获取注册时保存的随机盐值
    String salt = emp.getSalt();
 
    //5.将页面提交的密码password进行md5二次加密
    String password = DigestUtils.md5DigestAsHex((salt + encryPassword).getBytes());
 
    //6.密码比对,如果不一致则返回登陆失败结果
    if(!emp.getPassword().equals(password)){
        return R.error("密码错误!");
    }
 
    //7.查看员工状态是否可用
    if(emp.getStatus() == 0){
        return R.error("该员工已被禁用!");
    }
    
    //8.登录成功,将员工id存入Session对象并返回登录成功结果
    request.getSession().setAttribute("employee",emp.getId());
    return R.success(emp);
}

The above is the detailed content of How to achieve secure login with Java double MD5 encryption. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete