"use strict";
//
//  Copyright (c) Microsoft Corporation. All rights reserved.
//
Object.defineProperty(exports, "__esModule", { value: true });
exports.WebHmac = void 0;
const buffer_1 = require("buffer");
const hmacAlgorithm_1 = require("../hmacAlgorithm");
class WebHmac extends hmacAlgorithm_1.HmacAlgorithm {
    constructor(name, algorithmName, encryptThenMac = false) {
        super(name, algorithmName, WebHmac.getHashKeyLength(algorithmName), WebHmac.getHashDigestLength(algorithmName));
        this.encryptThenMac = encryptThenMac;
    }
    async createSigner(key) {
        const hmac = new WebSignerVerifier(this.algorithmName, true, this.digestLength, this.encryptThenMac);
        await hmac.init(key);
        return hmac;
    }
    async createVerifier(key) {
        const hmac = new WebSignerVerifier(this.algorithmName, false, this.digestLength, this.encryptThenMac);
        await hmac.init(key);
        return hmac;
    }
    static getHashKeyLength(hashAlgorithmName) {
        if (hashAlgorithmName === 'SHA2-512')
            return 512 / 8;
        if (hashAlgorithmName === 'SHA2-384')
            return 384 / 8;
        if (hashAlgorithmName === 'SHA2-256')
            return 256 / 8;
        throw new Error(`Unsupported hash algorithm: ${hashAlgorithmName}`);
    }
    static getHashDigestLength(hashAlgorithmName) {
        return this.getHashKeyLength(hashAlgorithmName);
    }
    static getWebHashAlgorithmName(hashAlgorithmName) {
        if (hashAlgorithmName === 'SHA2-512')
            return 'SHA-512';
        if (hashAlgorithmName === 'SHA2-384')
            return 'SHA-384';
        if (hashAlgorithmName === 'SHA2-256')
            return 'SHA-256';
        throw new Error(`Unsupported hash algorithm: ${hashAlgorithmName}`);
    }
}
exports.WebHmac = WebHmac;
class WebSignerVerifier {
    constructor(algorithmName, isSigning, digestLength, encryptThenMac) {
        this.algorithmName = algorithmName;
        this.isSigning = isSigning;
        this.digestLength = digestLength;
        this.encryptThenMac = encryptThenMac;
    }
    async init(key) {
        try {
            const name = this.algorithmName.replace('SHA2-', 'SHA-');
            this.key = await crypto.subtle.importKey('raw', key, { name: 'HMAC', hash: { name } }, false, this.isSigning ? ['sign'] : ['verify']);
        }
        catch (e) {
            throw new Error('Failed to initialize HMAC: ' + e);
        }
    }
    async sign(data) {
        return buffer_1.Buffer.from(await crypto.subtle.sign({ name: 'HMAC', hash: { name: this.algorithmName } }, this.key, data));
    }
    async verify(data, signature) {
        return await crypto.subtle.verify({ name: 'HMAC', hash: { name: this.algorithmName } }, this.key, signature, data);
    }
    dispose() { }
}
//# sourceMappingURL=https://github.com/VSCodium/sourcemaps/releases/download/stable-4c0b0c6cc561d2d3636d1ec250935431876ce4dc/node_modules-@microsoft-dev-tunnels-ssh-algorithms-web-webHmac.js.map