我正在实现一个登录系统,其中密码在前端使用 JavaScript 进行加密,然后发送到 Java 后端进行解密。以下是我正在使用的设置:
前端代码(HTML + JavaScript):
这是我使用 CryptoJS 进行加密的客户端实现:
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Login</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.1.1/crypto-js.min.js"></script>
<h1>Login</h1>
<form id="loginForm">
<label for="username">Username:</label>
<input type="text" id="username" name="username" required>
<br><br>
<label for="password">Password:</label>
<input type="password" id="password" name="password" required>
<br><br>
<button type="button" id="submitButton">Submit</button>
</form>
<script>
document.getElementById("submitButton").addEventListener("click", function () {
const username = document.getElementById("username").value;
const password = document.getElementById("password").value;
if (!username || !password) {
alert("Please fill in both fields!");
return;
}
// Secret key for encryption
const secretKey = "mySecretKey12345"; // Ensure this matches on the server-side
// Encrypt the password using CryptoJS
const encryptedPassword = CryptoJS.AES.encrypt(password, secretKey).toString();
// Send the encrypted password to the backend
fetch("http://localhost:8080/login", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
username: username,
password: encryptedPassword
})
})
.then(response => response.json())
.then(data => {
if (data.success) {
alert("Login successful!");
} else {
alert("Invalid credentials!");
}
})
.catch(error => {
console.error("Error:", error);
alert("An error occurred. Please try again.");
});
});
</script>
后端代码(Java):
在后端,我尝试使用 javax.crypto 包解密密码:
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
public class LoginController {
public String decrypt(String encryptedPassword, String secretKey) throws Exception {
byte[] keyBytes = secretKey.getBytes("UTF-8");
SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
byte[] decodedPassword = Base64.getDecoder().decode(encryptedPassword);
byte[] decryptedPasswordBytes = cipher.doFinal(decodedPassword);
return new String(decryptedPasswordBytes, "UTF-8");
}
}
只要使用 HTTPS 就不需要加密密码,因为无论如何你的所有流量都已加密