UNPKG

kucoin-api

Version:

Complete & robust Node.js SDK for Kucoin's REST APIs and WebSockets, with TypeScript & strong end to end tests.

52 lines 1.79 kB
import { neverGuard } from './misc-util.js'; function bufferToB64(buffer) { let binary = ''; const bytes = new Uint8Array(buffer); const len = bytes.byteLength; for (let i = 0; i < len; i++) { binary += String.fromCharCode(bytes[i]); } return globalThis.btoa(binary); } /** * Similar to node crypto's `createHash()` function */ export async function hashMessage(message, method, algorithm) { const encoder = new TextEncoder(); const buffer = await globalThis.crypto.subtle.digest(algorithm, encoder.encode(message)); switch (method) { case 'hex': { return Array.from(new Uint8Array(buffer)) .map((byte) => byte.toString(16).padStart(2, '0')) .join(''); } case 'base64': { return bufferToB64(buffer); } default: { throw neverGuard(method, `Unhandled sign method: "${method}"`); } } } /** * Sign a message, with a secret, using the Web Crypto API */ export async function signMessage(message, secret, method, algorithm) { const encoder = new TextEncoder(); const key = await globalThis.crypto.subtle.importKey('raw', encoder.encode(secret), { name: 'HMAC', hash: algorithm }, false, ['sign']); const buffer = await globalThis.crypto.subtle.sign('HMAC', key, encoder.encode(message)); switch (method) { case 'hex': { return Array.from(new Uint8Array(buffer)) .map((byte) => byte.toString(16).padStart(2, '0')) .join(''); } case 'base64': { return bufferToB64(buffer); } default: { throw neverGuard(method, `Unhandled sign method: "${method}"`); } } } //# sourceMappingURL=webCryptoAPI.js.map