UNPKG

gamemoney-fix

Version:
52 lines (51 loc) 1.54 kB
import { URL } from 'node:url'; import crypto from 'node:crypto'; import fs from 'node:fs'; const publicCert = fs .readFileSync(new URL('certs/gm.crt', import.meta.url)) .toString(); export function parametersToString(body) { let parametersString = ''; const keys = Object.keys(body).sort(); if (Array.isArray(body)) { keys.sort((a, b) => Number(a) - Number(b)); } for (const key of keys) { let value = body[key]; if (key === 'signature') { continue; } if (value === null || value === undefined) { value = ''; } if (typeof value === 'object' && value !== null) { value = parametersToString(value); } parametersString += `${key}:${value};`; } return parametersString; } export function verifyRsaSignature(body) { return crypto .createVerify('RSA-SHA256') .update(parametersToString(body), 'utf8') .verify(publicCert, body.signature, 'base64'); } export function generateRsaSignature(body, key) { return crypto .createSign('RSA-SHA256') .update(parametersToString(body), 'utf8') .sign(key, 'base64'); } export function generateHmacSignature(body, key) { return crypto .createHmac('sha256', key) .update(parametersToString(body), 'utf8') .digest('hex'); } export function getRandomString(length) { return crypto .randomBytes(Math.ceil(length / 2)) .toString('hex') .slice(0, length); }