Search code examples
node.jsexpressmulter

How to encrypt file using express multer


By having these simple few lines of code I've got file saved on server.

router.post('/upload',  upload.single('file'), function(req: Request, res: Response, next: Function) {
    console.log(req.file);
    res.json({ success: true, message: 'Uploaded' });
});

I want to encrypt the file before it is get saved.

Is there any way I can do that?


Solution

  • One way for encrypting files is with Buffers using multer's memoryStorage() and Node.js built-in crypto library.

    import multer from 'multer'
    import { scryptSync, createCipheriv } from 'crypto'
    import { mkdirSync, existsSync, writeFileSync } from 'fs'
    
    const upload = multer({ storage: multer.memoryStorage() })
    
    const encrypt = (buffer) => {
      // More info: https://nodejs.org/api/crypto.html
      const algorithm = 'aes-192-cbc'
      const iv = Buffer.alloc(16, 0)
      const key = scryptSync('super strong password', 'salt', 24)
    
      const cipher = createCipheriv(algorithm, key, iv)
      return Buffer.concat([cipher.update(buffer), cipher.final()])
    }
    
    const saveEncryptedFile = (buffer, filePath) => {
      if (!existsSync(path.dirname(filePath))) {
        mkdirSync(path.dirname(filePath))
      }
      writeFileSync(filePath, encrypt(buffer))
    }
    
    router.post('/upload', upload.single('file'), ({ file }, res, next) => {
      saveEncryptedFile(file.buffer, './your-file-path')
    })