Advertisement
klebermo

Untitled

Jul 14th, 2023
1,382
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.32 KB | None | 0 0
  1. package servlet;
  2.  
  3. import java.io.IOException;
  4. import java.io.InputStream;
  5. import java.io.PrintWriter;
  6. import java.nio.charset.StandardCharsets;
  7. import java.security.PublicKey;
  8. import java.util.UUID;
  9.  
  10. import javax.servlet.ServletException;
  11. import javax.servlet.annotation.WebServlet;
  12. import javax.servlet.http.Cookie;
  13. import javax.servlet.http.HttpServlet;
  14. import javax.servlet.http.HttpServletRequest;
  15. import javax.servlet.http.HttpServletResponse;
  16.  
  17. import util.RSASignature;
  18.  
  19. @WebServlet(name = "Login", urlPatterns = "/login")
  20. public class Login extends HttpServlet {
  21.     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  22.         String token = request.getParameter("token");
  23.         PrintWriter out = response.getWriter();
  24.  
  25.         if (token == null) {
  26.             out.println("fail - no token");
  27.             out.flush();
  28.             return;
  29.         }
  30.  
  31.         InputStream publicKeyInputStream = getClass().getClassLoader().getResourceAsStream("key_rsa.pub");
  32.         if (publicKeyInputStream == null) {
  33.             out.println("fail - no public key");
  34.             out.flush();
  35.             return;
  36.         }
  37.         String publicKeyString = new String(publicKeyInputStream.readAllBytes(), StandardCharsets.UTF_8);
  38.  
  39.         try {
  40.             PublicKey publicKey = util.RSAKeyGenerator.getPublicKey(publicKeyString);
  41.             boolean isVerified = RSASignature.verify(request.getRemoteAddr(), token, publicKey);
  42.  
  43.             if(isVerified) {
  44.                 UUID uuid = UUID.randomUUID();
  45.                 String plainUUID = uuid.toString();
  46.  
  47.                 Cookie cookie = new Cookie("uuid", plainUUID);
  48.                 cookie.setHttpOnly(true);
  49.                 cookie.setSecure(true);
  50.                 cookie.setPath("/");
  51.                 response.addCookie(cookie);
  52.  
  53.                 request.getSession().setAttribute("uuid", uuid);
  54.                 out.println("");
  55.                 out.flush();
  56.                 return;
  57.             } else {
  58.                 out.println("fail - invalid token");
  59.                 out.flush();
  60.                 return;
  61.             }
  62.         } catch (Exception e) {
  63.             e.printStackTrace();
  64.             out.println("fail - " + e.getLocalizedMessage());
  65.             out.flush();
  66.         }
  67.     }
  68. }
  69.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement