简体   繁体   English

无法在 Cloudflare Worker 脚本上创建 MD5 Hash

[英]Not able to create MD5 Hash on Cloudflare Worker Script

I am trying to implement custom authorization of requests, before sending them to microservices, I am using Cloudflare worker scripts for the authorization and I am not able to generate the MD5 hash through worker script.我正在尝试实现请求的自定义授权,在将它们发送到微服务之前,我使用 Cloudflare 工作脚本进行授权,我无法通过工作脚本生成 MD5 hash。

I have gone through many blogs and articles online but was not able to achieve the end result.我在网上浏览了许多博客和文章,但未能达到最终结果。 Any help is highly appreciated.非常感谢任何帮助。

Mentioned below is the glimpse of what I am trying to do下面提到的是我正在尝试做的一瞥

 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))
})

You don't need to import external libraries to calculate md5 hash in Cloudflare Workers.您无需导入外部库即可在 Cloudflare Workers 中计算md5 hash。

It's supported natively:它本机支持:

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})
}

When triggered, it will respond with 86fb269d190d2c85f6e0468ceca42a20 which is md5 of Hello world!触发时,它会以86fb269d190d2c85f6e0468ceca42a20响应,这是Hello world!md5 . .

Reference:参考:

here's an example of Cloudflare Workers hashing without a library, except using the SHA-256 algorithm in place of the obsolete MD5这是一个没有库的 Cloudflare Workers 散列示例,除了使用 SHA-256 算法代替过时的 MD5

export default {
  async fetch(request)
  {
    const myText = new TextEncoder().encode('Hello world!');
    const myDigest = await crypto.subtle.digest({ name: 'SHA-256' }, myText);
    const hashArray = Array.from(new Uint8Array(myDigest));
    const hashHex = hashArray.map(b => b.toString(16).padStart(2, '0')).join('')
    return new Response(hashHex, {status: 200});
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM