我的 servlet 加密并发送一个 HashMap 及其 MD5 哈希。
客户端然后接收它们,并将 MD5 与它从 HashMap 中计算出的 MD5 进行比较。
这有时有效,但在其他情况下无效,例如,如果 HashMap 是:
HashMap<String, Object> result = new HashMap<String, Object>();
result.put("error", 0);
result.put("coun", 0);
这样可行
但是,如果是:
HashMap<String, Object> result = new HashMap<String, Object>();
result.put("error", 0);
result.put("count", 0);
它不起作用 - 两个 MD5 哈希值不同。(唯一的区别是键'count'而不是'coun')
该程序发送类似的 HashMap,所有包含的键/值都只是字符串或整数,这是我第一次看到像这样奇怪的东西。
HashMap/MD5 实际发送方式的详细信息 -
服务器做:
//Work out MD5 of the HashMap result (convert it to bytes with objectOutputStream, and MD5 the bytes)
MessageDigest messageDigest = MessageDigest.getInstance("MD5");
ByteArrayOutputStream bos = new ByteArrayOutputStream() ;
ObjectOutputStream out = new ObjectOutputStream(bos) ;
out.writeObject(result);
out.close();
byte[] md5 = messageDigest.digest(bos.toByteArray();
//Encrypt the httpURLConnection response stream, and send the HashMap result and the md5 over the stream
Cipher symmetricCipher = Cipher.getInstance("DES");
symmetricCipher.init(Cipher.ENCRYPT_MODE, symmetricKey);
CipherOutputStream cipherOutput = new CipherOutputStream(response.getOutputStream(), symmetricCipher);
BufferedOutputStream bufferedOutput = new BufferedOutputStream(cipherOutput);
ObjectOutputStream objectOutput = new ObjectOutputStream(out);
objectOutput.writeObject(result);
objectOutput.writeObject(md5);
objectOutput.flush();
客户这样做:
//Decrypt the httpURLConnection response stream
Cipher symmetricCipher = Cipher.getInstance("DES");
symmetricCipher.init(Cipher.DECRYPT_MODE, symmetricKey);
CipherInputStream cipherInput = new CipherInputStream(httpInput, symmetricCipher);
BufferedInputStream bufferedInput = new BufferedInputStream(cipherInput);
//read HashMap and MD5
ObjectInputStream objectInput = new ObjectInputStream(in);
HashMap<String, Object> result = (HashMap<String, Object>) objectInput.readObject();
byte[] hash1 = (byte[]) objectInput.readObject();
//workout hash of the Hashmap received.
MessageDigest messageDigest = MessageDigest.getInstance("MD5");
ByteArrayOutputStream bos = new ByteArrayOutputStream() ;
ObjectOutputStream out = new ObjectOutputStream(bos) ;
out.writeObject(result);
out.close();
byte[] hash2 = messageDigest.digest(bos.toByteArray();
// Compare two hashes
if (!Arrays.equals(hash1, hash2)) {
System.out.println("Result received does not match hash, stopping list operation");
return;
}
使用相同类型的 inputStreams 进行解密,以相同的方式计算出 hashmap 的 md5,然后使用以下方法进行比较:
if (!Arrays.equals(hash1, hash2)) {
System.out.println("Result received does not match hash, stopping get operation");
return;
}
我不明白为什么这对于发送我尝试过的所有 HashMap 都有效,但现在不适用于此计数键。我已经测试了比较客户端和 servlet 上的 HashMap 中的各个键/值对,它们是相同的,但是在比较整个 HashMap 的两个 MD5 时,它们不匹配。
另外,我不确定我是否在流链的正确部分使用缓冲流?