使用 Cloudflare Workers 验证 HMAC 哈希

问题描述

我正在尝试验证从 WebHook 收到的 HMAC 签名。 WebHook 的详细信息是 https://cloudconvert.com/api/v2/webhooks#webhooks-events

这表示 HMAC 是使用 hash_hmac (PHP) 生成的,并且是主体的 SHA256 散列 - 即 JSON。收到的一个例子是:

c4faebbfb4e81db293801604d0565cf9701d9e896cae588d73ddfef3671e97d7

这看起来像小写的十六进制。

我正在尝试使用 Cloudflare Workers 来处理请求,但是我无法验证哈希。我的代码如下:

const encoder = new TextEncoder()

addEventListener('fetch',event => {
    event.respondWith(handleRequest(event.request))
})

async function handleRequest(request) {
    const contentType = request.headers.get('content-type') || ''
    const signature = request.headers.get('CloudConvert-Signature')
    let data

    await S.put('HEADER',signature)

    if (contentType.includes('application/json')) {
        data = await request.json()
        await S.put('EVENT',data.event)
        await S.put('TAG',data.job.tag)
        await S.put('JSON',JSON.stringify(data))
    }

    const key2 = await crypto.subtle.importKey(
        'raw',encoder.encode(CCSigningKey2),{ name: 'HMAC',hash: 'SHA-256' },false,['sign']
    )

    const signed2 = await crypto.subtle.sign(
        'HMAC',key2,encoder.encode(JSON.stringify(data))
    )
    
    await S.put('V22',btoa(String.fromCharCode(...new Uint8Array(signed2))))

    return new Response(null,{
        status: 204,headers: {
            'Cache-Control': 'no-cache'
        }
    })
}

这将生成一个哈希值:

e52613e6ecebdf98bb085f04ca1f91bf9a5cf1dc085f89dcaa3e5fbf5ebf1b06

我尝试过使用 crypto.subtle.verify 方法,但是没有用。

有人能看到代码有什么问题吗?或者已经使用 Cloudflare Workers 成功完成了这项工作?

标记

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)