http-headers - 计算 Content-Digest 字段的差异

标签 http-headers digital-signature

我正在尝试计算 eBay 文档中 Content-Digest header 的值 https://developer.ebay.com/develop/guides/digital-signatures-for-apis#sigin

当我尝试根据我对规范的理解来计算示例有效负载摘要 header 时,我得到了不同的值。我对规范的理解是否错误,或者文档中是否存在错误?

Content-Digest header

NOTE: When no HTTP payload is included (e.g., for a GET call,) this header is not required.

When an HTTP payload is included, this header provides an SHA-256 digest over the HTTP payload.

To add the Content-Digest header (as specified in draft-ietf-httpbis-digest-headers-10), calculate an SHA-256 digest over the HTTP payload (in UTF-8 character encoding). While the specification allows adding more than one digest (e.g., both SHA-256 and SHA-512), only the SHA-256 is needed in our case.

Consider the following payload:

{"hello": "world"}

In this case, the value of the Content-Digest header will be:

sha-256=:X48E9qOokqqrvdts8nOJRJN3OWDUoyWxBf7kbu9DBPE=:

因此,根据规范,该 header 的 key 似乎是摘要算法(在示例中为 sha-256),后跟 =。该值是以 utf-8 编码的有效负载的 Base64 编码摘要。

这是我在 ruby​​ 中计算摘要的尝试

2.5.3 :022 > s = '{"hello": "world"}'.encode('utf-8')
 => "{\"hello\": \"world\"}"
2.5.3 :023 > s
 => "{\"hello\": \"world\"}"
2.5.3 :024 > puts s
{"hello": "world"}
 => nil
2.5.3 :025 > require 'digest'
 => true
2.5.3 :026 > digest = Digest::SHA2.new(256).hexdigest s
 => "5f8f04f6a3a892aaabbddb6cf273894493773960d4a325b105fee46eef4304f1"
2.5.3 :027 > require 'base64'
 => true
2.5.3 :028 > Base64.strict_encode64 digest
 => "NWY4ZjA0ZjZhM2E4OTJhYWFiYmRkYjZjZjI3Mzg5NDQ5Mzc3Mzk2MGQ0YTMyNWIxMDVmZWU0NmVlZjQzMDRmMQ=="

如您所见,Base 64 编码摘要与示例完全不同。

最佳答案

所以我找到了我的问题,并将在这里发布解决方案供其他人使用。 Content-Digest header (至少对于 eBays SCA 要求)是一个 sha-256 散列 utf-8 编码字节数组,然后转换为 base64 编码字符串。

2.5.3 :001 > require 'base64'
 => true
2.5.3 :002 > require 'digest'
 => true
2.5.3 :003 > s = '{"hello": "world"}'.encode('utf-8')
 => "{\"hello\": \"world\"}"
2.5.3 :005 > Digest::SHA256.base64digest s
 => "X48E9qOokqqrvdts8nOJRJN3OWDUoyWxBf7kbu9DBPE="
2.5.3 :006 >

我在 C# 中需要这个,所以我的实现看起来像这样

private void _addDigestHeader(HttpWebRequest request, string requestBody)
{
    byte[] hashBytes;
    using (var sha256Hash = SHA256.Create())
    {
        hashBytes = sha256Hash.ComputeHash(Encoding.UTF8.GetBytes(xml.InnerXml));
    }
    var hashResult = Convert.ToBase64String(hashBytes);

    request.Headers.Add("content-digest", hashResult);
}

关于http-headers - 计算 Content-Digest 字段的差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74365335/

相关文章:

ios - HTTP 请求 header

javascript - 向请求添加 header 时出现 HTTP 状态代码 405 错误

algorithm - PKI HSM 模拟器

java - PGP,验证证书上的签名

.net - "referenced assembly"如何验证 "caller assembly"的签名/真实性?

c# - 将 X-Frame-Options header 添加到 MVC 4 应用程序中的所有页面

rest - Accept HTTP header 在处理异常时如何影响返回的内容?

google-chrome - Chrome 在 Google 字体上抛出内容安全策略错误

executable - 对我们的可执行文件进行数字签名有多重要?

python - 如何使用python数字签名PDF?