vue前端密码加密,springboot后端密码解密
    		       		warning:
    		            这篇文章距离上次修改已过449天,其中的内容可能已经有所变动。
    		        
        		                
                在Vue前端进行密码加密,并在Spring Boot后端进行解密,你可以使用JavaScript的CryptoJS库进行加密,并在Spring Boot中使用Java的javax.crypto库进行解密。
- 在Vue前端使用CryptoJS进行加密:
 
首先,需要安装CryptoJS:
npm install crypto-js然后,在你的Vue组件中使用CryptoJS进行加密:
import CryptoJS from 'crypto-js'
 
export default {
  methods: {
    encryptPassword(password) {
      const secretKey = "your-secret-key" // 密钥应该是安全的,不应该在前端暴露
      return CryptoJS.AES.encrypt(password, secretKey).toString()
    }
  }
}- 在Spring Boot后端进行解密:
 
首先,在你的Spring Boot项目中添加依赖(通常已经包含):
<!-- Add this if you don't have it already -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>然后,在你的Controller中使用Java的Crypto库进行解密:
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
 
@RestController
public class UserController {
 
    private static final String SECRET_KEY = "your-secret-key"; // 与前端使用的密钥必须一致
 
    @PostMapping("/login")
    public String login(@RequestParam String encryptedPassword) {
        String password = decryptPassword(encryptedPassword);
        // 在这里进行密码验证等逻辑
        return "Login successful";
    }
 
    private String decryptPassword(String encryptedPassword) {
        try {
            byte[] keyBytes = SECRET_KEY.getBytes("UTF-8");
            SecretKeySpec secretKey = new SecretKeySpec(keyBytes, "AES");
            Cipher cipher = Cipher.getInstance("AES");
            cipher.init(Cipher.DECRYPT_MODE, secretKey);
            byte[] original = cipher.doFinal(Base64.decodeBase64(encryptedPassword));
            return new String(original);
        } catch (Exception e) {
            throw new RuntimeException("Error decrypting password", e);
        }
    }
}请确保你的密钥your-secret-key在前端和后端保持一致,并且要保护它,不要在前端代码中暴露。这个例子使用了AES加密,你可以根据需要选择其他加密算法,但是密钥必须对前端和后端保持一致。
评论已关闭