密码学与证书 / 系统课时

实现端到端签名案例

实现端到端签名案例

完整实践要让真正的 HTTP 请求穿过解析、验签、重放检查和业务处理。本篇启动只监听本机的账单服务,由客户端构造并签发请求,检查首次成功、重复拒绝和正文篡改拒绝,最后确认业务只执行一次。

学习目标

  • 在同一可运行程序中连接客户端签发与 HTTP 服务认证。
  • 让签名绑定实际方法、目标、主机、正文与认证元数据。
  • 用响应和执行计数验收认证边界。

为案例限定明确范围

程序使用 Node.js 22 内置模块与 fetch,不需第三方依赖。服务只接受 POST 到固定路径,正文只有整数分金额字段,密钥在内存中临时生成。HTTP 仅监听回环地址;生产传输仍需 HTTPS、受控密钥服务和完整部署策略。

认证字段包括密钥标识、整数秒时间戳、随机 nonce 与规范 Base64url 签名。签名字节采用固定数组,绑定协议域、方法、路径、实际主机、正文摘要和元数据。这是受限教学协议,不是 RFC 9421的完整实现。

真实 HTTP 案例从客户端签发到服务端验证与业务计数,重复和篡改均拒绝

运行一个真实请求闭环

保存完整程序为 end-to-end.cjs,执行 node end-to-end.cjs。操作系统选择空闲端口,程序不打印该动态端口;三个请求结束后会关闭服务,避免留下后台进程。

js
const http = require('node:http');
const { once } = require('node:events');
const { generateKeyPairSync, createHash, randomBytes, sign, verify } = require('node:crypto');
const pair = generateKeyPairSync('ed25519');
const registry = new Map([['client-1', { publicKey: pair.publicKey,
  state: 'active', subject: 'billing-client', canCreate: true }]]);
const consumed = new Map();
let authority, executions = 0;
const signingBytes = r => Buffer.from(JSON.stringify(['invoice-v1', r.kid,
  r.method, r.path, r.authority, 'application/json',
  createHash('sha256').update(r.body).digest('base64url'), r.timestamp, r.nonce]));
function decodeSignature(value) {
  if (typeof value !== 'string' || !/^[A-Za-z0-9_-]{86}$/.test(value)) throw new Error('signature');
  const bytes = Buffer.from(value, 'base64url');
  if (bytes.length !== 64 || bytes.toString('base64url') !== value) throw new Error('signature');
  return bytes;
}
function reply(res, status, value) {
  res.writeHead(status, { 'content-type': 'application/json' });
  res.end(JSON.stringify(value));
}
const server = http.createServer(async (req, res) => {
  try {
    if (req.method !== 'POST' || req.url !== '/invoices') return reply(res, 404, { error: 'not-found' });
    // 原始正文有界读取,验证与业务解析使用同一份Buffer。
    const chunks = []; let length = 0;
    for await (const chunk of req) {
      length += chunk.length;
      if (length > 1024) return reply(res, 413, { error: 'too-large' });
      chunks.push(chunk);
    }
    const body = Buffer.concat(chunks);
    const kid = req.headers['x-key-id'];
    const timeText = req.headers['x-issued-at'];
    const nonce = req.headers['x-nonce'];
    if (req.headers.host !== authority || req.headers['content-type'] !== 'application/json' ||
        kid !== 'client-1' || typeof timeText !== 'string' || !/^[0-9]{10}$/.test(timeText) ||
        typeof nonce !== 'string' || !/^[0-9a-f]{32}$/.test(nonce)) throw new Error('headers');
    const timestamp = Number(timeText), now = Math.floor(Date.now() / 1000);
    const record = registry.get(kid);
    if (!record || record.state !== 'active' || !record.canCreate ||
        now - timestamp > 30 || timestamp - now > 5) throw new Error('policy');
    const request = { kid, method: req.method, path: req.url, authority,
      body, timestamp, nonce };
    if (!verify(null, signingBytes(request), record.publicKey,
      decodeSignature(req.headers['x-signature']))) throw new Error('verify');
    // 实际业务结构也要校验;不能执行未签或另行解析的字段。
    const payment = JSON.parse(body.toString('utf8'));
    if (!payment || Array.isArray(payment) || Object.keys(payment).join(',') !== 'amountCents' ||
        !Number.isSafeInteger(payment.amountCents) || payment.amountCents <= 0 ||
        payment.amountCents > 100000) return reply(res, 400, { error: 'payment' });
    for (const [key, expiry] of consumed) if (expiry < now) consumed.delete(key);
    const replayKey = JSON.stringify([kid, nonce]);
    // 此同步段适用于单进程教学;多副本要换共享原子存储。
    if (consumed.has(replayKey)) throw new Error('replay');
    consumed.set(replayKey, timestamp + 30);
    executions++;
    reply(res, 201, { invoiceId: 'DEMO-1' });
  } catch { reply(res, 401, { error: 'unauthorized' }); }
});
(async () => {
  server.listen(0, '127.0.0.1');
  await once(server, 'listening');
  authority = '127.0.0.1:' + server.address().port;
  try {
    const body = Buffer.from('{"amountCents":1200}');
    const request = { kid: 'client-1', method: 'POST', path: '/invoices', authority,
      body, timestamp: Math.floor(Date.now() / 1000), nonce: randomBytes(16).toString('hex') };
    const headers = { 'content-type': 'application/json', 'x-key-id': request.kid,
      'x-issued-at': String(request.timestamp), 'x-nonce': request.nonce,
      'x-signature': sign(null, signingBytes(request), pair.privateKey).toString('base64url') };
    for (const [name, data] of [['valid', body], ['replay', body],
      ['tampered', Buffer.from('{"amountCents":1300}')]]) {
      const response = await fetch('http://' + authority + '/invoices', { method: 'POST', headers, body: data });
      console.log(name + ':', response.status, await response.text());
    }
    console.log('business executions:', executions);
  } finally {
    // 关闭连接和监听器,使练习不留下服务进程。
    server.closeAllConnections();
    await new Promise(resolve => server.close(resolve));
  }
})().catch(error => { console.error(error.message); process.exitCode = 1; });

