Table of Contents
1: Introduction to the problem
Two: Solution
2.1: First Encryption
3.2: Second encryption
3: Code implementation
3.1: First encryption
Home Java javaTutorial How to achieve secure login with Java double MD5 encryption

How to achieve secure login with Java double MD5 encryption

May 17, 2023 pm 05:31 PM
java md5

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 || '操作失败')
    }
}
Copy after login

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("添加失败!");
}
Copy after login

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
}
Copy after login

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);
}
Copy after login

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 of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

PHP vs. Python: Core Features and Functionality PHP vs. Python: Core Features and Functionality Apr 13, 2025 am 12:16 AM

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

Create the Future: Java Programming for Absolute Beginners Create the Future: Java Programming for Absolute Beginners Oct 13, 2024 pm 01:32 PM

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.

PHP: The Foundation of Many Websites PHP: The Foundation of Many Websites Apr 13, 2025 am 12:07 AM

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.

See all articles