title: Node js encrypted video stream
body: <p>I'm trying to stream a video from a server to the client but have it encrypted in transit. </p>
  
  <p>Right now I'm not sure how to decrypt the stream before feeding in as the source code for a html video on the client.</p>
  
  <p>If I remove the <code>.pipe(encrypt)</code> the stream works, and I know that I need to unencrypt the data on the client, but I don't know how I can grab the pipe from the server, unencrypt it, and then use it as the src for a video.</p>
  
  <p>Server:</p>
  
  <pre><code>const express = require("express");
  const app = express();
  const fs = require("fs");
  const helmet = require("helmet");
  const crypto = require("crypto");
  const algorithm = "aes-256-ctr";
  const password = "d6F3Efeq";
  
  var encrypt = crypto.createCipher(algorithm, password);
  
  const port = process.env.PORT || 3000;
  app.use(helmet());
  app.use(express.static("public"));
  
  app.get("/stream", (req, res) =&gt; {
    console.log("Stream requested");
    const path =
      "/video.mp4";
    const stat = fs.statSync(path);
    const fileSize = stat.size;
    const range = req.headers.range;
    if (range) {
      const parts = range.replace(/bytes=/, "").split("-");
      const start = parseInt(parts[0], 10);
      const end = parts[1] ? parseInt(parts[1], 10) : fileSize - 1;
      const chunkSize = end - start + 1;
      const file = fs.createReadStream(path, { start, end });
      const head = {
        "Content-Range": `bytes ${start}-${end}/${fileSize}`,
        "Accept-Ranges": "bytes",
        "Content-Length": chunkSize,
        "Content-Type": "video/mp4",
      };
      res.writeHead(206, head);
      file.pipe(encrypt).pipe(res);
    } else {
      const head = {
        "Content-Length": fileSize,
        "COntent-Type": "video/mp4",
      };
      res.writeHead(200, head);
      fs.createReadStream(path).pipe(encrypt).pipe(res);
    }
  });
  
  app.listen(port, () =&gt; console.log(`Listening on port ${port}`));
  </code></pre>
  
  <p>Client html:</p>
  
  <pre><code>&lt;!DOCTYPE html&gt;
  &lt;html lang="en"&gt;
    &lt;head&gt;
      &lt;meta charset="UTF-8" /&gt;
      &lt;meta name="viewport" content="width=device-width, initial-scale=1.0" /&gt;
      &lt;title&gt;Stream&lt;/title&gt;
    &lt;/head&gt;
    &lt;body&gt;
      &lt;video src="./stream" controls&gt;&lt;/video&gt;
    &lt;/body&gt;
  &lt;/html&gt;
  </code></pre>