"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 sorting = { utf8Sorting: true };
    const { serializeEncryptionContext, serializeEncryptedDataKey } = (0, serialize_1.serializeFactory)(fromUtf8, sorting);
    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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