You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Cloudflare Worker中如何从URL获取参数并调用指定方法解密

Cloudflare Worker 路径hash提取与解密实现方案

你需要先确保已准备好decryptData依赖的三个工具函数:hexStringToUint8Array、getPasswordKey、arraybufferToString,解密密码建议存入Worker的加密环境变量,不要硬编码在代码中。

完整实现代码

// 你提供的解密函数
async function decryptData(encryptedData, password) {
  try {
    // split the IV off from the end (delimited using ::)
    encryptedComponents= encryptedData.split("::")

    const data = hexStringToUint8Array(encryptedComponents[0])
    const iv = hexStringToUint8Array(encryptedComponents[1])
    
    const passwordKey = await getPasswordKey(password, ['decrypt'])
    const decryptedContent = await crypto.subtle.decrypt(
      {
        name: 'AES-CBC',
        iv: iv,
      },
      passwordKey,
      data,
    )
    return arraybufferToString(decryptedContent)
  } catch (e) {
    throw e
  }
}

// 依赖工具函数示例,如你已有可替换为自己的实现
function hexStringToUint8Array(hex) {
  const length = hex.length / 2;
  const uint8 = new Uint8Array(length);
  for (let i = 0; i < length; i++) {
    uint8[i] = parseInt(hex.substr(i * 2, 2), 16);
  }
  return uint8;
}

async function getPasswordKey(password, usages) {
  const enc = new TextEncoder();
  const passwordKey = await crypto.subtle.importKey(
    'raw',
    enc.encode(password),
    { name: 'PBKDF2' },
    false,
    ['deriveKey']
  );
  // 此处盐值要和你加密时用的盐值一致
  const salt = enc.encode('your-custom-salt');
  return crypto.subtle.deriveKey(
    {
      name: 'PBKDF2',
      salt: salt,
      iterations: 100000,
      hash: 'SHA-256',
    },
    passwordKey,
    { name: 'AES-CBC', length: 256 },
    false,
    usages
  );
}

function arraybufferToString(buffer) {
  return new TextDecoder('utf-8').decode(buffer);
}

export default {
  async fetch(request, env, ctx) {
    try {
      // 解析请求URL
      const url = new URL(request.url);
      // 提取路径中的hash值,适配https://xxx/hash/格式
      const pathSegments = url.pathname.split('/').filter(segment => segment.trim() !== '');
      if (pathSegments.length < 1) {
        return new Response('缺少待解密的hash参数', { status: 400 });
      }
      const encryptedHash = pathSegments[0];
      // 调用解密函数,密码从环境变量DECRYPT_PASSWORD中取
      const decryptedContent = await decryptData(encryptedHash, env.DECRYPT_PASSWORD);
      // 返回解密结果,可根据需要修改返回格式为JSON等
      return new Response(decryptedContent, {
        headers: { 'Content-Type': 'text/plain; charset=utf-8' }
      });
    } catch (err) {
      return new Response(`解密失败:${err.message}`, { status: 500 });
    }
  }
};

配置说明

  • 进入Cloudflare Worker控制台的「设置」-「环境变量」,添加加密变量DECRYPT_PASSWORD,值为你解密用的密码
  • 替换getPasswordKey中的盐值为你加密时使用的对应值,迭代次数也要和加密时保持一致
  • 如果你需要修改返回格式,可调整解密成功后的Response构造参数,比如返回JSON格式就修改Content-Type,把内容用JSON.stringify包裹即可

内容的提问来源于stack exchange,提问作者Dinesh chandra

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 02:54:04