我正在尝试实现请求的自定义授权,在将请求发送到微服务之前,我正在使用 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
,这是Hello world!
md5
。
参考:
- https://developers.cloudflare.com/workers/runtime-apis/web-crypto
- https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/digest
下面是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});
}
}