Java Tutorial/Servlet/Authentication
Содержание
A password protected servlet
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.bouncycastle.crypto.Digest;
import org.bouncycastle.crypto.digests.SHA1Digest;
public class PasswordServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("user = " + request.getParameter("user"));
System.out.println("timestamp = " + request.getParameter("timestamp"));
System.out.println("random = " + request.getParameter("random"));
System.out.println("digest = " + request.getParameter("digest"));
String user = request.getParameter("user");
String password = lookupPassword(user);
String timestamp = request.getParameter("timestamp");
String randomNumber = request.getParameter("random");
byte[] userBytes = user.getBytes();
byte[] timestampBytes = HexCodec.hexToBytes(timestamp);
byte[] randomBytes = HexCodec.hexToBytes(randomNumber);
byte[] passwordBytes = password.getBytes();
Digest digest = new SHA1Digest();
digest.update(userBytes, 0, userBytes.length);
digest.update(timestampBytes, 0, timestampBytes.length);
digest.update(randomBytes, 0, randomBytes.length);
digest.update(passwordBytes, 0, passwordBytes.length);
byte[] digestValue = new byte[digest.getDigestSize()];
digest.doFinal(digestValue, 0);
String message = "";
String clientDigest = request.getParameter("digest");
if (isEqual(digestValue, HexCodec.hexToBytes(clientDigest)))
message = "User " + user + " logged in.";
else
message = "Login was unsuccessful.";
response.setContentType("text/plain");
response.setContentLength(message.length());
PrintWriter out = response.getWriter();
out.println(message);
}
private String lookupPassword(String user) {
return "happy8";
}
private boolean isEqual(byte[] one, byte[] two) {
if (one.length != two.length)
return false;
for (int i = 0; i < one.length; i++)
if (one[i] != two[i])
return false;
return true;
}
}
class HexCodec {
private static final char[] kDigits = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a",
"b", "c", "d", "e", "f" };
public static char[] bytesToHex(byte[] raw) {
int length = raw.length;
char[] hex = new char[length * 2];
for (int i = 0; i < length; i++) {
int value = (raw[i] + 256) % 256;
int highIndex = value >> 4;
int lowIndex = value & 0x0f;
hex[i * 2 + 0] = kDigits[highIndex];
hex[i * 2 + 1] = kDigits[lowIndex];
}
return hex;
}
public static byte[] hexToBytes(char[] hex) {
int length = hex.length / 2;
byte[] raw = new byte[length];
for (int i = 0; i < length; i++) {
int high = Character.digit(hex[i * 2], 16);
int low = Character.digit(hex[i * 2 + 1], 16);
int value = (high << 4) | low;
if (value > 127)
value -= 256;
raw[i] = (byte) value;
}
return raw;
}
public static byte[] hexToBytes(String hex) {
return hexToBytes(hex.toCharArray());
}
}
Get Auth Type from Servlet Request
import java.util.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.security.*;
public class MyServlet extends HttpServlet {
public void init(ServletConfig cfg) throws ServletException
{
super.init(cfg);
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<HTML>");
out.println("<HEAD>");
out.println("<TITLE>");
out.println("User Authentication");
out.println("</TITLE>");
out.println("</HEAD>");
out.println("<BODY>");
out.println("<H1>User Authentication</H1>");
String type = request.getAuthType();
out.println("Welcome to this secure page.<BR>");
out.println("Authentication mechanism: " + type + "<BR>");
Principal principal = request.getUserPrincipal();
out.println("Your username is: " + principal.getName() + "<BR>");
out.println("</BODY>");
out.println("</HTML>");
}
}
Servlet Login
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class MyServlet extends HttpServlet {
public void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
res.setContentType("text/html");
PrintWriter out = res.getWriter();
String account = req.getParameter("account");
String password = req.getParameter("password");
String pin = req.getParameter("pin");
if (!allowUser(account, password, pin)) {
out.println("<HTML><HEAD><TITLE>Access Denied</TITLE></HEAD>");
out.println("<BODY>Your login and password are invalid.<BR>");
out.println("You may want to
== Servlet with bouncy castle security package ==
<!-- start source code -->
<source lang="java">
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.bouncycastle.crypto.StreamCipher;
import org.bouncycastle.crypto.engines.RC4Engine;
import org.bouncycastle.crypto.params.KeyParameter;
public class StealthServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String user = request.getParameter("user");
HttpSession session = request.getSession();
StreamCipher inCipher = (StreamCipher) session.getAttribute("inCipher");
StreamCipher outCipher = (StreamCipher) session.getAttribute("outCipher");
if (inCipher == null && outCipher == null) {
byte[] inKey = getInKey(user);
byte[] outKey = getOutKey(user);
inCipher = new RC4Engine();
outCipher = new RC4Engine();
inCipher.init(true, new KeyParameter(inKey));
outCipher.init(false, new KeyParameter(outKey));
session.setAttribute("inCipher", inCipher);
session.setAttribute("outCipher", outCipher);
}
String clientHex = request.getParameter("message");
byte[] clientCiphertext = HexCodec.hexToBytes(clientHex);
byte[] clientDecrypted = new byte[clientCiphertext.length];
inCipher.processBytes(clientCiphertext, 0, clientCiphertext.length, clientDecrypted, 0);
System.out.println("message = " + new String(clientDecrypted));
String message = "Hello, this is StealthServlet.";
byte[] plaintext = message.getBytes();
byte[] ciphertext = new byte[plaintext.length];
outCipher.processBytes(plaintext, 0, plaintext.length, ciphertext, 0);
char[] hexCiphertext = HexCodec.bytesToHex(ciphertext);
response.setContentType("text/plain");
response.setContentLength(hexCiphertext.length);
PrintWriter out = response.getWriter();
out.println(hexCiphertext);
}
private byte[] getInKey(String user) {
return "Outgoing MIDlet key".getBytes();
}
private byte[] getOutKey(String user) {
return "Incoming MIDlet key".getBytes();
}
}
class HexCodec {
private static final char[] kDigits = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a",
"b", "c", "d", "e", "f" };
public static char[] bytesToHex(byte[] raw) {
int length = raw.length;
char[] hex = new char[length * 2];
for (int i = 0; i < length; i++) {
int value = (raw[i] + 256) % 256;
int highIndex = value >> 4;
int lowIndex = value & 0x0f;
hex[i * 2 + 0] = kDigits[highIndex];
hex[i * 2 + 1] = kDigits[lowIndex];
}
return hex;
}
public static byte[] hexToBytes(char[] hex) {
int length = hex.length / 2;
byte[] raw = new byte[length];
for (int i = 0; i < length; i++) {
int high = Character.digit(hex[i * 2], 16);
int low = Character.digit(hex[i * 2 + 1], 16);
int value = (high << 4) | low;
if (value > 127)
value -= 256;
raw[i] = (byte) value;
}
return raw;
}
public static byte[] hexToBytes(String hex) {
return hexToBytes(hex.toCharArray());
}
}
Simple Servlet Example using the getRemoteUser() method.
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MainClass extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException,
java.io.IOException {
res.setContentType("text/html");
java.io.PrintWriter out = res.getWriter();
out.println("<HTML>");
out.println("<HEAD><TITLE>User Example</TITLE></HEAD>");
out.println("<BODY>");
String username = req.getRemoteUser();
if (username == null) {
out.println("Hello. You are not logged in.");
} else if ("Bob".equals(username)) {
out.println("Hello, Bob. Nice to see you again.");
} else {
out.println("Hello, " + username + ".");
}
out.println("</BODY>");
out.println("</HTML>");
out.close();
}
}