"use strict";
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
Object.defineProperty(exports, "__esModule", { value: true });
exports.buildCryptographicMaterialsCacheKeyHelpers = void 0;
const serialize_1 = require("@aws-crypto/serialize");
const portable_compare_1 = require("./portable_compare");
//  512 bits of 0 for padding between hashes in decryption materials cache ID generation.
const BIT_PAD_512 = Buffer.alloc(64);
function buildCryptographicMaterialsCacheKeyHelpers(fromUtf8, toUtf8, sha512) {
    const { serializeEncryptionContext, serializeEncryptedDataKey } = (0, serialize_1.serializeFactory)(fromUtf8);
    return {
        buildEncryptionMaterialCacheKey,
        buildDecryptionMaterialCacheKey,
        encryptedDataKeysHash,
        encryptionContextHash,
    };
    async function buildEncryptionMaterialCacheKey(partition, { suite, encryptionContext }) {
        const algorithmInfo = suite
            ? [new Uint8Array([1]), (0, serialize_1.uInt16BE)(suite.id)]
            : [new Uint8Array([0])];
        const key = await sha512(await sha512(fromUtf8(partition)), ...algorithmInfo, await encryptionContextHash(encryptionContext));
        return toUtf8(key);
    }
    async function buildDecryptionMaterialCacheKey(partition, { suite, encryptedDataKeys, encryptionContext }) {
        const { id } = suite;
        const key = await sha512(await sha512(fromUtf8(partition)), (0, serialize_1.uInt16BE)(id), ...(await encryptedDataKeysHash(encryptedDataKeys)), BIT_PAD_512, await encryptionContextHash(encryptionContext));
        return toUtf8(key);
    }
    async function encryptedDataKeysHash(encryptedDataKeys) {
        const hashes = await Promise.all(encryptedDataKeys
            .map(serializeEncryptedDataKey)
            .map(async (edk) => sha512(edk)));
        return hashes.sort(portable_compare_1.compare);
    }
    async function encryptionContextHash(context) {
        /* The AAD section is uInt16BE(length) + AAD
         * see: https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/message-format.html#header-aad
         * However, the RAW Keyring wants _only_ the ADD.
         * So, I just slice off the length.
         */
        const serializedContext = serializeEncryptionContext(context).slice(2);
        return sha512(serializedContext);
    }
}
exports.buildCryptographicMaterialsCacheKeyHelp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