kucoin-api
Version:
Complete & robust Node.js SDK for Kucoin's REST APIs and WebSockets, with TypeScript & strong end to end tests.
57 lines • 2.02 kB
JavaScript
Object.defineProperty(exports, "__esModule", { value: true });
exports.signMessage = exports.hashMessage = void 0;
const misc_util_js_1 = require("./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
*/
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 (0, misc_util_js_1.neverGuard)(method, `Unhandled sign method: "${method}"`);
}
}
}
exports.hashMessage = hashMessage;
/**
* Sign a message, with a secret, using the Web Crypto API
*/
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 (0, misc_util_js_1.neverGuard)(method, `Unhandled sign method: "${method}"`);
}
}
}
exports.signMessage = signMessage;
//# sourceMappingURL=webCryptoAPI.js.map
;