Search code examples
node.jsencryptionnode-streamsnodejs-streamnode-crypto

How to encrypt a stream in node js


How to encrypt and decrypt a stream in node js without saving the file locally or converting it into buffer. if there is no way then pls provide memory efficient and less storage consuming way to encrypt and decrypt stream in node js so that i can directly upload stream to google drive through api .


Solution

  • Finally i got solution to this question . I am posting the answer here for everyone who need this
    I am using a library called aes-encrypt-stream
    or you can use crpto library as well or any other. Here

    use stream.PassThrough
    Here file.stream is my input stream
    stream is my outputstream
    From this code i am able to reduce memory consumption of server for encryption

    const { createEncryptStream, createDecryptStream, setPassword } = require('aes-encrypt-stream');
    setPassword(Buffer.from('your key here', 'hex'));
    PassThroughStream = require('stream').PassThrough,
    stream = new PassThroughStream();
    await createEncryptStream(file.stream).pipe(stream);
    

    now stream is encrypted