Frontend-Code:
Code: Select all
function encryptPassword(password) {
const encryptedPassword = CryptoJS.AES.encrypt(password, "SecretKey123").toString();
return encryptedPassword;
}
document.getElementById("loginForm").onsubmit = function (e) {
e.preventDefault();
const passwordField = document.getElementById("password");
passwordField.value = encryptPassword(passwordField.value);
this.submit();
};
Login
Code: Select all
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
@Controller
@RequestMapping("/login")
public class LoginController {
private static final String SECRET_KEY = "SecretKey123"; // Must be 16 chars for AES
@PostMapping
public String login(@RequestParam String username, @RequestParam String password, Model model) {
try {
String decryptedPassword = decrypt(password);
// Validate username and decryptedPassword
// Perform authentication logic
} catch (Exception e) {
model.addAttribute("error", "Invalid encryption");
return "login";
}
return "home";
}
private String decrypt(String encryptedPassword) throws Exception {
SecretKeySpec secretKey = new SecretKeySpec(SECRET_KEY.getBytes(), "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, secretKey);
byte[] decodedBytes = Base64.getDecoder().decode(encryptedPassword);
byte[] original = cipher.doFinal(decodedBytes);
return new String(original);
}
}