如何在 WCF 服务提供的对象图上用 C# 创建哈希码
我目前有一个 WCF 服务,它根据请求提供数据的对象图。我希望有一种机制,客户端可以在其拥有的缓存对象图上计算哈希值,然后可以将该哈希值提供给 WCF 服务以查看它是否与服务拥有的数据匹配。
我尝试使用标准加密算法来计算对象的哈希值,但由于对象定义由服务保存,因此当将其传输到客户端时,可以添加额外的属性,并且属性的顺序可能会改变,这两者会影响产生的哈希值。
除了在 WCF 服务定义上的每个对象上覆盖 GetHashCode,然后在客户端上重新实现相同类型的哈希生成作为实用程序之外,是否还有其他机制?
I currently have a WCF service which provides an object graph of data on request. I want to have a mechanism where the client can compute a hash on the cached object graph it posses and can then supply this hash value to the WCF service to see if it matches the data the service possesses.
I tried this using a standard cryptographic algorithm for computing a hash on the objects but as the object definitions are held by the service, when this is transmitted to the client extra properties can be added and the order of the properties may change, both of which will affect the hash produced.
Is there any mechanism other than say overriding GetHashCode on each object on the WCF service definition and then re-implementing the same kind of hash generation as a utility on the client?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以简单地将其序列化为已知的布局,并采用序列化形式的已知哈希(md5?)。不过,这需要可预测的序列化 - 因此 XML 属性将像空白一样令人痛苦。但并非不可克服。
或者,基于反射/md5 的方法?
You could simply serialize it to a known layout and take a known hash (md5?) of the serialised form. This requires a predictable serialization though - so XML attributes would be a pain as would whitespace. But not insurmountable.
Alternatively, a reflection / md5 based approach?
现在设法解决这个问题。我没有在客户端和服务器上使用 XMLSerialiser 来创建内存流,然后可以计算哈希值,而是将其更改为使用 DataContractSerializer,WCF 服务使用 DataContractSerializer 将对象图序列化到客户端。这意味着对象图具有相同的结构和布局。现在,计算两种序列化形式上的哈希值是匹配的。
以防万一有人感兴趣,这就是它的工作原理,我调用它,然后将返回的 byte[] 与客户端提供的进行比较:
Managed to sort this out now. Rather than using an XMLSerialiser on the client and server to create a memory stream that I could then compute a hash on I changed it to use the DataContractSerializer which the WCF service is using to serialise the object graph to the client. This then means that the object graphs are of the same structure and layout. Computing the hash on both serialised forms now matches.
Just in case anyones interested this is how its working, I'm calling this then comparing the byte[] returned with that supplied by the client: