我正在寻找一种方法来检查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.
}这有可能吗?
发布于 2010-02-02 09:22:42
是的,这是可能的。您需要借助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();
}
}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();
}
}使用方法:
// 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.发布于 2010-02-02 22:45:07
从技术上讲,术语“签名”是专用于签名的,哈希函数不会计算这些签名。
要使用散列函数确保数据在传输过程中不被更改,则必须有一种安全的带外方式来传输散列值;在HTTP标头中添加散列值是行不通的,因为任何能够更改传输的数据的人都可以随意重新计算散列,并按其认为合适的方式修改HTTP标头。
使用密码学,您可以将安全的带外传输“集中”到一个可重用的密钥中。如果客户端和服务器有一个共享的秘密值,假定的攻击者不知道,那么缩写是MAC,如“消息验证码”;通常的MAC是HMAC。
在许多实际情况下,不能使用MAC,因为MAC需要共享秘密,并且共享太多次的秘密不再是真正的秘密。每个秘密持有者都有能力重新计算MAC。如果每个客户端都知道这个秘密,那么基本上它就不是一个秘密,可以安全地假设攻击者也知道它。因此,您可以更进一步,使用数字签名(真正的签名,使用RSA、DSS、ECDSA的签名)其中服务器使用私钥(只有服务器知道),而客户端只知道相应的公钥。公钥的知识足以验证签名,但不能产生新的签名,并且不能从公钥重新计算私钥(尽管它们在数学上相互关联)。然而,实现数字签名并正确地使用它比通常假设的要困难得多;您最好的选择是在现有的实现中使用已经调试过的协议,该协议恰好被称为"SSL“。
这里的要点是,如果没有SSL,您所做的任何事情都不会阻止坚定的攻击者;它只会占用CPU周期和网络带宽,并给您一种温暖而模糊的感觉。
发布于 2010-02-02 09:23:39
你想做什么?
您最好查看标准消息格式,并将响应的内容包装在这样的消息中,然后对其进行签名。OAuth出现在我的脑海中。
此外,如果启用SSL,客户端可以确保响应的内容未被篡改。
https://stackoverflow.com/questions/2181215
复制相似问题