无法在Cloudflare Worker脚本上创建MD5哈希

问题描述

我正在尝试实现请求的自定义授权,然后再将它们发送到微服务,我使用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))
})

解决方法

您无需导入外部库即可在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的{​​{1}}进行响应。

参考: