"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const types_1 = require("../types");
const NodeRSA = require("node-rsa");
const crypto_1 = require("crypto");
const buildRsaCryptoProvider_1 = require("./webCrypto/buildRsaCryptoProvider");
const legacyRSAOptions = {
    // Must use pkcs1 otherwise any data encrypted with NodeRSA will crash the
    // app when decrypted by RN-RSA.
    // https://github.com/amitaymolko/react-native-rsa-native/issues/66#issuecomment-932768139
    encryptionScheme: 'pkcs1',
    // Allows NodeRSA to work with pkcs1-v1.5 in newer NodeJS versions:
    environment: 'browser',
};
const legacyRsa = {
    generateKeyPair: async () => {
        const keys = new NodeRSA();
        keys.setOptions(legacyRSAOptions);
        const keySize = 2048;
        keys.generateKeyPair(keySize, 65537);
        // Sanity check
        if (!keys.isPrivate())
            throw new Error('No private key was generated');
        if (!keys.isPublic())
            throw new Error('No public key was generated');
        return { keyPair: keys, keySize };
    },
    loadKeys: async (publicKey, privateKey) => {
        const keys = new NodeRSA();
        keys.setOptions(legacyRSAOptions);
        // Don't specify the import format, and let it auto-detect because
        // react-native-rsa might not create a key in the expected format.
        keys.importKey(publicKey);
        if (privateKey)
            keys.importKey(privateKey);
        return keys;
    },
    // Unlimited, but probably not a good idea to encrypt a large amount of data (>=1 KiB).
    // Breaking input into blocks is handled by NodeRSA, but seems to use ECB mode.
    maximumPlaintextLengthBytes: null,
    encrypt: async (plaintextUtf8, rsaKeyPair) => {
        // eslint-disable-next-line @typescript-eslint/no-explicit-any -- Workaround for incorrect types after improving type safety
        return rsaKeyPair.encrypt(plaintextUtf8, 'buffer', 'utf8');
    },
    decrypt: async (ciphertext, rsaKeyPair) => {
        return rsaKeyPair.decrypt(ciphertext, 'utf8');
    },
    publicKey: async (rsaKeyPair) => {
        return rsaKeyPair.exportKey('pkcs1-public-pem');
    },
    privateKey: async (rsaKeyPair) => {
        return rsaKeyPair.exportKey('pkcs1-private-pem');
    },
};
const rsa = {
    [types_1.PublicKeyAlgorithm.Unknown]: null,
    [types_1.PublicKeyAlgorithm.RsaV1]: legacyRsa,
    [types_1.PublicKeyAlgorithm.RsaV2]: (0, buildRsaCryptoProvider_1.default)(types_1.PublicKeyAlgorithm.RsaV2, crypto_1.webcrypto),
    [types_1.PublicKeyAlgorithm.RsaV3]: (0, buildRsaCryptoProvider_1.default)(types_1.PublicKeyAlgorithm.RsaV3, crypto_1.webcrypto),
};
exports.default = rsa;
//# sourceMappingURL=RSA.node.js.map