跳转到内容
搜索文档

使用 timingSafeEqual

使用 timingSafeEqual 防止时序攻击。 timingSafeEqual.

最后更新 查看 MarkdownAgent 设置

如需快速上手,请点击下方按钮。

Deploy to Cloudflare

这会在你的 GitHub 账户中创建仓库,并将应用部署到 Cloudflare Workers。

crypto.subtle.timingSafeEqual 函数使用恒定时间算法比较两个值。耗时与值的内容无关。

使用相等运算符(=====)比较字符串时,比较会在第一个不匹配的字符处结束。使用 timingSafeEqual,攻击者无法通过时序判断两个字符串在哪个位置存在差异。

timingSafeEqual 函数接受两个 ArrayBufferTypedArray 值进行比较。这些缓冲区必须长度相等,否则会抛出异常。 请注意,此函数相对于参数长度并非恒定时间,也不保证周围代码的恒定时间。 处理密钥时应谨慎,避免引入时序侧信道。

要比较两个字符串,必须使用 TextEncoder API。

interface Environment {
	MY_SECRET_VALUE?: string;
}

export default {
	async fetch(req: Request, env: Environment) {
		if (!env.MY_SECRET_VALUE) {
			return new Response("Missing secret binding", { status: 500 });
		}

		const authToken = req.headers.get("Authorization") || "";

		const encoder = new TextEncoder();

		const userValue = encoder.encode(authToken);
		const secretValue = encoder.encode(env.MY_SECRET_VALUE);

		// Do not return early when lengths differ — that leaks the secret's
		// length through timing.  Instead, always perform a constant-time
		// comparison: when the lengths match compare directly; otherwise
		// compare the user input against itself (always true) and negate.
		const lengthsMatch = userValue.byteLength === secretValue.byteLength;
		const isEqual = lengthsMatch
			? crypto.subtle.timingSafeEqual(userValue, secretValue)
			: !crypto.subtle.timingSafeEqual(userValue, userValue);

		if (!isEqual) {
			return new Response("Unauthorized", { status: 401 });
		}

		return new Response("Welcome!");
	},
};
from workers import WorkerEntrypoint, Response
from js import TextEncoder, crypto

class Default(WorkerEntrypoint):
    async def fetch(self, request):
        auth_token = request.headers["Authorization"] or ""
        secret = self.env.MY_SECRET_VALUE

        if secret is None:
            return Response("Missing secret binding", status=500)

        encoder = TextEncoder.new()
        user_value = encoder.encode(auth_token)
        secret_value = encoder.encode(secret)

        # Do not return early when lengths differ — that leaks the secret's
        # length through timing.  Always perform a constant-time comparison.
        if user_value.byteLength == secret_value.byteLength:
            is_equal = crypto.subtle.timingSafeEqual(user_value, secret_value)
        else:
            is_equal = not crypto.subtle.timingSafeEqual(user_value, user_value)

        if not is_equal:
            return Response("Unauthorized", status=401)

        return Response("Welcome!")
import { Hono } from 'hono';

interface Environment {
  Bindings: {
    MY_SECRET_VALUE?: string;
  }
}

const app = new Hono<Environment>();

// Middleware to handle authentication with timing-safe comparison
app.use('*', async (c, next) => {
  const secret = c.env.MY_SECRET_VALUE;

  if (!secret) {
    return c.text("Missing secret binding", 500);
  }

  const authToken = c.req.header("Authorization") || "";

  const encoder = new TextEncoder();

  const userValue = encoder.encode(authToken);
  const secretValue = encoder.encode(secret);

  // Do not return early when lengths differ — that leaks the secret's
  // length through timing.  Instead, always perform a constant-time
  // comparison: when the lengths match compare directly; otherwise
  // compare the user input against itself (always true) and negate.
  const lengthsMatch = userValue.byteLength === secretValue.byteLength;
  const isEqual = lengthsMatch
    ? crypto.subtle.timingSafeEqual(userValue, secretValue)
    : !crypto.subtle.timingSafeEqual(userValue, userValue);

  if (!isEqual) {
    return c.text("Unauthorized", 401);
  }

  // If we got here, the auth token is valid
  await next();
});

// Protected route
app.get('*', (c) => {
  return c.text("Welcome!");
});

export default app;

这篇文档对您有帮助吗?