MD5签署HttpServletResponse

Pab*_*dez 6 java hash servlets

我正在寻找一种方法来检查a的内容,HttpServletResponse用MD5哈希对它们进行签名.

伪代码可能看起来像这样

process(Response response, Request request){

defaultProcessingFor(response,request);

dispatcher.handle(response,request);

// Here I want to read the contents of the Response object (now filled with data) to create a MD5 hash with them and add it to a header.
}
Run Code Online (Sandbox Code Playgroud)

那可能吗?

Bal*_*usC 6

是的,这是可能的.您需要在帮助下装饰响应,HttpServletResponseWrapper其中您将ServletOutputStream自定义实现替换为将MD5摘要和"原始"输出流写入字节的自定义实现.最后提供一个访问器来获得最终的MD5总和.

更新我只是为了好玩一点,这是一个开球的例子:

响应包装器:

public class MD5ServletResponse extends HttpServletResponseWrapper {

    private final MD5ServletOutputStream output;
    private final PrintWriter writer;

    public MD5ServletResponse(HttpServletResponse response) throws IOException {
        super(response);
        output = new MD5ServletOutputStream(response.getOutputStream());
        writer = new PrintWriter(output, true);
    }

    public PrintWriter getWriter() throws IOException {
        return writer;
    }

    public ServletOutputStream getOutputStream() throws IOException {
        return output;
    }

    public byte[] getHash() {
        return output.getHash();
    }

}
Run Code Online (Sandbox Code Playgroud)

MD5输出流:

public class MD5ServletOutputStream extends ServletOutputStream {

    private final ServletOutputStream output;
    private final MessageDigest md5;

    {
        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            throw new ExceptionInInitializerError(e);
        }
    }

    public MD5ServletOutputStream(ServletOutputStream output) {
        this.output = output;
    }

    public void write(int i) throws IOException {
        byte[] b = { (byte) i };
        md5.update(b);
        output.write(b, 0, 1);
    }

    public byte[] getHash() {
        return md5.digest();
    }

}
Run Code Online (Sandbox Code Playgroud)

如何使用它:

// Wrap original response with it:
MD5ServletResponse md5response = new MD5ServletResponse(response);

// Now just use md5response instead or response, e.g.:
dispatcher.handle(request, md5response);

// Then get the hash, e.g.:
byte[] hash = md5response.getHash();
StringBuilder hashAsHexString = new StringBuilder(hash.length * 2);
for (byte b : hash) {
    hashAsHexString.append(String.format("%02x", b));
}
System.out.println(hashAsHexString); // Example af28cb895a479397f12083d1419d34e7.
Run Code Online (Sandbox Code Playgroud)