sign.ts
1.89 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
// RSA 加签 / 验签核心(基于 jsrsasign,算法 SHA256withRSA)
// 文档 §三/§五:请求由前端私钥加签,响应由服务端公钥验签。
import { KJUR, hextob64, b64tohex } from 'jsrsasign';
import { SIGN_CONFIG, CLIENT_PRIVATE_KEY } from './config';
export const APP_ID = SIGN_CONFIG.APP_ID;
export const ALGORITHM = SIGN_CONFIG.ALGORITHM;
// 客户端私钥(前端)→ 请求加签;服务端公钥(运行时拉取)→ 响应验签
let clientPrivateKey: string | null = null;
let serverPublicKey: string | null = null;
if (CLIENT_PRIVATE_KEY) setClientPrivateKey(CLIENT_PRIVATE_KEY);
export function setClientPrivateKey(pem: string): void {
clientPrivateKey = pem.trim();
}
export function setServerPublicKey(pem: string): void {
serverPublicKey = pem.trim();
}
export function isSignReady(): boolean {
return !!clientPrivateKey;
}
export function isVerifyReady(): boolean {
return !!serverPublicKey;
}
/** 请求方向:用客户端私钥对原文加签,返回 Base64 签名 */
export function rsaSign(content: string): string {
if (!clientPrivateKey) throw new Error('客户端私钥未配置,无法对请求加签');
const sig = new KJUR.crypto.Signature({ alg: ALGORITHM });
sig.init(clientPrivateKey);
sig.updateString(content); // 按 UTF-8 处理
return hextob64(sig.sign());
}
/** 响应方向:用服务端公钥验证 Base64 签名 */
export function rsaVerify(content: string, signBase64: string): boolean {
if (!serverPublicKey) return false;
const sig = new KJUR.crypto.Signature({ alg: ALGORITHM });
sig.init(serverPublicKey);
sig.updateString(content);
return sig.verify(b64tohex(signBase64));
}
/** 一次性随机串(防重放 nonce) */
export function uuid(): string {
if (typeof crypto !== 'undefined' && crypto.randomUUID) return crypto.randomUUID();
return Date.now().toString(16) + Math.random().toString(16).slice(2);
}