Javascript Signature Generator

const secret = 'YOUR-API-SECRET';

const getValues = function (obj) {
    let values = [];

    obj = Object.keys(obj).sort().reduce(function (r, k) {
        return (r[k] = obj[k], r);
    }, {});

    for (const key in obj) {
        const value = obj[key];

        if (Array.isArray(value) || (typeof value === 'object' && value !== null)) {
            values.push(...getValues(value));
            continue;
        }

        if (typeof value == 'boolean') {
            values.push(value ? '1' : '0');
            continue;
        }

        values.push(value ? value.toString() : '');
    }
    return values;
};

const hmac = async (message, secret) => {
    const msgBuffer = new TextEncoder().encode(message);
    const secretBuffer = new TextEncoder().encode(secret);
    const key = await crypto.subtle.importKey('raw', secretBuffer, { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']);
    const signatureBuffer = await crypto.subtle.sign('HMAC', key, msgBuffer);
    const signatureArray = Array.from(new Uint8Array(signatureBuffer));

    return signatureArray.map(b => b.toString(16).padStart(2, '0')).join('');
};

async function generateSignature(url, params, secret, salt) {
    const path = (new URL(url)).pathname;

    const toSign = path + getValues(params).join('') + (salt || '');

    const signature = await hmac(toSign, secret);

    return {
        signature: signature,
        salt: salt
    };
}
ssofyKnowledge Base
At our core, we believe that staying up-to-date with the latest trends and advancements in Authentication and related areas is essential. That's why we take great pride in keeping you informed with the latest insights, updates, and news in this rapidly evolving landscape.


Do you need support?
SSOfy is by Cubelet Ltd.
Copyright © 2024 Cubelet Ltd. All rights reserved.