且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用 PHP 生成 XML 签名摘要

更新时间:2022-11-28 18:15:19

我找到了解决方案.对于我尝试的大多数示例,所需的转换是独占规范化和注释:http://www.w3.org/TR/2002/REC-xml-exc-c14n-20020718/#WithComments

I found the solution. For most of the examples I tried, the required transformation was exclusive canonicalization with comments: http://www.w3.org/TR/2002/REC-xml-exc-c14n-20020718/#WithComments

所以我的问题是我做错了转换.PHP 的 C14N 函数中的第一个参数定义了是否使用独占转换.代码应该是这样的(注意我去掉了对第一个元素的不必要的遍历):

So my problem was that I was doing the transformation wrong. The first parameter in PHP's C14N function defines whether to use exclusive transformation or not. This is what the code should have been (note that I removed the unnecessary traversal to the first element):

public function testCreateDigest(DOMDocument $request, $expectedDigest) {

    $ns = $request->documentElement->namespaceURI;
    $body = $request
        ->getElementsByTagNameNS($ns, 'Body')
        ->item(0);

    $content = $body->C14N(true, true); // <-- exclusive, with comments

    $actualDigest = base64_encode(hash('SHA1', $content, true));

    $this->assertEquals($expectedDigest, $actualDigest);

}

所以你有它.这提醒我在漫无目的地编码之前仔细检查我的 XML 并了解标准.

So there you have it. This served as a reminder for me to double check my XML and understand the standards before I go coding aimlessly.