"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createEncryptionSession = createEncryptionSession;
exports.encryptValueWithSession = encryptValueWithSession;
exports.encryptValue = encryptValue;
const crypto_1 = require("crypto");
function deriveKey(sharedSecret) {
    return (0, crypto_1.createHash)('sha256').update(sharedSecret).digest();
}
function createEncryptionSession(publicKey) {
    const recipientPublicKey = Buffer.from(publicKey, 'hex');
    const ecdh = (0, crypto_1.createECDH)('prime256v1');
    ecdh.generateKeys();
    const ephemeralPublicKey = ecdh.getPublicKey(null, 'uncompressed');
    const sharedSecret = ecdh.computeSecret(recipientPublicKey);
    const derivedKey = deriveKey(sharedSecret);
    return { ephemeralPublicKey, derivedKey };
}
function encryptValueWithSession(value, session) {
    try {
        const stringValue = value === undefined ? 'null' : JSON.stringify(value);
        const { ephemeralPublicKey, derivedKey } = session;
        const iv = (0, crypto_1.randomBytes)(16);
        const cipher = (0, crypto_1.createCipheriv)('aes-256-gcm', derivedKey, iv);
        let encrypted = cipher.update(stringValue, 'utf8');
        encrypted = Buffer.concat([encrypted, cipher.final()]);
        const authTag = cipher.getAuthTag();
        const version = Buffer.from([0x00]);
        const resultBuffer = Buffer.concat([version, ephemeralPublicKey, iv, authTag, encrypted]);
        return resultBuffer.toString('base64');
    }
    catch (error) {
        throw new Error(`Failed to encrypt value. Please check that the public key is valid. Error: ${error instanceof Error ? error.message : String(error)}`);
    }
}
function encryptValue(value, publicKey) {
    return encryptValueWithSession(value, createEncryptionSession(publicKey));
}
//# sourceMappingURL=encryption-functions.js.map