UNPKG

did-jwt

Version:

Library for Signing and Verifying JWTs that use DIDs as issuers and JWEs that use DIDs as recipients

41 lines • 1.8 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ES256KSigner = ES256KSigner; const util_js_1 = require("../util.js"); const Digest_js_1 = require("../Digest.js"); const secp256k1_js_1 = require("@noble/curves/secp256k1.js"); /** * Creates a configured signer function for signing data using the ES256K (secp256k1 + sha256) algorithm. * * The signing function itself takes the data as a `Uint8Array` or `string` and returns a `base64Url`-encoded signature * * @example * ```TypeScript * const sign: Signer = ES256KSigner(process.env.PRIVATE_KEY) * const signature: string = await sign(data) * ``` * * @param {String} privateKey a private key as `Uint8Array` * @param {Boolean} recoverable an optional flag to add the recovery param to the generated signatures * @return {Function} a configured signer function `(data: string | Uint8Array): Promise<string>` */ function ES256KSigner(privateKey, recoverable = false) { const privateKeyBytes = privateKey; if (privateKeyBytes.length !== 32) { throw new Error(`bad_key: Invalid private key format. Expecting 32 bytes, but got ${privateKeyBytes.length}`); } return async (data) => { const signature = secp256k1_js_1.secp256k1.sign((0, Digest_js_1.sha256)(data), privateKeyBytes, { prehash: false, format: recoverable ? 'recovered' : 'compact', }); if (recoverable) { const sigBytes = new Uint8Array(65); sigBytes.set(signature.slice(1, 65), 0); sigBytes[64] = signature[0]; return (0, util_js_1.bytesToBase64url)(sigBytes); } return (0, util_js_1.bytesToBase64url)(signature); }; } //# sourceMappingURL=ES256KSigner.js.map