预期输出:

text
valid: 201 {"invoiceId":"DEMO-1"}
replay: 401 {"error":"unauthorized"}
tampered: 401 {"error":"unauthorized"}
business executions: 1

时间、nonce、临时密钥和端口每次不同,输出中的示例账单标识固定。重复请求的签名仍然正确,但 nonce 已消费;篡改请求在验签阶段失败,所以两者都不能增加业务执行计数。

从结果检查每个边界

客户端对原始正文计算摘要,服务端对收到的同一 Buffer 重算,修改金额便改变签名字节。方法、路径和实际主机也在字节中,服务另外限制固定方法与路由;错误路由在认证前返回 404。

服务器从受控注册表查主体与公钥,不使用请求自带公钥。规范签名解码器拒绝额外填充和非零未使用位,认证字段用明确字符串规则限制。业务金额在通过身份与签名检查后仍有范围校验,密码学有效不代表任何金额都被授权。

时间检查使用服务器当前整数秒,记录在到期边界仍保留。消费 nonce 与增加计数之间没有 await,因此单进程不能插入第二个请求。但该性质不跨机器存在:部署副本时必须改为共享原子消费,而不是把 Map 拷贝到每个节点。

把练习扩展为可靠服务

真实入口还要限制并发、请求时长和全局缓存容量,处理断开连接与流读取异常。示例的通用 catch 只用于统一认证响应;生产应在内部保留有限阶段类别,区分客户端输入错误与服务依赖故障。

JSON 结构是一个受限字段,正式协议要明确重复键、无效 UTF-8 与数字范围等解析规则。多语言接入时将实际正文和签名字节作为公开测试夹具互验,避免不同解析器把相同文本理解成不同业务对象。

业务计数只是测试观察点,账单应由持久化事务处理并支持独立幂等标识。若消费后业务失败,认证包不能重用;客户端重新签发并查询业务状态。演示的固定账单返回值也应换成真实事务结果,不可用于多个成功请求的身份标识。

最终验收增加过期、撤销、错公钥、非法编码和并发重复请求,并断言业务状态。完整闭环的价值是把算法、字节和业务的联系变成真实运行证据,随后再按明确边界替换秘密存储、共享状态和部署组件。

按自己的节奏,确认真正理解。

目录与阅读设置

记录一个想法

实现端到端签名案例

0 / 10000 · 笔记保存到账号。未提交的修改会在关闭、离开或刷新后丢失。

登录哪都通