openpgp.createMessage returns 2 promises in ReadStream; resulting in duplicate PGP armored encrypted files

34 Views Asked by At

With Below function, using OpenPGP.js, console.log(testMessage) produces 2 promises

As such, the output from fileWriteStream produces PGP armored files which are duplicated/concatenated. Can someone solve this?


async function encryptFile(inputFilePath, publicKeyFilePath, outputFilePath) {
    try {
        const publicKey = await readPublicKeyFromFile(publicKeyFilePath);
        const fileReadStream = createReadStream(inputFilePath);
        const fileWriteStream = createWriteStream(outputFilePath);
              
        fileReadStream.on('data', async (chunk) => {

            const testMessage = openpgp.createMessage({ binary: chunk });
            console.log(testMessage);

            const encryptedData = await openpgp.encrypt({
                message: await openpgp.createMessage({ binary: chunk }),
                encryptionKeys: publicKey,
                format: 'armored',
                //encryptionUserIDs: [{ name: 'test', email: '[email protected]'}],
            });

            fileWriteStream.write(encryptedData);
        });
        
        fileReadStream.on('end', () => {
            fileWriteStream.end();
            console.log('File encrypted and written to another file successfully!');
        });
        
        fileReadStream.on('error', (error) => {
            console.error('Error reading file:', error);
        });
      
        fileWriteStream.on('error', (error) => {
            console.error('Error writing file:', error);
        });

    } catch (error) {
        console.error('Error encrypting file:', error);
    }   
}


// Usage
const publicKeyFilePath = 'public.asc'; // Replace with the path to your public key file
encryptFile(filePath, publicKeyFilePath, outputPath);

Expecting only 1 promise return. Instead PGP returns the following:

-----BEGIN PGP MESSAGE-----
wcDMA4njtiqlWjiyAQwAs3bnqAGqBIGr6w7InsIMOiBSCx0wNLgENOnZlrA+...bIlsX1wRR1wLb+/KTe8Djzn5eR5Lvhfh=usvc-----END PGP MESSAGE----------BEGIN PGP MESSAGE-----
wcDMA4njtiqlWjiyAQv/VWAUmagaFPQMmUWSt24oeFl1vCWv/KNr4fngcK3x.....ZYiN/RuXK4hMDBTclrqnEcfFR5eOk-----END PGP MESSAGE-----
0

There are 0 best solutions below