简体   繁体   中英

Encrypt the uploaded file before saving to disk using Node.js

Currently, I am using multer library to save files on File system. This application is using Node and Express .

I can save the file first on server and then encrypt it. Later on delete the unencrypted file. However, I do not want to add unencrypted file on server directly. So, I am looking for a way to encrypt the incoming file from the front end and then save it to disk.

const defaultFolder = 'upload';
const filePath = resolveHome(process.env.FILE_STORAGE_LOCATION || defaultFolder);
const key = 'test';
const cipher = crypto.createCipher('aes-256-cbc', key);
const decipher = crypto.createDecipher('aes-256-cbc', key);

const upload = multer({
    storage: multer.diskStorage({
        destination: filePath,
        filename: (req, file, cb) => {
            const parts = file.originalname.split('.');
            const ext = parts.pop();
            const name = parts.join('.');
            cb(null, name + '-' + Date.now() + '.' + ext);
        },
    }),
}).single('file');

app.post('/upload', (req, res) => {
    upload(req, res, err => {
        if (err) {
            return res.status(400).send({
                error: 'The request was invalid',
                fileName: req.file.originalname,
            });
        }
        return res.status(200).send({
            fileName: req.file.filename,
        });
    });
});

I tried to use crypto library to encrypt the file but it's not working. I believe the req.cipher is invalid as I would normally use req.file to get reference to the file.

app.post('/upload', (req, res) => {
    upload(req, res, err => {
        output = fs.createWriteStream(filePath + '/' + req.file.originalname);
        req.pipe(cipher).pipe(output).on('finish', () => console.log('Encrypted file written on disk'));
        if (err) {
            return res.status(400).send({
                error: 'The request was invalid',
                fileName: req.file.originalname,
            });
        }
        return res.status(200).send({
            fileName: req.file.originalname,
        });
    });
});

I had tried to just write file without using cipher and file was empty. Adding this information in case it helps.

req.pipe(output).on('finish', () => console.log('Encrypted file written on disk'));

Can you try this

app.post('/upload', function(req, res) {
    upload(req, res, function(err) {
        var fileName = req.file.destination +"\\"+ req.file.filename
        var input = fs.createReadStream(fileName);
        var output = fs.createWriteStream(fileName + ".enc");
        input.pipe(cipher).pipe(output);
        output.on('finish', function() {
            fs.unlink(fileName, (err) => {
                if (err) throw err;
                console.log('Encrypted  file written to disk!');
                res.end('Encrypted  file written to disk!')
            });

        });
    })
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM