【问题标题】:Not able to create MD5 Hash on Cloudflare Worker Script无法在 Cloudflare Worker 脚本上创建 MD5 哈希
【发布时间】:2020-08-13 14:52:26
【问题描述】:

我正在尝试实现请求的自定义授权,在将它们发送到微服务之前,我使用 Cloudflare 工作脚本进行授权,我无法通过工作脚本生成 MD5 哈希。

我在网上浏览了许多博客和文章,但未能达到最终结果。 非常感谢任何帮助。

下面提到的是我正在尝试做的一瞥

 addEventListener('fetch', event => {
    importScripts('https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.9-1/md5.js');
    let test = CryptoJS.MD5('test').toString();
    console.log(test);
    event.respondWith(handleRequest(event.request))
})

【问题讨论】:

标签: javascript node.js cloudflare serverless


【解决方案1】:

您无需导入外部库即可在 Cloudflare Workers 中计算 md5 哈希。

原生支持:

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

/**
 * Respond to the request
 * @param {Request} request
 */
async function handleRequest(request) {
  const message = "Hello world!"
  const msgUint8 = new TextEncoder().encode(message) // encode as (utf-8) Uint8Array
  const hashBuffer = await crypto.subtle.digest('MD5', msgUint8) // hash the message
  const hashArray = Array.from(new Uint8Array(hashBuffer)) // convert buffer to byte array
  const hashHex = hashArray.map(b => b.toString(16).padStart(2, '0')).join('') // convert bytes to hex string

  return new Response(hashHex, {status: 200})
}

当被触发时,它将以86fb269d190d2c85f6e0468ceca42a20 进行响应,即md5 of Hello world!

参考:

【讨论】:

  • 工作就像一个魅力,非常感谢。
猜你喜欢
  • 2017-07-26
  • 1970-01-01
  • 1970-01-01
  • 2017-05-04
  • 2023-03-16
  • 2021-10-10
  • 1970-01-01
  • 1970-01-01
  • 2015-01-05
相关资源
最近更新 更多