import { ISigner } from './interface'; /** * HMAC签名器 */ export class HMACSigner implements ISigner { private key: CryptoKey | null = null; constructor(keyString: string) { this.importKey(keyString); } /** * 导入密钥 */ private async importKey(keyString: string): Promise { const encoder = new TextEncoder(); const keyData = encoder.encode(keyString); this.key = await crypto.subtle.importKey( 'raw', keyData, { name: 'HMAC', hash: 'SHA-256', }, false, ['sign', 'verify'] ); } /** * 生成签名 */ async sign(data: Uint8Array): Promise { if (!this.key) { throw new Error('密钥未设置'); } const signature = await crypto.subtle.sign('HMAC', this.key, data); return new Uint8Array(signature); } /** * 验证签名 */ async verify(data: Uint8Array, signature: Uint8Array): Promise { if (!this.key) { throw new Error('密钥未设置'); } return await crypto.subtle.verify('HMAC', this.key, signature, data); } }