[英]Not able to create MD5 Hash on Cloudflare Worker Script
我正在嘗試實現請求的自定義授權,在將它們發送到微服務之前,我使用 Cloudflare 工作腳本進行授權,我無法通過工作腳本生成 MD5 hash。
我在網上瀏覽了許多博客和文章,但未能達到最終結果。 非常感謝任何幫助。
下面提到的是我正在嘗試做的一瞥
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
hash。
它本機支持:
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
! .
參考:
這是一個沒有庫的 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.