Search code examples
javascriptnode.jscloudflareserverless

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.

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

Solution

  • You don't need to import external libraries to calculate md5 hash in Cloudflare Workers.

    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!.

    Reference: